f4c90eb5850008fc5b584a9330c710c943d63d7e
[mailer.git] / inc / libs / surfbar_functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 08/31/2008 *
4  * ===============                              Last change: 08/31/2008 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : surfbar_functions.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for surfbar                            *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer die Surfbar                      *
12  * -------------------------------------------------------------------- *
13  *                                                                      *
14  * -------------------------------------------------------------------- *
15  * Copyright (c) 2003 - 2008 by Roland Haeder                           *
16  * For more information visit: http://www.mxchange.org                  *
17  *                                                                      *
18  * This program is free software; you can redistribute it and/or modify *
19  * it under the terms of the GNU General Public License as published by *
20  * the Free Software Foundation; either version 2 of the License, or    *
21  * (at your option) any later version.                                  *
22  *                                                                      *
23  * This program is distributed in the hope that it will be useful,      *
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
26  * GNU General Public License for more details.                         *
27  *                                                                      *
28  * You should have received a copy of the GNU General Public License    *
29  * along with this program; if not, write to the Free Software          *
30  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
31  * MA  02110-1301  USA                                                  *
32  ************************************************************************/
33
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
37         require($INC);
38 }
39
40 // -----------------------------------------------------------------------------
41 //                               Admin functions
42 // -----------------------------------------------------------------------------
43
44 // Admin has added an URL with given user id and so on
45 function SURFBAR_ADMIN_ADD_URL ($url) {
46         // Do some pre-checks
47         if (!IS_ADMIN()) {
48                 // Not an admin
49                 return false;
50         } elseif (!VALIDATE_URL($url)) {
51                 // URL invalid
52                 return false;
53         } elseif (SURFBAR_LOOKUP_BY_URL($url, "0")) {
54                 // URL already found in surfbar!
55                 return false;
56         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS()) {
57                 // No more allowed!
58                 return false;
59         }
60
61         // Do we have fixed or dynamic payment model?
62         $reward = SURFBAR_DETERMINE_REWARD();
63         $costs  = SURFBAR_DETERMINE_COSTS();
64
65         // Register the new URL
66         return SURFBAR_REGISTER_URL($url, "0", $reward, $costs, "0", "CONFIRMED", "unlock");
67 }
68 // Admin function for unlocking URLs
69 function SURFBAR_ADMIN_UNLOCK_URL_IDS ($IDs) {
70         // Is this an admin or invalid array?
71         if (!IS_ADMIN()) {
72                 // Not admin or invalid IDs array
73                 return false;
74         } elseif (!is_array($IDs)) {
75                 // No array
76                 return false;
77         } elseif (count($IDs) == 0) {
78                 // Empty array
79                 return false;
80         }
81
82         // Set to true to make AND expression valid if first URL got unlocked
83         $done = true;
84
85         // Update the status for all ids
86         foreach ($IDs as $id => $dummy) {
87                 // Test all ids through (ignores failed)
88                 $done = (($done) && (SURFBAR_CHANGE_STATUS($id, "PENDING", "CONFIRMED")));
89         } // END - if
90
91         // Return total status
92         return $done;
93 }
94
95 // -----------------------------------------------------------------------------
96 //                               Member functions
97 // -----------------------------------------------------------------------------
98
99 // Member has added an URL
100 function SURFBAR_MEMBER_ADD_URL ($url) {
101         global $_CONFIG;
102
103         // Do some pre-checks
104         if (!IS_MEMBER()) {
105                 // Not a member
106                 return false;
107         } elseif (!VALIDATE_URL($url)) {
108                 // URL invalid
109                 return false;
110         } elseif (SURFBAR_LOOKUP_BY_URL($url, $GLOBALS['userid'])) {
111                 // URL already found in surfbar!
112                 return false;
113         } elseif (!SURFBAR_IF_USER_BOOK_MORE_URLS($GLOBALS['userid'])) {
114                 // No more allowed!
115                 return false;
116         }
117
118         // Do we have fixed or dynamic payment model?
119         $reward = SURFBAR_DETERMINE_REWARD();
120         $costs  = SURFBAR_DETERMINE_COSTS();
121
122         // Register the new URL
123         return SURFBAR_REGISTER_URL($url, $GLOBALS['userid'], $reward, $costs);
124 }
125 // -----------------------------------------------------------------------------
126 //                               Generic functions
127 // -----------------------------------------------------------------------------
128
129 // Looks up by an URL
130 function SURFBAR_LOOKUP_BY_URL ($url) {
131         // Now lookup that given URL by itself
132         $urlArray = SURFBAR_GET_URL_DATA($url, "url");
133
134         // Was it found?
135         return (count($urlArray) > 0);
136 }
137 // Load URL data by given search term and column
138 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id") {
139         global $lastUrlData;
140
141         // By default nothing is found
142         $lastUrlData = array();
143
144         // Is the column an id number?
145         if (($column == "id") || ($column == "userid")) {
146                 // Extra secure input
147                 $searchTerm = bigintval($searchTerm);
148         } // END - if
149
150         // If the column is "id" there can be only one entry
151         $limit = "";
152         if ($column == "id") {
153                 $limit = "LIMIT 1";
154         } // END - if
155
156         // Look up the record
157         $result = SQL_QUERY_ESC("SELECT id, userid, url, reward, costs, views_total, status, registered, last_locked, lock_reason
158 FROM "._MYSQL_PREFIX."_surfbar_urls
159 WHERE %s='%s'
160 ORDER BY %s %s
161 %s",
162                 array($column, $searchTerm, $order, $sort, $limit), __FILE__, __LINE__);
163
164         // Is there at least one record?
165         if (SQL_NUMROWS($result) > 0) {
166                 // Then load all!
167                 while ($dataRow = SQL_FETCHARRAY($result)) {
168                         // Shall we group these results?
169                         if ($group == "id") {
170                                 // Add the row by id as index
171                                 $lastUrlData[$dataRow['id']] = $dataRow;
172                         } else {
173                                 // Group entries
174                                 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
175                         }
176                 } // END - while
177         } // END - if
178
179         // Free the result
180         SQL_FREERESULT($result);
181
182         // Return the result
183         return $lastUrlData;
184 }
185 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
186 function SURFBAR_REGISTER_URL ($url, $uid, $reward, $costs, $paymentId=0, $status="PENDING", $addMode="reg") {
187         global $_CONFIG;
188
189         // Make sure by the user registered URLs are always pending
190         if ($addMode == "reg") $status = "PENDING";
191
192         // Prepare content
193         $content = array(
194                 'url'         => $url,
195                 'frametester' => FRAMETESTER($url),
196                 'uid'         => $uid,
197                 'reward'      => $reward,
198                 'costs'       => $costs,
199                 'status'      => $status
200         );
201
202         // Insert the URL into database
203         $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
204
205         // Translate status, reward and costs
206         $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
207         $content['reward'] = TRANSLATE_COMMA($content['reward']);
208         $content['costs']  = TRANSLATE_COMMA($content['costs']);
209
210         // If in reg-mode we notify admin
211         if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
212                 // Notify admin even when he as unlocked an email
213                 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
214         } // END - if
215
216         // Send mail to user
217         SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
218
219         // Return the insert id
220         return $content['insert_id'];
221 }
222 // Inserts an url by given data array and return the insert id
223 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
224         // Get userid
225         $uid = bigintval($urlData['uid']);
226
227         // Is the id set?
228         if (empty($uid)) $uid = 0;
229
230         // Just run the insert query for now
231         SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid, url, reward, costs, status) VALUES('%s', '%s', %s, %s, '%s')",
232                 array(
233                         $uid,
234                         $urlData['url'],
235                         (float)$urlData['reward'],
236                         (float)$urlData['costs'],
237                         $urlData['status']
238                 ), __FILE__, __LINE__
239         );
240
241         // Return insert id
242         return SQL_INSERTID();
243 }
244 // Notify admin(s) with a selected message and content
245 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
246         // Prepare template name
247         $templateName = sprintf("admin_surfbar_%s", $messageType);
248
249         // Prepare subject
250         $eval = sprintf("\$subject = ADMIN_SURFBAR_NOTIFY_%s_SUBJECT;",
251                 strtoupper($messageType)
252         );
253         eval($eval);
254
255         // Send the notification out
256         return SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
257 }
258 // Notify the user about the performed action
259 function SURFBAR_NOTIFY_USER ($messageType, $content) {
260         // Skip notification if userid is zero
261         if ($content['uid'] == 0) {
262                 return false;
263         } // END - if
264
265         // Prepare template name
266         $templateName = sprintf("member_surfbar_%s", $messageType);
267
268         // Prepare subject
269         $eval = sprintf("\$subject = MEMBER_SURFBAR_NOTIFY_%s_SUBJECT;",
270                 strtoupper($messageType)
271         );
272         eval($eval);
273
274         // Load template
275         $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content);
276
277         // Send the email
278         return SEND_EMAIL($content['uid'], $subject, $mailText);
279 }
280 // Translate the URL status
281 function SURFBAR_TRANSLATE_STATUS ($status) {
282         // Create constant name
283         $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
284
285         // Set default translated status
286         $statusTranslated = "!".$constantName."!";
287
288         // Generate eval() command
289         if (defined($constantName)) {
290                 $eval = "\$statusTranslated = ".$constantName.";";
291                 eval($eval);
292         } // END - if
293
294         // Return result
295         return $statusTranslated;
296 }
297 // Determine reward
298 function SURFBAR_DETERMINE_REWARD () {
299         global $_CONFIG;
300
301         // Static values are default
302         $reward = $_CONFIG['surfbar_static_reward'];
303
304         // Do we have static or dynamic?
305         if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
306                 // "Calculate" dynamic reward
307                 $reward += SURFBAR_CALCULATE_DYNAMIC_ADD();
308         } // END - if
309
310         // Return reward
311         return $reward;
312 }
313 // "Calculate" dynamic add
314 function SURFBAR_CALCULATE_DYNAMIC_ADD () {
315         // Get min/max values
316         $min = SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE();
317         $max = SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE();
318
319         // "Calculate" dynamic part and return it
320         return mt_rand($min, $max);
321 }
322 // Determine costs
323 function SURFBAR_DETERMINE_COSTS () {
324         global $_CONFIG;
325
326         // Static costs is default
327         $costs  = $_CONFIG['surfbar_static_costs'];
328
329         // Do we have static or dynamic?
330         if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
331                 // "Calculate" dynamic costs
332                 $costs += SURFBAR_CALCULATE_DYNAMIC_ADD();
333         } // END - if
334
335         // Return costs
336         return $costs;
337 }
338 // Determine right template name
339 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
340         // Default is the frameset
341         $templateName = "surfbar_frameset";
342
343         // Any frame set? ;-)
344         if (isset($_GET['frame'])) {
345                 // Use the frame as a template name part... ;-)
346                 $templateName = sprintf("surfbar_frame_%s",
347                         SQL_ESCAPE($_GET['frame'])
348                 );
349         } // END - if
350
351         // Return result
352         return $templateName;
353 }
354 // Check if the "reload lock" of the current user is full, call this function
355 // before you call SURFBAR_CHECK_RELOAD_LOCK().
356 function SURFBAR_CHECK_RELOAD_FULL() {
357         global $SURFBAR_CACHE, $_CONFIG;
358
359         // Default is full!
360         $isFull = true;
361
362         // Cache static reload lock
363         $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
364         //DEBUG_LOG(__FUNCTION__.":Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."");
365
366         // Do we have dynamic model?
367         if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
368                 // "Calculate" dynamic lock
369                 $SURFBAR_CACHE['surf_lock'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
370         } // END - if
371
372         // Ask the database
373         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
374 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
375 LIMIT 1",
376                 array($GLOBALS['userid']), __FILE__, __LINE__
377         );
378
379         // Fetch row
380         list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
381
382         // Is it null?
383         if (is_null($SURFBAR_CACHE['user_locks'])) {
384                 // Then fix it to zero!
385                 $SURFBAR_CACHE['user_locks'] = 0;
386         } // END - if
387
388         // Free result
389         SQL_FREERESULT($result);
390
391         // Get total URLs
392         $total = SURFBAR_GET_TOTAL_URLS();
393
394         // Do we have some URLs in lock? Admins can always surf on own URLs!
395         //DEBUG_LOG(__FUNCTION__.":userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}");
396         $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
397
398         // Return result
399         return $isFull;
400 }
401 // Get total amount of URLs of given status for current user or of CONFIRMED URLs by default
402 function SURFBAR_GET_TOTAL_URLS ($status="CONFIRMED", $excludeUserId="") {
403         // Determine depleted user account
404         $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
405
406         // Is the exlude userid set?
407         if ($excludeUserId !== "") {
408                 // Then add it
409                 $UIDs[] = $excludeUserId;
410         } // END - if
411
412         // Get amount from database
413         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
414 FROM "._MYSQL_PREFIX."_surfbar_urls
415 WHERE userid NOT IN (".implode(",", $UIDs).") AND status='%s'",
416                 array($status), __FILE__, __LINE__
417         );
418
419         // Fetch row
420         list($cnt) = SQL_FETCHROW($result);
421
422         // Free result
423         SQL_FREERESULT($result);
424
425         // Return result
426         return $cnt;
427 }
428 // Check wether the user is allowed to book more URLs
429 function SURFBAR_IF_USER_BOOK_MORE_URLS ($uid=0) {
430         global $_CONFIG;
431
432         // Is this admin and userid is zero or does the user has some URLs left to book?
433         return ((($uid == 0) && (IS_ADMIN())) || (SURFBAR_GET_TOTAL_USER_URLS($uid, "", array("REJECTED")) < $_CONFIG['surfbar_max_order']));
434 }
435 // Get total amount of URLs of given status for current user
436 function SURFBAR_GET_TOTAL_USER_URLS ($uid=0, $status="",$exclude="") {
437         global $_CONFIG;
438
439         // Is the user 0 and user is logged in?
440         if (($uid == 0) && (IS_MEMBER())) {
441                 // Then use this userid
442                 $uid = $GLOBALS['userid'];
443         } elseif ($uid == 0) {
444                 // Error!
445                 return ($_CONFIG['surfbar_max_order'] + 1);
446         }
447
448         // Default is all URLs
449         $ADD = "";
450
451         // Is the status set?
452         if (is_array($status)) {
453                 // Only URLs with these status
454                 $ADD = sprintf(" AND status IN('%s')", implode("','", $status));
455         } elseif (!empty($status)) {
456                 // Only URLs with this status
457                 $ADD = sprintf(" AND status='%s'", $status);
458         } elseif (is_array($exclude)) {
459                 // Exclude URLs with these status
460                 $ADD = sprintf(" AND status NOT IN('%s')", implode("','", $exclude));
461         } elseif (!empty($exclude)) {
462                 // Exclude URLs with this status
463                 $ADD = sprintf(" AND status != '%s'", $exclude);
464         }
465
466         // Get amount from database
467         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
468 FROM "._MYSQL_PREFIX."_surfbar_urls
469 WHERE userid=%s".$ADD."
470 LIMIT %s",
471                 array($uid, $_CONFIG['surfbar_max_order']), __FILE__, __LINE__
472         );
473
474         // Fetch row
475         list($cnt) = SQL_FETCHROW($result);
476
477         // Free result
478         SQL_FREERESULT($result);
479
480         // Return result
481         return $cnt;
482 }
483 // Generate a validation code for the given id number
484 function SURFBAR_GENERATE_VALIDATION_CODE ($id, $salt="") {
485         global $_CONFIG, $SURFBAR_CACHE;
486
487         // @TODO Invalid salt should be refused
488         $SURFBAR_CACHE['salt'] = "INVALID";
489
490         // Get code length from config
491         $length = $_CONFIG['code_length'];
492
493         // Fix length to 10
494         if ($length == 0) $length = 10;
495
496         // Generate a code until the length matches
497         $valCode = "";
498         while (strlen($valCode) != $length) {
499                 // Is the salt set?
500                 if (empty($salt)) {
501                         // Generate random hashed string
502                         $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
503                         //DEBUG_LOG(__FUNCTION__.":newSalt=".SURFBAR_GET_SALT()."");
504                 } else {
505                         // Use this as salt!
506                         $SURFBAR_CACHE['salt'] = $salt;
507                         //DEBUG_LOG(__FUNCTION__.":oldSalt=".SURFBAR_GET_SALT()."");
508                 }
509
510                 // ... and now the validation code
511                 $valCode = GEN_RANDOM_CODE($length, sha1(SURFBAR_GET_SALT().":".$id), $GLOBALS['userid']);
512                 //DEBUG_LOG(__FUNCTION__.":valCode={$valCode}");
513         } // END - while
514
515         // Hash it with md5() and salt it with the random string
516         $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
517
518         // Finally encrypt it PGP-like and return it
519         $valHashedCode = generatePassString($hashedCode);
520         //DEBUG_LOG(__FUNCTION__.":finalValCode={$valHashedCode}");
521         return $valHashedCode;
522 }
523 // Check validation code
524 function SURFBAR_CHECK_VALIDATION_CODE ($id, $check, $salt) {
525         global $SURFBAR_CACHE;
526
527         // Secure id number
528         $id = bigintval($id);
529
530         // Now generate the code again
531         $code = SURFBAR_GENERATE_VALIDATION_CODE($id, $salt);
532
533         // Return result of checking hashes and salts
534         //DEBUG_LOG(__FUNCTION__.":---".$code."|".$check."---");
535         //DEBUG_LOG(__FUNCTION__.":+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++");
536         return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
537 }
538 // Lockdown the userid/id combination (reload lock)
539 function SURFBAR_LOCKDOWN_ID ($id) {
540         //* //DEBUG: */ print "LOCK!");
541         ///* //DEBUG: */ return;
542         // Just add it to the database
543         SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
544                 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__);
545
546         // Remove the salt from database
547         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
548                 array(bigintval($id), $GLOBALS['userid']), __FILE__, __LINE__);
549 }
550 // Pay points to the user and remove it from the sender
551 function SURFBAR_PAY_POINTS ($id) {
552         // Remove it from the URL owner
553         //DEBUG_LOG(__FUNCTION__.":uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."");
554         if (SURFBAR_GET_USERID() > 0) {
555                 SUB_POINTS(SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
556         } // END - if
557
558         // Book it to the user
559         //DEBUG_LOG(__FUNCTION__.":uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."");
560         ADD_POINTS_REFSYSTEM($GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
561 }
562 // Updates the statistics of current URL/userid
563 function SURFBAR_UPDATE_INSERT_STATS_RECORD () {
564         global $_CONFIG;
565
566         // Update views_total
567         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1 WHERE id=%s LIMIT 1",
568                 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
569
570         // Update the stats entry
571         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_stats SET count=count+1 WHERE userid=%s AND url_id=%s LIMIT 1",
572                 array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
573
574         // Was that update okay?
575         if (SQL_AFFECTEDROWS() == 0) {
576                 // No, then insert entry
577                 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_stats (userid,url_id,count) VALUES(%s,%s,1)",
578                         array($GLOBALS['userid'], SURFBAR_GET_ID()), __FILE__, __LINE__);
579         } // END - if
580
581         // Update total/daily/weekly/monthly counter
582         $_CONFIG['surfbar_total_counter']++;
583         $_CONFIG['surfbar_daily_counter']++;
584         $_CONFIG['surfbar_weekly_counter']++;
585         $_CONFIG['surfbar_monthly_counter']++;
586
587         // Update config as well
588         UPDATE_CONFIG(array("surfbar_total_counter", "surfbar_daily_counter", "surfbar_weekly_counter", "surfbar_monthly_counter"), array(1,1,1,1), "+");
589 }
590 // Update the salt for validation and statistics
591 function SURFBAR_UPDATE_SALT_STATS () {
592         // Update statistics record
593         SURFBAR_UPDATE_INSERT_STATS_RECORD();
594
595         // Simply store the salt from cache away in database...
596         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
597                 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
598
599         // Debug message
600         //DEBUG_LOG(__FUNCTION__.":salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."");
601
602         // Was that okay?
603         if (SQL_AFFECTEDROWS() == 0) {
604                 // Insert missing entry!
605                 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES(%s, %s, '%s')",
606                         array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
607         } // END - if
608
609         // Debug message
610         //DEBUG_LOG(__FUNCTION__.":affectedRows=".SQL_AFFECTEDROWS()."");
611
612         // Return if the update was okay
613         return (SQL_AFFECTEDROWS() == 1);
614 }
615 // Check if the reload lock is active for given id
616 function SURFBAR_CHECK_RELOAD_LOCK ($id) {
617         //DEBUG_LOG(__FUNCTION__.":id={$id}");
618         // Ask the database
619         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
620 FROM "._MYSQL_PREFIX."_surfbar_locks
621 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
622 ORDER BY last_surfed ASC
623 LIMIT 1",
624                 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
625         );
626
627         // Fetch counter
628         list($cnt) = SQL_FETCHROW($result);
629
630         // Free result
631         SQL_FREERESULT($result);
632
633         // Return check
634         //DEBUG_LOG(__FUNCTION__.":cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."");
635         return ($cnt == 1);
636 }
637 // Determine which user hash no more points left
638 function SURFBAR_DETERMINE_DEPLETED_USERIDS() {
639         // Init array
640         $UIDs = array();
641
642         // Do we have a current user id?
643         if (IS_MEMBER()) {
644                 // Then add this as well
645                 $UIDs[] = $GLOBALS['userid'];
646
647                 // Get all userid except logged in one
648                 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
649 WHERE userid NOT IN (%s,0) AND status='CONFIRMED'
650 GROUP BY userid
651 ORDER BY userid ASC",
652                         array($GLOBALS['userid']), __FILE__, __LINE__);
653         } else {
654                 // Get all userid
655                 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
656 WHERE status='CONFIRMED'
657 GROUP BY userid
658 ORDER BY userid ASC", __FILE__, __LINE__);
659         }
660
661         // Load all userid
662         while (list($uid) = SQL_FETCHROW($result)) {
663                 // Get total points
664                 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
665                 //DEBUG_LOG(__FUNCTION__.":uid={$uid},points={$points}");
666
667                 // Shall we add this to ignore?
668                 if ($points <= 0) {
669                         // Ignore this one!
670                         //DEBUG_LOG(__FUNCTION__.":uid={$uid} has depleted points amount!");
671                         $UIDs[] = $uid;
672                 } // END - if
673         } // END - while
674
675         // Free result
676         SQL_FREERESULT($result);
677
678         // Debug message
679         //DEBUG_LOG(__FUNCTION__.":UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")");
680
681         // Return result
682         return $UIDs;
683 }
684 // Determine how many users are Online in surfbar
685 function SURFBAR_DETERMINE_TOTAL_ONLINE () {
686         global $_CONFIG;
687
688         // Count all users in surfbar modue and return the value
689         $result = SQL_QUERY_ESC("SELECT id
690 FROM "._MYSQL_PREFIX."_surfbar_stats
691 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_online)) <= %s
692 GROUP BY userid",
693                 array($_CONFIG['online_timeout']), __FILE__, __LINE__);
694
695         // Fetch count
696         $cnt = SQL_NUMROWS($result);
697
698         // Free result
699         SQL_FREERESULT($result);
700
701         // Return result
702         return $cnt;
703 }
704 // Determine waiting time for one URL 
705 function SURFBAR_DETERMINE_WAIT_TIME () {
706         global $_CONFIG;
707
708         // Static time is default
709         $time = $_CONFIG['surfbar_static_time'];
710
711         // Which payment model do we have?
712         if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
713                 // "Calculate" dynamic time
714                 $time += SURFBAR_CALCULATE_DYNAMIC_ADD();
715         } // END - if
716
717         // Return value
718         return $time;
719 }
720 // Changes the status of an URL from given to other
721 function SURFBAR_CHANGE_STATUS ($id, $prevStatus, $newStatus) {
722         // Get URL data for status comparison
723         $data = SURFBAR_GET_URL_DATA($id);
724
725         // Is the status like prevStatus is saying?
726         if ($data[$id]['status'] != $prevStatus) {
727                 // No, then abort here
728                 return false;
729         } // END - if
730
731         // Update the status now
732         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET status='%s' WHERE id=%s LIMIT 1",
733                 array($newStatus, bigintval($id)), __FILE__, __LINE__);
734
735         // Was that fine?
736         if (SQL_AFFECTEDROWS() != 1) {
737                 // No, something went wrong
738                 return false;
739         } // END - if
740
741         // Prepare content for notification routines
742         $data[$id]['uid']         = $data[$id]['userid'];
743         $data[$id]['frametester'] = FRAMETESTER($data[$id]['url']);
744         $data[$id]['reward']      = TRANSLATE_COMMA($data[$id]['reward']);
745         $data[$id]['costs']       = TRANSLATE_COMMA($data[$id]['costs']);
746         $data[$id]['status']      = SURFBAR_TRANSLATE_STATUS($newStatus);
747         $data[$id]['registered']  = MAKE_DATETIME($data[$id]['registered'], "2");
748         $newStatus = strtolower($newStatus);
749
750         // Send admin notification
751         SURFBAR_NOTIFY_ADMIN("url_{$newStatus}", $data[$id]);
752
753         // Send user notification
754         SURFBAR_NOTIFY_USER("url_{$newStatus}", $data[$id]);
755
756         // All done!
757         return true;
758 }
759 // Calculate minimum value for dynamic payment model
760 function SURFBAR_CALCULATE_DYNAMIC_MIN_VALUE () {
761         global $_CONFIG;
762
763         // Addon is zero by default
764         $addon = 0;
765
766         // Percentage part
767         $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
768
769         // Get total users
770         $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
771
772         // Get online users
773         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
774
775         // Calculate addon
776         $addon += abs(log($onlineUsers / $totalUsers + 1) * $percent * $totalUsers);
777
778         // Get total URLs
779         $totalUrls = SURFBAR_GET_TOTAL_URLS("CONFIRMED", "0");
780
781         // Get user's total URLs
782         $userUrls = SURFBAR_GET_TOTAL_USER_URLS(0, "CONFIRMED");
783
784         // Calculate addon
785         if ($totalUrls > 0) {
786                 $addon += abs(log($userUrls / $totalUrls + 1) * $percent * $totalUrls);
787         } else {
788                 $addon += abs(log($userUrls / 1 + 1) * $percent * $totalUrls);
789         }
790
791         // Return addon
792         return $addon;
793 }
794 // Calculate maximum value for dynamic payment model
795 function SURFBAR_CALCULATE_DYNAMIC_MAX_VALUE () {
796         global $_CONFIG;
797
798         // Addon is zero by default
799         $addon = 0;
800
801         // Maximum value
802         $max = log(2);
803
804         // Percentage part
805         $percent = abs(log($_CONFIG['surfbar_dynamic_percent'] / 100 + 1));
806
807         // Get total users
808         $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true);
809
810         // Calculate addon
811         $addon += abs($max * $percent * $totalUsers);
812
813         // Get total URLs
814         $totalUrls = SURFBAR_GET_TOTAL_URLS("CONFIRMED", "0");
815
816         // Calculate addon
817         $addon += abs($max * $percent * $totalUrls);
818
819         // Return addon
820         return $addon;
821 }
822 // Calculate dynamic lock
823 function SURFBAR_CALCULATE_DYNAMIC_LOCK () {
824         global $_CONFIG;
825
826         // Default lock is 30 seconds
827         $addon = 30;
828
829         // Get online users
830         $onlineUsers = SURFBAR_DETERMINE_TOTAL_ONLINE();
831
832         // Calculate lock
833         $addon = abs(log($onlineUsers / $addon + 1));
834
835         // Return value
836         return $addon;
837 }
838 // "Getter" for lock ids array
839 function SURFBAR_GET_LOCK_IDS () {
840         // Prepare some arrays
841         $IDs = array();
842         $USE = array();
843         $ignored = array();
844
845         // Get all id from locks within the timestamp
846         $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed) AS last
847 FROM
848         "._MYSQL_PREFIX."_surfbar_locks
849 WHERE
850         userid=%s
851 ORDER BY
852         id ASC", array($GLOBALS['userid']),
853                 __FILE__, __LINE__);
854
855         // Load all entries
856         while (list($lid, $url, $last) = SQL_FETCHROW($result)) {
857                 // Debug message
858                 //DEBUG_LOG(__FUNCTION__.":next - lid={$lid},url={$url},rest=".(time() - $last)."/".SURFBAR_GET_DATA('surf_lock')."");
859
860                 // Skip entries that are too old
861                 if (($last > (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
862                         // Debug message
863                         //DEBUG_LOG(__FUNCTION__.":okay - lid={$lid},url={$url},last={$last}");
864
865                         // Add only if missing or bigger
866                         if ((!isset($IDs[$url])) || ($IDs[$url] > $last)) {
867                                 // Debug message
868                                 //DEBUG_LOG(__FUNCTION__.":ADD - lid={$lid},url={$url},last={$last}");
869
870                                 // Add this ID
871                                 $IDs[$url] = $last;
872                                 $USE[$url] = $lid;
873                         } // END - if
874                 } else {
875                         // Debug message
876                         //DEBUG_LOG(__FUNCTION__.":ignore - lid={$lid},url={$url},last={$last}");
877
878                         // Ignore these old entries!
879                         $ignored[] = $url;
880                         unset($IDs[$url]);
881                         unset($USE[$url]);
882                 }
883         } // END - while
884
885         // Free result
886         SQL_FREERESULT($result);
887
888         // Return array
889         return $USE;
890 }
891 // "Getter" for maximum random number
892 function SURFBAR_GET_MAX_RANDOM ($UIDs, $ADD) {
893         global $_CONFIG;
894         // Count max availabe entries
895         $result = SQL_QUERY("SELECT sbu.id AS cnt
896 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
897 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
898 ON sbu.id=sbs.url_id
899 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
900 ON sbu.id=l.url_id
901 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
902 GROUP BY sbu.id", __FILE__, __LINE__);
903
904         // Log last query
905         //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
906
907         // Fetch max rand
908         $maxRand = SQL_NUMROWS($result);
909
910         // Free result
911         SQL_FREERESULT($result);
912
913         // Return value
914         return $maxRand;
915 }
916 // Load all URLs of the current user and return it as an array
917 function SURFBAR_GET_USER_URLS () {
918         // Init array
919         $URLs = array();
920
921         // Begin the query
922         $result = SQL_QUERY_ESC("SELECT u.id, 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
923 FROM "._MYSQL_PREFIX."_surfbar_urls AS u
924 WHERE u.userid=%s AND u.status != 'DELETED'
925 ORDER BY u.id ASC",
926                 array($GLOBALS['userid']), __FILE__, __LINE__);
927
928         // Are there entries?
929         if (SQL_NUMROWS($result) > 0) {
930                 // Load all rows
931                 while ($row = SQL_FETCHARRAY($result)) {
932                         // Add the row
933                         $URLs[$row['id']] = $row;
934                 } // END - while
935         } // END - if
936
937         // Free result
938         SQL_FREERESULT($result);
939
940         // Return the array
941         return $URLs;
942 }
943 // Create list of actions depending on status for the user
944 function SURFBAR_MEMBER_ACTIONS ($id, $status) {
945         /* DEBUG: */ die("id={$id},status={$status}");
946 }
947 // Determine next id for surfbar or get data for given id, always call this before you call other
948 // getters below this function!!!
949 function SURFBAR_DETERMINE_NEXT_ID ($id = 0) {
950         global $SURFBAR_CACHE, $_CONFIG;
951
952         // Default is no id and no random number
953         $nextId = 0;
954         $randNum = 0;
955
956         // Is the ID set?
957         if ($id == 0) {
958                 // Get array with lock ids
959                 $USE = SURFBAR_GET_LOCK_IDS();
960
961                 // Shall we add some URL ids to ignore?
962                 $ADD = "";
963                 if (count($USE) > 0) {
964                         // Ignore some!
965                         $ADD = " AND sbu.id NOT IN (";
966                         foreach ($USE as $url_id => $lid) {
967                                 // Add URL id
968                                 $ADD .= $url_id.",";
969                         } // END - foreach
970
971                         // Add closing bracket
972                         $ADD = substr($ADD, 0, -1) . ")";
973                 } // END - if
974
975                 // Determine depleted user account
976                 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
977
978                 // Get maximum randomness factor
979                 $maxRand = SURFBAR_GET_MAX_RANDOM($UIDs, $ADD);
980
981                 // If more than one URL can be called generate the random number!
982                 if ($maxRand > 1) {
983                         // Generate random number
984                         $randNum = mt_rand(0, ($maxRand - 1));
985                 } // END - if
986
987                 // And query the database
988                 //DEBUG_LOG(__FUNCTION__.":randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."");
989                 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.reward, sbu.costs, sbu.views_total, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
990 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
991 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
992 ON sbu.id=sbs.url_id
993 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
994 ON sbu.id=l.url_id
995 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
996 GROUP BY sbu.id
997 ORDER BY l.last_surfed ASC, sbu.id ASC
998 LIMIT %s,1",
999                         array($randNum), __FILE__, __LINE__
1000                 );
1001         } else {
1002                 // Get data from specified id number
1003                 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.reward, sbu.costs, sbu.views_total, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
1004 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
1005 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
1006 ON sbu.id=sbs.url_id
1007 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
1008 ON sbu.id=l.url_id
1009 WHERE sbu.userid != %s AND sbu.status='CONFIRMED' AND sbu.id=%s
1010 LIMIT 1",
1011                         array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
1012                 );
1013         }
1014
1015         // Is there an id number?
1016         //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS()."");
1017         if (SQL_NUMROWS($result) == 1) {
1018                 // Load/cache data
1019                 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - BEFORE");
1020                 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
1021                 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - AFTER");
1022
1023                 // Determine waiting time
1024                 $SURFBAR_CACHE['time'] = SURFBAR_DETERMINE_WAIT_TIME();
1025
1026                 // Is the last salt there?
1027                 if (is_null($SURFBAR_CACHE['last_salt'])) {
1028                         // Then repair it wit the static!
1029                         //DEBUG_LOG(__FUNCTION__.":last_salt - FIXED!");
1030                         $SURFBAR_CACHE['last_salt'] = "";
1031                 } // END - if
1032
1033                 // Fix missing last_surfed
1034                 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
1035                         // Fix it here
1036                         //DEBUG_LOG(__FUNCTION__.":last_surfed - FIXED!");
1037                         $SURFBAR_CACHE['last_surfed'] = 0;
1038                 } // END - if
1039
1040                 // Get base/fixed reward and costs
1041                 $SURFBAR_CACHE['reward'] = SURFBAR_DETERMINE_REWARD();
1042                 $SURFBAR_CACHE['costs']  = SURFBAR_DETERMINE_COSTS();
1043                 //DEBUG_LOG(__FUNCTION__.":BASE/STATIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1044
1045                 // Only in dynamic model add the dynamic bonus!
1046                 if ($_CONFIG['surfbar_pay_model'] == "DYNAMIC") {
1047                         // Calculate dynamic reward/costs and add it
1048                         $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_ADD();
1049                         $SURFBAR_CACHE['costs']  += SURFBAR_CALCULATE_DYNAMIC_ADD();
1050                         //DEBUG_LOG(__FUNCTION__.":DYNAMIC+ - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
1051                 } // END - if
1052
1053                 // Now get the id
1054                 $nextId = SURFBAR_GET_ID();
1055         } // END - if
1056
1057         // Free result
1058         SQL_FREERESULT($result);
1059
1060         // Return result
1061         //DEBUG_LOG(__FUNCTION__.":nextId={$nextId}");
1062         return $nextId;
1063 }
1064 // -----------------------------------------------------------------------------
1065 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
1066 // $SURFBAR_CACHE ARRAY!
1067 // -----------------------------------------------------------------------------
1068 // Private getter for data elements
1069 function SURFBAR_GET_DATA ($element) {
1070         global $SURFBAR_CACHE;
1071         //DEBUG_LOG(__FUNCTION__.":element={$element}");
1072
1073         // Default is null
1074         $data = null;
1075
1076         // Is the entry there?
1077         if (isset($SURFBAR_CACHE[$element])) {
1078                 // Then take it
1079                 $data = $SURFBAR_CACHE[$element];
1080         } else { // END - if
1081                 print("<pre>");
1082                 print_r($SURFBAR_CACHE);
1083                 debug_print_backtrace();
1084                 die("</pre>");
1085         }
1086
1087         // Return result
1088         //DEBUG_LOG(__FUNCTION__.":element[$element]={$data}");
1089         return $data;
1090 }
1091 // Getter for reward from cache
1092 function SURFBAR_GET_REWARD () {
1093         // Get data element and return its contents
1094         return SURFBAR_GET_DATA('reward');
1095 }
1096 // Getter for costs from cache
1097 function SURFBAR_GET_COSTS () {
1098         // Get data element and return its contents
1099         return SURFBAR_GET_DATA('costs');
1100 }
1101 // Getter for URL from cache
1102 function SURFBAR_GET_URL () {
1103         // Get data element and return its contents
1104         return SURFBAR_GET_DATA('url');
1105 }
1106 // Getter for salt from cache
1107 function SURFBAR_GET_SALT () {
1108         // Get data element and return its contents
1109         return SURFBAR_GET_DATA('salt');
1110 }
1111 // Getter for id from cache
1112 function SURFBAR_GET_ID () {
1113         // Get data element and return its contents
1114         return SURFBAR_GET_DATA('id');
1115 }
1116 // Getter for userid from cache
1117 function SURFBAR_GET_USERID () {
1118         // Get data element and return its contents
1119         return SURFBAR_GET_DATA('userid');
1120 }
1121 // Getter for user reload locks
1122 function SURFBAR_GET_USER_RELOAD_LOCK () {
1123         // Get data element and return its contents
1124         return SURFBAR_GET_DATA('user_locks');
1125 }
1126 // Getter for reload time
1127 function SURFBAR_GET_RELOAD_TIME () {
1128         // Get data element and return its contents
1129         return SURFBAR_GET_DATA('time');
1130 }
1131 //
1132 ?>