2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/31/2008 *
4 * =============== Last change: 08/31/2008 *
6 * -------------------------------------------------------------------- *
7 * File : surfbar_functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Functions for surfbar *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Funktionen fuer die Surfbar *
12 * -------------------------------------------------------------------- *
14 * -------------------------------------------------------------------- *
15 * Copyright (c) 2003 - 2008 by Roland Haeder *
16 * For more information visit: http://www.mxchange.org *
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. *
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. *
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, *
32 ************************************************************************/
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";
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?
48 // Check if that URL does not exist
49 if (SURFBAR_LOOKUP_BY_URL($url, $uid)) {
54 // Register the new URL
55 return SURFBAR_REGISTER_URL($url, $uid, $reward, $costs, $paymentId, "CONFIRMED", "unlock");
58 function SURFBAR_LOOKUP_BY_URL ($url) {
59 // Now lookup that given URL by itself
60 $urlArray = SURFBAR_GET_URL_DATA($url, "url");
63 return (count($urlArray) > 0);
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") {
69 // By default nothing is found
70 $lastUrlData = array();
72 // Is the column an id number?
73 if (($column == "id") || ($column == "userid")) {
75 $searchTerm = bigintval($searchTerm);
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
83 array($column, $searchTerm, $order, $sort), __FILE__, __LINE__);
85 // Is there at least one record?
86 if (SQL_NUMROWS($result) > 0) {
88 while ($dataRow = SQL_FETCHARRAY($result)) {
89 // Shall we group these results?
91 // Add the row by id as index
92 $lastUrlData[$dataRow['id']] = $dataRow;
95 $lastUrlData[$dataRow[$group]][$dataRow['id']] = $dataRow;
101 SQL_FREERESULT($result);
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") {
110 // Make sure by the user registered URLs are always pending
111 if ($addMode == "reg") $status = "PENDING";
116 'frametester' => FRAMETESTER($url),
120 'payment_id' => $paymentId,
124 // Insert the URL into database
125 $content['insert_id'] = SURFBAR_INSERT_URL_BY_ARRAY($content);
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']);
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);
139 SURFBAR_NOTIFY_USER("url_{$addMode}", $content);
141 // Return the insert id
142 return $content['insert_id'];
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')",
149 bigintval($urlData['uid']),
151 (float)$urlData['reward'],
152 (float)$urlData['costs'],
153 bigintval($urlData['payment_id']),
155 ), __FILE__, __LINE__
159 return SQL_INSERTID();
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);
167 $eval = sprintf("\$subject = ADMIN_SURFBAR_NOTIFY_%s_SUBJECT;",
168 strtoupper($messageType)
172 // Send the notification out
173 SEND_ADMIN_NOTIFICATION($subject, $templateName, $content, $content['uid']);
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);
181 $eval = sprintf("\$subject = MEMBER_SURFBAR_NOTIFY_%s_SUBJECT;",
182 strtoupper($messageType)
187 $mailText = LOAD_EMAIL_TEMPLATE($templateName, $content);
190 SEND_EMAIL($content['uid'], $subject, $mailText);
192 // Translate the URL status
193 function SURFBAR_TRANSLATE_STATUS ($status) {
194 // Create constant name
195 $constantName = sprintf("SURFBAR_URL_STATUS_%s", strtoupper($status));
197 // Set default translated status
198 $statusTranslated = "!".$constantName."!";
200 // Generate eval() command
201 if (defined($constantName)) {
202 $eval = "\$statusTranslated = ".$constantName.";";
207 return $statusTranslated;
209 // Determine right template name
210 function SURFBAR_DETERMINE_TEMPLATE_NAME() {
211 // Default is the frameset
212 $templateName = "surfbar_frameset";
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'])
223 return $templateName;
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;
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'];
239 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt FROM "._MYSQL_PREFIX."_surfbar_locks
240 WHERE userid=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
242 array($GLOBALS['userid']), __FILE__, __LINE__
246 list($SURFBAR_CACHE['user_locks']) = SQL_FETCHROW($result);
249 if (is_null($SURFBAR_CACHE['user_locks'])) {
250 // Then fix it to zero!
251 $SURFBAR_CACHE['user_locks'] = 0;
255 SQL_FREERESULT($result);
258 $total = SURFBAR_GET_TOTAL_URLS();
260 // Do we have some URLs in lock? Admins can always surf on own URLs!
261 //* DEBUG: */ echo __FUNCTION__.":userLocks=".SURFBAR_GET_DATA('user_locks').",total={$total}<br />\n";
262 $isFull = ((SURFBAR_GET_DATA('user_locks') == $total) && ($total > 0));
265 die("DYNAMIC not yet implemented!");
271 // Get total amount of URLs of given status for current user or of CONFIRMED URLs by default
272 function SURFBAR_GET_TOTAL_URLS ($status="CONFIRMED") {
273 // Get amount from database
274 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
275 FROM "._MYSQL_PREFIX."_surfbar_urls
276 WHERE userid != %d AND status='%s'",
277 array($GLOBALS['userid'], $status), __FILE__, __LINE__
281 list($cnt) = SQL_FETCHROW($result);
284 SQL_FREERESULT($result);
289 // Generate a validation code for the given id number
290 function SURFBAR_GENERATE_VALIDATION_CODE ($id, $salt="") {
291 global $_CONFIG, $SURFBAR_CACHE;
293 // Generate a code until the length matches
295 while (strlen($valCode) != $_CONFIG['code_length']) {
298 // Generate random hashed string
299 $SURFBAR_CACHE['salt'] = sha1(GEN_PASS(255));
302 $SURFBAR_CACHE['salt'] = $salt;
304 //* DEBUG: */ echo __FUNCTION__.":".SURFBAR_GET_SALT()."*<br />\n";
306 // ... and now the validation code
307 $valCode = GEN_RANDOM_CODE($_CONFIG['code_length'], sha1(SURFBAR_GET_SALT().":".$id), $GLOBALS['userid']);
308 //* DEBUG: */ echo __FUNCTION__.":valCode={$valCode}<br />\n";
311 // Hash it with md5() and salt it with the random string
312 $hashedCode = generateHash(md5($valCode), SURFBAR_GET_SALT());
314 // Finally encrypt it PGP-like and return it
315 return generatePassString($hashedCode);
317 // Check validation code
318 function SURFBAR_CHECK_VALIDATION_CODE ($id, $check, $salt) {
319 global $SURFBAR_CACHE;
322 $id = bigintval($id);
324 // Now generate the code again
325 $code = SURFBAR_GENERATE_VALIDATION_CODE($id, $salt);
327 // Return result of checking hashes and salts
328 //* DEBUG: */ echo __FUNCTION__.":---".$code."---<br />\n---".$check."---<br />\n";
329 //* DEBUG: */ echo __FUNCTION__.":+++".$salt."+++<br />\n+++".SURFBAR_GET_DATA('last_salt')."+++<br />\n";
330 return (($code == $check) && ($salt == SURFBAR_GET_DATA('last_salt')));
332 // Lockdown the userid/id combination (reload lock)
333 function SURFBAR_LOCKDOWN_ID ($id) {
334 //* DEBUG: */ print "LOCK!<br />\n";
335 //* DEBUG: */ return;
336 // Just add it to the database
337 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_locks (userid, url_id) VALUES(%s, %s)",
338 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__);
340 // Remove the salt from database
341 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_surfbar_salts WHERE url_id=%s AND userid=%s LIMIT 1",
342 array(bigintval($id), $GLOBALS['userid']), __FILE__, __LINE__);
344 // Pay points to the user and remove it from the sender
345 function SURFBAR_PAY_POINTS ($id) {
346 global $SURFBAR_CACHE, $_CONFIG;
348 // Re-configure ref-system to surfbar levels
349 $_CONFIG['db_percents'] = "percent";
350 $_CONFIG['db_table'] = "surfbar_reflevels";
352 // Book it to the user
353 ADD_POINTS_REFSYSTEM($GLOBALS['userid'], SURFBAR_GET_DATA('reward'));
355 // Remove it from the URL owner
356 SUB_POINTS($SURFBAR_CACHE['userid'], SURFBAR_GET_DATA('costs'));
358 // Update the salt for validation
359 function SURFBAR_UPDATE_SALT() {
360 // Update views_total
361 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_urls SET views_total=views_total+1 WHERE id=%s LIMIT 1",
362 array(SURFBAR_GET_ID()), __FILE__, __LINE__);
364 // Simply store the salt from cache away in database...
365 SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_surfbar_salts SET last_salt='%s' WHERE url_id=%s AND userid=%s LIMIT 1",
366 array(SURFBAR_GET_SALT(), SURFBAR_GET_ID(), $GLOBALS['userid']), __FILE__, __LINE__);
369 if (SQL_AFFECTEDROWS() == 0) {
370 // Insert missing entry!
371 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_surfbar_salts (url_id,userid,last_salt) VALUES(%s, %s, '%s')",
372 array(SURFBAR_GET_ID(), $GLOBALS['userid'], SURFBAR_GET_SALT()), __FILE__, __LINE__);
375 // Return if the update was okay
376 return (SQL_AFFECTEDROWS() == 1);
378 // Check if the reload lock is active for given id
379 function SURFBAR_CHECK_RELOAD_LOCK ($id) {
380 //* DEBUG: */ echo __FUNCTION__.":id={$id}<br />\n";
382 $result = SQL_QUERY_ESC("SELECT COUNT(id) AS cnt
383 FROM "._MYSQL_PREFIX."_surfbar_locks
384 WHERE userid=%s AND url_id=%s AND (UNIX_TIMESTAMP() - ".SURFBAR_GET_DATA('surf_lock').") < UNIX_TIMESTAMP(last_surfed)
385 ORDER BY last_surfed ASC
387 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
391 list($cnt) = SQL_FETCHROW($result);
394 SQL_FREERESULT($result);
397 //* DEBUG: */ echo __FUNCTION__.":cnt={$cnt},".SURFBAR_GET_DATA('surf_lock')."<br />\n";
400 // Determine next id for surfbar view, always call this before you call other
401 // getters below this function!!!
402 function SURFBAR_GET_NEXT_ID ($id = 0) {
403 global $SURFBAR_CACHE, $_CONFIG;
406 $nextId = 0; $randNum = 0;
410 // Set max random factor to total URLs minus 1
411 $maxRand = SURFBAR_GET_TOTAL_URLS() - 1;
413 // If more than one URL can be called generate the random number!
415 // Generate random number
416 $randNum = mt_rand(0, $maxRand);
419 // Get all id from locks within the timestamp
420 $result = SQL_QUERY_ESC("SELECT id, url_id, UNIX_TIMESTAMP(last_surfed)
422 "._MYSQL_PREFIX."_surfbar_locks
426 id ASC", array($GLOBALS['userid']),
430 $IDs = array(); $USE = array();
432 while (list($id, $url, $last) = SQL_FETCHROW($result)) {
433 //* DEBUG: */ echo __FUNCTION__.": next - id={$id},url={$url},last={$last}<br />\n";
434 // Skip entries that are too old
435 if (($last < (time() - SURFBAR_GET_DATA('surf_lock'))) && (!in_array($url, $ignored))) {
436 //* DEBUG: */ echo __FUNCTION__.": okay - id={$id},url={$url},last={$last}<br />\n";
437 // Add only if missing or bigger
438 if ((!isset($IDs[$url])) || ($IDs[$url] <= $last)) {
440 //* DEBUG: */ echo __FUNCTION__.": ADD - id={$id},url={$url},last={$last}<br />\n";
445 // Ignore these old entries!
446 //* DEBUG: */ echo __FUNCTION__.": ignore - id={$id},url={$url},last={$last}<br />\n";
454 SQL_FREERESULT($result);
456 // Shall we add some ids?
458 if (count($USE) > 0) {
459 $ADD = " AND l.id IN (".implode(",", $USE).")";
463 $result = SQL_QUERY_ESC("SELECT userid FROM "._MYSQL_PREFIX."_surfbar_urls
464 WHERE userid != %s AND status='CONFIRMED'
466 ORDER BY userid ASC",
467 array($GLOBALS['userid']), __FILE__, __LINE__);
470 $UIDs = array($GLOBALS['userid']);
471 while (list($uid) = SQL_FETCHROW($result)) {
473 $points = GET_TOTAL_DATA($uid, "user_points", "points") - GET_TOTAL_DATA($uid, "user_data", "used_points");
474 //* DEBUG: */ echo __FUNCTION__.":uid={$uid},points={$points}<br />\n";
476 // Shall we add this to ignore?
484 SQL_FREERESULT($result);
486 // And query the database
487 //* DEBUG: */ echo __FUNCTION__.":randNum={$randNum},maxRand={$maxRand},surfLock=".SURFBAR_GET_DATA('surf_lock')."<br />\n";
488 $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
489 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
490 LEFT JOIN "._MYSQL_PREFIX."_payments AS p
491 ON sbu.payment_id=p.id
492 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
494 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
496 WHERE sbu.userid NOT IN (".implode(",", $UIDs).") AND sbu.status='CONFIRMED'".$ADD."
498 ORDER BY l.last_surfed ASC, sbu.id ASC
500 array($randNum), __FILE__, __LINE__
503 while($content = SQL_FETCHARRAY($result)) {
504 echo "<pre>".print_r($content, true)."</pre>";
509 // Get data from specified id number
510 $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
511 FROM "._MYSQL_PREFIX."_surfbar_urls AS sbu
512 LEFT JOIN "._MYSQL_PREFIX."_payments AS p
513 ON sbu.payment_id=p.id
514 LEFT JOIN "._MYSQL_PREFIX."_surfbar_salts AS sbs
516 LEFT JOIN "._MYSQL_PREFIX."_surfbar_locks AS l
518 WHERE sbu.userid != %s AND sbu.status='CONFIRMED' AND sbu.id=%s
520 array($GLOBALS['userid'], bigintval($id)), __FILE__, __LINE__
524 // Is there an id number?
525 if (SQL_NUMROWS($result) == 1) {
527 //* DEBUG: */ echo __FUNCTION__.":count(".count($SURFBAR_CACHE).") - BEFORE<br />\n";
528 $SURFBAR_CACHE = merge_array($SURFBAR_CACHE, SQL_FETCHARRAY($result));
529 //* DEBUG: */ echo __FUNCTION__.":count(".count($SURFBAR_CACHE).") - AFTER<br />\n";
531 // Is the time there?
532 if (is_null($SURFBAR_CACHE['time'])) {
533 // Then repair it wit the static!
534 //* DEBUG: */ echo __FUNCTION__.": time - STATIC!<br />\n";
535 $SURFBAR_CACHE['time'] = $_CONFIG['surfbar_static_time'];
538 // Is the last salt there?
539 if (is_null($SURFBAR_CACHE['last_salt'])) {
540 // Then repair it wit the static!
541 //* DEBUG: */ echo __FUNCTION__.": last_salt - FIXED!<br />\n";
542 $SURFBAR_CACHE['last_salt'] = "";
545 // Fix missing last_surfed
546 if ((!isset($SURFBAR_CACHE['last_surfed'])) || (is_null($SURFBAR_CACHE['last_surfed']))) {
548 //* DEBUG: */ echo __FUNCTION__.": last_surfed - FIXED!<br />\n";
549 $SURFBAR_CACHE['last_surfed'] = "0";
552 // Are we in static mode?
553 if ($_CONFIG['surfbar_pay_model'] == "STATIC") {
554 // Then use static reward/costs!
555 $SURFBAR_CACHE['reward'] = $_CONFIG['surfbar_static_reward'];
556 $SURFBAR_CACHE['costs'] = $_CONFIG['surfbar_static_costs'];
558 // Calculate dynamic reward/costs and add it
559 $SURFBAR_CACHE['reward'] += SURFBAR_CALCULATE_DYNAMIC_REWARD_ADD();
560 $SURFBAR_CACHE['costs'] += SURFBAR_CALCULATE_DYNAMIC_COSTS_ADD();
564 $nextId = SURFBAR_GET_ID();
568 SQL_FREERESULT($result);
571 //* DEBUG: */ echo __FUNCTION__.":nextId={$nextId}<br />\n";
574 // ----------------------------------------------------------------------------
575 // PLEASE DO NOT ADD ANY OTHER FUNCTIONS BELOW THIS LINE ELSE THEY "WRAP" THE
576 // $SURFBAR_CACHE ARRAY!
577 // ----------------------------------------------------------------------------
578 // Private getter for data elements
579 function SURFBAR_GET_DATA ($element) {
580 global $SURFBAR_CACHE;
585 // Is the entry there?
586 if (isset($SURFBAR_CACHE[$element])) {
588 $data = $SURFBAR_CACHE[$element];
591 print_r($SURFBAR_CACHE);
592 debug_print_backtrace();
599 // Getter for reward from cache
600 function SURFBAR_GET_REWARD () {
601 // Get data element and return its contents
602 return SURFBAR_GET_DATA('reward');
604 // Getter for costs from cache
605 function SURFBAR_GET_COSTS () {
606 // Get data element and return its contents
607 return SURFBAR_GET_DATA('costs');
609 // Getter for URL from cache
610 function SURFBAR_GET_URL () {
611 // Get data element and return its contents
612 return SURFBAR_GET_DATA('url');
614 // Getter for salt from cache
615 function SURFBAR_GET_SALT () {
616 // Get data element and return its contents
617 return SURFBAR_GET_DATA('salt');
619 // Getter for id from cache
620 function SURFBAR_GET_ID () {
621 // Get data element and return its contents
622 return SURFBAR_GET_DATA('id');
624 // Getter for user reload locks
625 function SURFBAR_GET_USER_RELOAD_LOCK () {
626 // Get data element and return its contents
627 return SURFBAR_GET_DATA('user_locks');
629 // Getter for reload time
630 function SURFBAR_GET_RELOAD_TIME () {
631 // Get data element and return its contents
632 return SURFBAR_GET_DATA('time');