More fixes for surfbar extension
[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 (ereg(basename(__FILE__), $_SERVER['PHP_SELF'])) {
36         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
37         require($INC);
38 }
39
40 // Admin has added an URL with given user id
41 function SURFBAR_ADMIN_ADD_URL ($url, $uid, $reward, $costs, $paymentId) {
42         // Is this really an admin?
43         if (!IS_ADMIN()) {
44                 // Then leave here
45                 return false;
46         } // END - if
47
48         // Check if that URL does not exist
49         if (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
50                 // Already found!
51                 return false;
52         } // END - if
53
54         // Register the new URL
55         return SURFBAR_REGISTER_URL($url, $uid, $reward, $costs, $paymentId, "CONFIRMED", "unlock");
56 }
57 // Looks up by an URL
58 function SURFBAR_LOOKUP_BY_URL ($url) {
59         // Now lookup that given URL by itself
60         $urlArray = SURFBAR_GET_URL_DATA($url, "url");
61
62         // Was it found?
63         return (count($urlArray) > 0);
64 }
65 // Load URL data by given search term and column
66 function SURFBAR_GET_URL_DATA ($searchTerm, $column="id", $order="id", $sort="ASC", $group="id") {
67         global $lastUrlData;
68
69         // By default nothing is found
70         $lastUrlData = array();
71
72         // Is the column an id number?
73         if (($column == "id") || ($column == "userid")) {
74                 // Extra secure input
75                 $searchTerm = bigintval($searchTerm);
76         } // END - if
77
78         // Look up the record
79         $result = SQL_QUERY_ESC("SELECT id, userid, url, reward, costs, views_total, status, registered, last_locked, lock_reason
80 FROM "._MYSQL_PREFIX."_surfbar_urls
81 WHERE %s='%s'
82 ORDER BY %s %s",
83                 array($column, $searchTerm, $order, $sort), __FILE__, __LINE__);
84
85         // Is there at least one record?
86         if (SQL_NUMROWS($result) > 0) {
87                 // Then load all!
88                 while ($dataRow = SQL_FETCHARRAY($result)) {
89                         // Shall we group these results?
90                         if ($group == "id") {
91                                 // Add the row by id as index
92                                 $lastUrlData[$dataRow['id']] = $dataRow;
93                         } else {
94                                 // Group entries
95                                 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
96                         }
97                 } // END - while
98         } // END - if
99
100         // Free the result
101         SQL_FREERESULT($result);
102
103         // Return the result
104         return $lastUrlData;
105 }
106 // Registers an URL with the surfbar. You should have called SURFBAR_LOOKUP_BY_URL() first!
107 function SURFBAR_REGISTER_URL ($url, $uid, $reward, $paymentId, $costs, $status="PENDING", $addMode="reg") {
108         global $_CONFIG;
109
110         // Make sure by the user registered URLs are always pending
111         if ($addMode == "reg") $status = "PENDING";
112
113         // Prepare content
114         $content = array(
115                 'url'         => $url,
116                 'frametester' => FRAMETESTER($url),
117                 'uid'         => $uid,
118                 'reward'      => $reward,
119                 'costs'       => $costs,
120                 'payment_id'  => $paymentId,
121                 'status'      => $status
122         );
123
124         // Insert the URL into database
125         $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
126
127         // Translate status, reward and costs
128         $content['status'] = SURFBAR_TRANSLATE_STATUS($content['status']);
129         $content['reward'] = TRANSLATE_COMMA($content['reward']);
130         $content['costs']  = TRANSLATE_COMMA($content['costs']);
131
132         // If in reg-mode we notify admin
133         if (($addMode == "reg") || ($_CONFIG['surfbar_notify_admin_unlock'] == "Y")) {
134                 // Notify admin even when he as unlocked an email
135                 SURFBAR_NOTIFY_ADMIN("url_{$addMode}", $content);
136         } // END - if
137
138         // Send mail to user
139         SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
140
141         // Return the insert id
142         return $content['insert_id'];
143 }
144 // Inserts an url by given data array and return the insert id
145 function SURFBAR_INSERT_URL_BY_ARRAY ($urlData) {
146         // Just run the insert query for now
147         SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_urls (userid, url, reward, costs, payment_id, status) VALUES(%s, '%s', %s, %s, %s, '%s')",
148                 array(
149                         bigintval($urlData['uid']),
150                         $urlData['url'],
151                         (float)$urlData['reward'],
152                         (float)$urlData['costs'],
153                         bigintval($urlData['payment_id']),
154                         $urlData['status']
155                 ), __FILE__, __LINE__
156         );
157
158         // Return insert id
159         return SQL_INSERTID();
160 }
161 // Notify admin(s) with a selected message and content
162 function SURFBAR_NOTIFY_ADMIN ($messageType, $content) {
163         // Prepare template name
164         $templateName = sprintf("admin_surfbar_%s", $messageType);
165
166         // Prepare subject
167         $eval = sprintf("\$subject = ADMIN_SURFBAR_NOTIFY_%s_SUBJECT;",
168                 strtoupper($messageType)
169         );
170         eval($eval);
171
172         // Send the notification out
173         SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
174 }
175 // Notify the user about the performed action
176 function SURFBAR_NOTIFY_USER ($messageType, $content) {
177         // Prepare template name
178         $templateName = sprintf("member_surfbar_%s", $messageType);
179
180         // Prepare subject
181         $eval = sprintf("\$subject = MEMBER_SURFBAR_NOTIFY_%s_SUBJECT;",
182                 strtoupper($messageType)
183         );
184         eval($eval);
185
186         // Load template
187         $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content);
188
189         // Send the email
190         SEND_EMAIL($content['uid'], $subject, $mailText);
191 }
192 // Translate the URL status
193 function SURFBAR_TRANSLATE_STATUS ($status) {
194         // Create constant name
195         $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
196
197         // Set default translated status
198         $statusTranslated = "!".$constantName."!";
199
200         // Generate eval() command
201         if (defined($constantName)) {
202                 $eval = "\$statusTranslated = ".$constantName.";";
203                 eval($eval);
204         } // END - if
205
206         // Return result
207         return $statusTranslated;
208 }
209 // Determine right template name
210 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
211         // Default is the frameset
212         $templateName = "surfbar_frameset";
213
214         // Any frame set? ;-)
215         if (isset($_GET['frame'])) {
216                 // Use the frame as a template name part... ;-)
217                 $templateName = sprintf("surfbar_frame_%s",
218                         SQL_ESCAPE($_GET['frame'])
219                 );
220         } // END - if
221
222         // Return result
223         return $templateName;
224 }
225 // Check if the "reload lock" of the current user is full, call this function
226 // before you call SURFBAR_CHECK_RELOAD_LOCK().
227 function SURFBAR_CHECK_RELOAD_FULL() {
228         global $SURFBAR_CACHE, $_CONFIG;
229
230         // Default is full!
231         $isFull = true;
232
233         // Do we have static or dynamic mode?
234         if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
235                 // Cache static reload lock
236                 $SURFBAR_CACHE['surf_lock'] = $_CONFIG['surfbar_static_lock'];
237                 //DEBUG_LOG(__FUNCTION__.":Fixed surf lock is ".$_CONFIG['surfbar_static_lock']."");
238
239                 // Ask the database
240                 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
241 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
242 LIMIT 1",
243                         array($GLOBALS['userid']), __FILE__, __LINE__
244                 );
245
246                 // Fetch row
247                 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
248
249                 // Is it null?
250                 if (is_null($SURFBAR_CACHE['user_locks'])) {
251                         // Then fix it to zero!
252                         $SURFBAR_CACHE['user_locks'] = 0;
253                 } // END - if
254
255                 // Free result
256                 SQL_FREERESULT($result);
257
258                 // Get total URLs
259                 $total = SURFBAR_GET_TOTAL_URLS();
260
261                 // Do we have some URLs in lock? Admins can always surf on own URLs!
262                 //DEBUG_LOG(__FUNCTION__.":userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}");
263                 $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
264         } else {
265                 // Dynamic model...
266                 die("DYNAMIC not yet implemented!");
267         }
268
269         // Return result
270         return $isFull;
271 }
272 // Get total amount of URLs of given status for current user or of CONFIRMED URLs by default
273 function SURFBAR_GET_TOTAL_URLS ($status="CONFIRMED") {
274         // Determine depleted user account
275         $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
276
277         // Get amount from database
278         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
279 FROM "._MYSQL_PREFIX."_surfbar_urls
280 WHERE userid NOT IN (".implode(",", $UIDs).") AND status='%s'",
281                 array($status), __FILE__, __LINE__
282         );
283
284         // Fetch row
285         list($cnt) = SQL_FETCHROW($result);
286
287         // Free result
288         SQL_FREERESULT($result);
289
290         // Return result
291         return $cnt;
292 }
293 // Generate a validation code for the given id number
294 function SURFBAR_GENERATE_VALIDATION_CODE ($id, $salt="") {
295         global $_CONFIG, $SURFBAR_CACHE;
296
297         // Generate a code until the length matches
298         $valCode = "";
299         while (strlen($valCode) != $_CONFIG['code_length']) {
300                 // Is the salt set?
301                 if (empty($salt)) {
302                         // Generate random hashed string
303                         $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
304                         //DEBUG_LOG(__FUNCTION__.":newSalt=".SURFBAR_GET_SALT()."");
305                 } else {
306                         // Use this as salt!
307                         $SURFBAR_CACHE['salt'] = $salt;
308                         //DEBUG_LOG(__FUNCTION__.":oldSalt=".SURFBAR_GET_SALT()."");
309                 }
310
311                 // ... and now the validation code
312                 $valCode = GEN_RANDOM_CODE($_CONFIG['code_length'], sha1(SURFBAR_GET_SALT().":".$id), $GLOBALS['userid']);
313                 //DEBUG_LOG(__FUNCTION__.":valCode={$valCode}");
314         } // END - while
315
316         // Hash it with md5() and salt it with the random string
317         $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
318
319         // Finally encrypt it PGP-like and return it
320         $valHashedCode = generatePassString($hashedCode);
321         //DEBUG_LOG(__FUNCTION__.":finalValCode={$valHashedCode}");
322         return $valHashedCode;
323 }
324 // Check validation code
325 function SURFBAR_CHECK_VALIDATION_CODE ($id, $check, $salt) {
326         global $SURFBAR_CACHE;
327
328         // Secure id number
329         $id = bigintval($id);
330
331         // Now generate the code again
332         $code = SURFBAR_GENERATE_VALIDATION_CODE($id, $salt);
333
334         // Return result of checking hashes and salts
335         //DEBUG_LOG(__FUNCTION__.":---".$code."|".$check."---");
336         //DEBUG_LOG(__FUNCTION__.":+++".$salt."|".SURFBAR_GET_DATA('last_salt')."+++");
337         return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
338 }
339 // Lockdown the userid/id combination (reload lock)
340 function SURFBAR_LOCKDOWN_ID ($id) {
341         //* DEBUG: */ print "LOCK!");
342         ///* DEBUG: */ return;
343         // Just add it to the database
344         SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
345                 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__);
346
347         // Remove the salt from database
348         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
349                 array(bigintval($id), $GLOBALS['userid']), __FILE__, __LINE__);
350 }
351 // Pay points to the user and remove it from the sender
352 function SURFBAR_PAY_POINTS ($id) {
353         global $SURFBAR_CACHE, $_CONFIG;
354
355         // Re-configure ref-system to surfbar levels
356         $_CONFIG['db_percents'] = "percent";
357         $_CONFIG['db_table']    = "surfbar_reflevels";
358
359         // Remove it from the URL owner
360         //DEBUG_LOG(__FUNCTION__.":uid=".SURFBAR_GET_USERID().",costs=".SURFBAR_GET_COSTS()."");
361         SUB_POINTS(SURFBAR_GET_USERID(), SURFBAR_GET_COSTS());
362
363         // Book it to the user
364         //DEBUG_LOG(__FUNCTION__.":uid=".$GLOBALS['userid'].",reward=".SURFBAR_GET_REWARD()."");
365         ADD_POINTS_REFSYSTEM($GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
366 }
367 // Update the salt for validation
368 function SURFBAR_UPDATE_SALT() {
369         // Update views_total
370         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1 WHERE id=%s LIMIT 1",
371                 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
372
373         // Simply store the salt from cache away in database...
374         SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
375                 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
376
377         // Debug message
378         //DEBUG_LOG(__FUNCTION__.":salt=".SURFBAR_GET_SALT().",id=".SURFBAR_GET_ID().",uid=".$GLOBALS['userid']."");
379
380         // Was that okay?
381         if (SQL_AFFECTEDROWS() == 0) {
382                 // Insert missing entry!
383                 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES(%s, %s, '%s')",
384                         array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
385         } // END - if
386
387         // Debug message
388         //DEBUG_LOG(__FUNCTION__.":affectedRows=".SQL_AFFECTEDROWS()."");
389
390         // Return if the update was okay
391         return (SQL_AFFECTEDROWS() == 1);
392 }
393 // Check if the reload lock is active for given id
394 function SURFBAR_CHECK_RELOAD_LOCK ($id) {
395         //DEBUG_LOG(__FUNCTION__.":id={$id}");
396         // Ask the database
397         $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
398 FROM "._MYSQL_PREFIX."_surfbar_locks
399 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
400 ORDER BY last_surfed ASC
401 LIMIT 1",
402                 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
403         );
404
405         // Fetch counter
406         list($cnt) = SQL_FETCHROW($result);
407
408         // Free result
409         SQL_FREERESULT($result);
410
411         // Return check
412         //DEBUG_LOG(__FUNCTION__.":cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."");
413         return ($cnt == 1);
414 }
415 // Determine which user hash no more points left
416 function SURFBAR_DETERMINE_DEPLETED_USERIDS() {
417         // Init array
418         $UIDs = array();
419
420         // Do we have a current user id?
421         if (IS_LOGGED_IN()) {
422                 // Then add this as well
423                 $UIDs[] = $GLOBALS['userid'];
424
425                 // Get all userid except logged in one
426                 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
427 WHERE userid != %s AND status='CONFIRMED'
428 GROUP BY userid
429 ORDER BY userid ASC",
430                         array($GLOBALS['userid']), __FILE__, __LINE__);
431         } else {
432                 // Get all userid
433                 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
434 WHERE status='CONFIRMED'
435 GROUP BY userid
436 ORDER BY userid ASC", __FILE__, __LINE__);
437         }
438
439         // Load all userid
440         while (list($uid) = SQL_FETCHROW($result)) {
441                 // Get total points
442                 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
443                 //DEBUG_LOG(__FUNCTION__.":uid={$uid},points={$points}");
444
445                 // Shall we add this to ignore?
446                 if ($points <= 0) {
447                         // Ignore this one!
448                         $UIDs[] = $uid;
449                         //DEBUG_LOG(__FUNCTION__.":uid={$uid} has depleted points amount!");
450                 } // END - if
451         } // END - while
452
453         // Free result
454         SQL_FREERESULT($result);
455
456         // Debug message
457         //DEBUG_LOG(__FUNCTION__.":UIDs::count=".count($UIDs)." (with own userid=".$GLOBALS['userid'].")");
458
459         // Return result
460         return $UIDs;
461 }
462 // Determine next id for surfbar view, always call this before you call other
463 // getters below this function!!!
464 function SURFBAR_GET_NEXT_ID ($id = 0) {
465         global $SURFBAR_CACHE, $_CONFIG;
466
467         // Default is no id!
468         $nextId = 0; $randNum = 0;
469
470         // Is the ID set?
471         if ($id == 0) {
472                 // Prepare some arrays
473                 $IDs = array();
474                 $USE = array();
475                 $ignored = array();
476
477                 // Get all id from locks within the timestamp
478                 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed)
479 FROM
480         "._MYSQL_PREFIX."_surfbar_locks
481 WHERE
482         userid=%s
483 ORDER BY
484         id ASC", array($GLOBALS['userid']),
485                         __FILE__, __LINE__);
486
487                 // Load all entries
488                 while (list($id, $url, $last) = SQL_FETCHROW($result)) {
489                         //DEBUG_LOG(__FUNCTION__.":next - id={$id},url={$url},last={$last}");
490                         // Skip entries that are too old
491                         if (($last < (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
492                                 //DEBUG_LOG(__FUNCTION__.":okay - id={$id},url={$url},last={$last}");
493                                 // Add only if missing or bigger
494                                 if ((!isset($IDs[$url])) || ($IDs[$url] <= $last)) {
495                                         // Add this ID
496                                         //DEBUG_LOG(__FUNCTION__.":ADD - id={$id},url={$url},last={$last}");
497                                         $IDs[$url] = $last;
498                                         $USE[$url] = $id;
499                                 } // END - if
500                         } else {
501                                 // Ignore these old entries!
502                                 //DEBUG_LOG(__FUNCTION__.":ignore - id={$id},url={$url},last={$last}");
503                                 $ignored[] = $url;
504                                 unset($IDs[$url]);
505                                 unset($USE[$url]);
506                         }
507                 } // END - while
508
509                 // Free result
510                 SQL_FREERESULT($result);
511
512                 // Shall we add some ids?
513                 $ADD = "";
514                 if (count($USE) > 0) {
515                         $ADD = " AND l.id IN (".implode(",", $USE).")";
516                 } // END - if
517
518                 // Determine depleted user account
519                 $UIDs = SURFBAR_DETERMINE_DEPLETED_USERIDS();
520
521                 // Count max availabe entries
522                 $result = SQL_QUERY("SELECT sbu.id AS cnt
523 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
524 LEFT JOIN "._MYSQL_PREFIX."_payments AS p
525 ON sbu.payment_id=p.id
526 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
527 ON sbu.id=sbs.url_id
528 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
529 ON sbu.id=l.url_id
530 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
531 GROUP BY sbu.id", __FILE__, __LINE__);
532
533                 // Log last query
534                 //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS($result)."");
535
536                 // Fetch max rand
537                 $maxRand = SQL_NUMROWS($result);
538
539                 // Free result
540                 SQL_FREERESULT($result);
541
542                 // If more than one URL can be called generate the random number!
543                 if ($maxRand > 1) {
544                         // Generate random number
545                         $randNum = mt_rand(0, $maxRand);
546                 } // END - if
547
548                 // And query the database
549                 //DEBUG_LOG(__FUNCTION__.":randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."");
550                 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.reward, sbu.costs, sbu.views_total, p.time, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
551 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
552 LEFT JOIN "._MYSQL_PREFIX."_payments AS p
553 ON sbu.payment_id=p.id
554 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
555 ON sbu.id=sbs.url_id
556 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
557 ON sbu.id=l.url_id
558 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
559 GROUP BY sbu.id
560 ORDER BY l.last_surfed ASC, sbu.id ASC
561 LIMIT %s,1",
562                         array($randNum), __FILE__, __LINE__
563                 );
564         } else {
565                 // Get data from specified id number
566                 $result = SQL_QUERY_ESC("SELECT sbu.id, sbu.userid, sbu.url, sbs.last_salt, sbu.reward, sbu.costs, sbu.views_total, p.time, UNIX_TIMESTAMP(l.last_surfed) AS last_surfed
567 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
568 LEFT JOIN "._MYSQL_PREFIX."_payments AS p
569 ON sbu.payment_id=p.id
570 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
571 ON sbu.id=sbs.url_id
572 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
573 ON sbu.id=l.url_id
574 WHERE sbu.userid != %s AND sbu.status='CONFIRMED' AND sbu.id=%s
575 LIMIT 1",
576                         array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
577                 );
578         }
579
580         // Is there an id number?
581         //DEBUG_LOG(__FUNCTION__.":lastQuery=".$_CONFIG['db_last_query']."|numRows=".SQL_NUMROWS($result)."|Affected=".SQL_AFFECTEDROWS($result)."");
582         if (SQL_NUMROWS($result) == 1) {
583                 // Load/cache data
584                 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - BEFORE");
585                 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
586                 //DEBUG_LOG(__FUNCTION__.":count(".count($SURFBAR_CACHE).") - AFTER");
587
588                 // Is the time there?
589                 if (is_null($SURFBAR_CACHE['time'])) {
590                         // Then repair it wit the static!
591                         //DEBUG_LOG(__FUNCTION__.":time - STATIC!");
592                         $SURFBAR_CACHE['time'] = $_CONFIG['surfbar_static_time'];
593                 } // END - if
594
595                 // Is the last salt there?
596                 if (is_null($SURFBAR_CACHE['last_salt'])) {
597                         // Then repair it wit the static!
598                         //DEBUG_LOG(__FUNCTION__.":last_salt - FIXED!");
599                         $SURFBAR_CACHE['last_salt'] = "";
600                 } // END - if
601
602                 // Fix missing last_surfed
603                 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
604                         // Fix it here
605                         //DEBUG_LOG(__FUNCTION__.":last_surfed - FIXED!");
606                         $SURFBAR_CACHE['last_surfed'] = "0";
607                 } // END - if
608
609                 // Are we in static mode?
610                 if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
611                         // Then use static reward/costs!
612                         $SURFBAR_CACHE['reward'] = $_CONFIG['surfbar_static_reward'];
613                         $SURFBAR_CACHE['costs']  = $_CONFIG['surfbar_static_costs'];
614                         //DEBUG_LOG(__FUNCTION__.":FIXED - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
615                 } else {
616                         // Calculate dynamic reward/costs and add it
617                         $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_REWARD_ADD();
618                         $SURFBAR_CACHE['costs']  += SURFBAR_CALCULATE_DYNAMIC_COSTS_ADD();
619                         //DEBUG_LOG(__FUNCTION__.":DYNAMIC - reward=".SURFBAR_GET_REWARD()."|costs=".SURFBAR_GET_COSTS()."");
620                 }
621
622                 // Now get the id
623                 $nextId = SURFBAR_GET_ID();
624         } // END - if
625
626         // Free result
627         SQL_FREERESULT($result);
628
629         // Return result
630         //DEBUG_LOG(__FUNCTION__.":nextId={$nextId}");
631         return $nextId;
632 }
633 // ----------------------------------------------------------------------------
634 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
635 // $SURFBAR_CACHE ARRAY!
636 // ----------------------------------------------------------------------------
637 // Private getter for data elements
638 function SURFBAR_GET_DATA ($element) {
639         global $SURFBAR_CACHE;
640         //DEBUG_LOG(__FUNCTION__.":element={$element}");
641
642         // Default is null
643         $data = null;
644
645         // Is the entry there?
646         if (isset($SURFBAR_CACHE[$element])) {
647                 // Then take it
648                 $data = $SURFBAR_CACHE[$element];
649         } else { // END - if
650                 print("<pre>");
651                 print_r($SURFBAR_CACHE);
652                 debug_print_backtrace();
653                 die("</pre>");
654         }
655
656         // Return result
657         //DEBUG_LOG(__FUNCTION__.":element[$element]={$data}");
658         return $data;
659 }
660 // Getter for reward from cache
661 function SURFBAR_GET_REWARD () {
662         // Get data element and return its contents
663         return SURFBAR_GET_DATA('reward');
664 }
665 // Getter for costs from cache
666 function SURFBAR_GET_COSTS () {
667         // Get data element and return its contents
668         return SURFBAR_GET_DATA('costs');
669 }
670 // Getter for URL from cache
671 function SURFBAR_GET_URL () {
672         // Get data element and return its contents
673         return SURFBAR_GET_DATA('url');
674 }
675 // Getter for salt from cache
676 function SURFBAR_GET_SALT () {
677         // Get data element and return its contents
678         return SURFBAR_GET_DATA('salt');
679 }
680 // Getter for id from cache
681 function SURFBAR_GET_ID () {
682         // Get data element and return its contents
683         return SURFBAR_GET_DATA('id');
684 }
685 // Getter for userid from cache
686 function SURFBAR_GET_USERID () {
687         // Get data element and return its contents
688         return SURFBAR_GET_DATA('userid');
689 }
690 // Getter for user reload locks
691 function SURFBAR_GET_USER_RELOAD_LOCK () {
692         // Get data element and return its contents
693         return SURFBAR_GET_DATA('user_locks');
694 }
695 // Getter for reload time
696 function SURFBAR_GET_RELOAD_TIME () {
697         // Get data element and return its contents
698         return SURFBAR_GET_DATA('time');
699 }
700 //
701 ?>