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