PageRenderTime 52ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/classes/core/CASHSystem.php

https://gitlab.com/x33n/platform
PHP | 718 lines | 553 code | 40 blank | 125 comment | 135 complexity | 2027e11bc0d1bb580a286a60c95507b3 MD5 | raw file
  1. <?php
  2. /**
  3. * An abstract collection of lower level static functions that are useful
  4. * across other classes.
  5. *
  6. * @package platform.org.cashmusic
  7. * @author CASH Music
  8. * @link http://cashmusic.org/
  9. *
  10. * Copyright (c) 2013, CASH Music
  11. * Licensed under the GNU Lesser General Public License version 3.
  12. * See http://www.gnu.org/licenses/lgpl-3.0.html
  13. *
  14. */abstract class CASHSystem {
  15. /**
  16. * Handle annoying environment issues like magic quotes, constants and
  17. * auto-loaders before firing up the CASH platform and whatnot
  18. *
  19. */public static function startUp($return_request=false) {
  20. // only want to do this once, so we check for 'initial_page_request_time'
  21. if (!isset($GLOBALS['cashmusic_script_store']['initial_page_request_time'])) {
  22. // remove magic quotes, never call them "magic" in front of your friends
  23. if (get_magic_quotes_gpc()) {
  24. function stripslashes_from_gpc(&$value) {$value = stripslashes($value);}
  25. $gpc = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
  26. array_walk_recursive($gpc, 'stripslashes_from_gpc');
  27. unset($gpc);
  28. }
  29. // define constants (use sparingly!)
  30. $root = realpath(dirname(__FILE__) . '/../..');
  31. define('CASH_PLATFORM_ROOT', $root);
  32. $cash_settings = CASHSystem::getSystemSettings();
  33. if (substr($cash_settings['apilocation'], -1) != '/') {
  34. $cash_settings['apilocation'] .= '/';
  35. }
  36. define('CASH_API_URL', trim($cash_settings['apilocation'],'/'));
  37. define('CASH_ADMIN_URL', str_replace('/api','/admin',CASH_API_URL));
  38. define('CASH_PUBLIC_URL',str_replace('admin','public',CASH_ADMIN_URL));
  39. // set up auto-load
  40. spl_autoload_register('CASHSystem::autoloadClasses');
  41. // set timezone
  42. date_default_timezone_set($cash_settings['timezone']);
  43. // fire off new CASHRequest to cover any immediate-need things like GET
  44. // asset requests, etc...
  45. $cash_page_request = new CASHRequest();
  46. if (!empty($cash_page_request->response)) {
  47. $cash_page_request->sessionSet(
  48. 'initial_page_request',
  49. array(
  50. 'request' => $cash_page_request->request,
  51. 'response' => $cash_page_request->response,
  52. 'status_uid' => $cash_page_request->response['status_uid']
  53. ),
  54. 'script'
  55. );
  56. }
  57. $cash_page_request->sessionSet('initial_page_request_time',time(),'script');
  58. if ($return_request) {
  59. return $cash_page_request;
  60. } else {
  61. unset($cash_page_request);
  62. }
  63. }
  64. }
  65. /**
  66. * Starts a persistent CASH session in the database, with corresponding cookie
  67. *
  68. * @return none
  69. */public static function startSession($reset_session_id=false,$force_session_id=false) {
  70. $cash_page_request = new CASHRequest(null);
  71. $cash_page_request->startSession($reset_session_id,$force_session_id);
  72. unset($cash_page_request);
  73. }
  74. /**
  75. * The main public method to embed elements. Notice that it echoes rather
  76. * than returns, because it's meant to be used simply by calling and spitting
  77. * out the needed code...
  78. *
  79. * @return none
  80. */public static function embedElement($element_id,$access_method='direct',$location=false) {
  81. // fire up the platform sans-direct-request to catch any GET/POST info sent
  82. // in to the page
  83. CASHSystem::startSession();
  84. $cash_page_request = new CASHRequest(null);
  85. $initial_page_request = $cash_page_request->sessionGet('initial_page_request','script');
  86. if ($initial_page_request && isset($initial_page_request['request']['element_id'])) {
  87. // now test that the initial POST/GET was targeted for this element:
  88. if ($initial_page_request['request']['element_id'] == $element_id) {
  89. $status_uid = $initial_page_request['response']['status_uid'];
  90. $original_request = $initial_page_request['request'];
  91. $original_response = $initial_page_request['response'];
  92. } else {
  93. $status_uid = false;
  94. $original_request = false;
  95. $original_response = false;
  96. }
  97. } else {
  98. $status_uid = false;
  99. $original_request = false;
  100. $original_response = false;
  101. }
  102. $cash_body_request = new CASHRequest(
  103. array(
  104. 'cash_request_type' => 'element',
  105. 'cash_action' => 'getmarkup',
  106. 'id' => $element_id,
  107. 'status_uid' => $status_uid,
  108. 'original_request' => $original_request,
  109. 'original_response' => $original_response,
  110. 'access_method' => $access_method,
  111. 'location' => $location
  112. )
  113. );
  114. if ($cash_body_request->response['status_uid'] == 'element_getmarkup_400') {
  115. // there was no element found. so you know...punt
  116. echo '<div class="cashmusic error">Element #' . $element_id . ' could not be found.</div>';
  117. }
  118. if (is_string($cash_body_request->response['payload'])) {
  119. // element found and happy. spit it out.
  120. echo $cash_body_request->response['payload'];
  121. }
  122. if ($cash_body_request->sessionGet('initialized_element_' . $element_id,'script')) {
  123. // second half of a wrapper element — fringe case
  124. if (ob_get_level()) {
  125. ob_flush();
  126. }
  127. }
  128. $cash_body_request->embedSessionPixel();
  129. unset($cash_page_request);
  130. unset($cash_body_request);
  131. }
  132. /**
  133. * Gets the contents from a URL. First tries file_get_contents then cURL.
  134. * If neither of those work, then the server asks a friend to print out the
  135. * page at the URL and mail it to the data center. Since this takes a couple
  136. * days we return false, but that's taking nothing away from the Postal
  137. * service. They've got a hard job, so say thank you next time you get some
  138. * mail from the postman.
  139. *
  140. * @return string
  141. */public static function getURLContents($data_url,$post_data=false,$ignore_errors=false) {
  142. $url_contents = false;
  143. $user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.5; rv:7.0) Gecko/20100101 Firefox/7.0';
  144. $do_post = is_array($post_data);
  145. if ($do_post) {
  146. $post_query = http_build_query($post_data);
  147. $post_length = count($post_data);
  148. }
  149. if (ini_get('allow_url_fopen')) {
  150. // try with fopen wrappers
  151. $options = array(
  152. 'http' => array(
  153. 'protocol_version'=>'1.1',
  154. 'header'=>array(
  155. 'Connection: close'
  156. ),
  157. 'user_agent' => $user_agent
  158. ));
  159. if ($do_post) {
  160. $options['http']['method'] = 'POST';
  161. $options['http']['content'] = $post_query;
  162. }
  163. if ($ignore_errors) {
  164. $options['http']['ignore_errors'] = true;
  165. }
  166. $context = stream_context_create($options);
  167. $url_contents = @file_get_contents($data_url,false,$context);
  168. } elseif (in_array('curl', get_loaded_extensions())) {
  169. // fall back to cURL
  170. $ch = curl_init();
  171. $timeout = 20;
  172. @curl_setopt($ch,CURLOPT_URL,$data_url);
  173. if ($do_post) {
  174. curl_setopt($ch,CURLOPT_POST,$post_length);
  175. curl_setopt($ch,CURLOPT_POSTFIELDS,$post_query);
  176. }
  177. @curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
  178. @curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  179. @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,$timeout);
  180. @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  181. @curl_setopt($ch, CURLOPT_AUTOREFERER, true);
  182. @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  183. @curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  184. if ($ignore_errors) {
  185. @curl_setopt($ch, CURLOPT_FAILONERROR, false);
  186. } else {
  187. @curl_setopt($ch, CURLOPT_FAILONERROR, true);
  188. }
  189. $data = curl_exec($ch);
  190. curl_close($ch);
  191. $url_contents = $data;
  192. }
  193. return $url_contents;
  194. }
  195. /**
  196. * If the function name doesn't describe what this one does well enough then
  197. * seriously: you need to stop reading the comments and not worry about it
  198. *
  199. */public static function autoloadClasses($classname) {
  200. foreach (array('/classes/core/','/classes/seeds/') as $location) {
  201. $file = CASH_PLATFORM_ROOT.$location.$classname.'.php';
  202. if (file_exists($file)) {
  203. // using 'include' instead of 'require_once' because of efficiency
  204. include($file);
  205. }
  206. }
  207. }
  208. /**
  209. * Gets API credentials for the effective or actual user
  210. *
  211. * @param {string} effective || actual
  212. * @return array
  213. */public static function getAPICredentials($user_type='effective') {
  214. $data_request = new CASHRequest(null);
  215. $user_id = $data_request->sessionGet('cash_' . $user_type . '_user');
  216. if ($user_id) {
  217. $data_request = new CASHRequest(
  218. array(
  219. 'cash_request_type' => 'system',
  220. 'cash_action' => 'getapicredentials',
  221. 'user_id' => $user_id
  222. )
  223. );
  224. return $data_request->response['payload'];
  225. }
  226. return false;
  227. }
  228. /**
  229. * Very basic. Takes a URL and checks if headers have been sent. If not we
  230. * do a proper location header redirect. If headers have been sent it
  231. * returns a line of JS to initiate a client-side redirect.
  232. *
  233. * @return none
  234. */public static function redirectToUrl($url) {
  235. if (!headers_sent()) {
  236. header("Location: $url");
  237. exit;
  238. } else {
  239. $output_script = '<script type="text/javascript">window.location = "' . $url . '";</script>';
  240. echo $output_script;
  241. return $output_script;
  242. }
  243. }
  244. public static function findReplaceInFile($filename,$find,$replace) {
  245. if (is_file($filename)) {
  246. $file = file_get_contents($filename);
  247. $file = str_replace($find, $replace, $file);
  248. if (file_put_contents($filename, $file)) {
  249. return true;
  250. } else {
  251. return false;
  252. }
  253. } else {
  254. return false;
  255. }
  256. }
  257. public static function getSystemSettings($setting_name='all') {
  258. $cash_settings = json_decode(getenv('cashmusic_platform_settings'),true);
  259. if (!$cash_settings) {
  260. $cash_settings = parse_ini_file(CASH_PLATFORM_ROOT.'/settings/cashmusic.ini.php');
  261. // check for system connections in environment and on file
  262. $system_connections = json_decode(getenv('cashmusic_system_connections'),true);
  263. if (!$system_connections && file_exists(CASH_PLATFORM_ROOT.'/settings/connections.json')) {
  264. $system_connections = json_decode(file_get_contents(CASH_PLATFORM_ROOT.'/settings/connections.json'),true);
  265. }
  266. if ($system_connections) {
  267. $cash_settings['system_connections'] = $system_connections;
  268. }
  269. // put all the settings into the current environment
  270. $json_settings = json_encode($cash_settings);
  271. putenv("cashmusic_platform_settings=$json_settings");
  272. } else {
  273. // so we found the environment variable — if we're on file-based settings the 'system_connections'
  274. // would be set. if we're purely environment variables they wouldn't be present, so we add them
  275. if (!isset($cash_settings['system_connections'])) {
  276. if (file_exists(CASH_PLATFORM_ROOT.'/settings/connections.json')) {
  277. $cash_settings['system_connections'] = json_decode(file_get_contents(CASH_PLATFORM_ROOT.'/settings/connections.json'),true);
  278. }
  279. $system_connections = json_decode(getenv('cashmusic_connection_settings'),true);
  280. if ($system_connections) {
  281. $cash_settings['system_connections'] = $system_connections;
  282. }
  283. }
  284. }
  285. if ($setting_name == 'all') {
  286. return $cash_settings;
  287. } else {
  288. if (array_key_exists($setting_name, $cash_settings)) {
  289. return $cash_settings[$setting_name];
  290. } else {
  291. return false;
  292. }
  293. }
  294. }
  295. public static function setSystemSetting($setting_name=false,$value='') {
  296. if ($setting_name) {
  297. $cash_settings = CASHSystem::getSystemSettings();
  298. // if ($cash_settings['instancetype'] != 'multi') { --- DISABLED SINGLE-USER ONLY BECAUSE WHY?
  299. if (array_key_exists($setting_name, $cash_settings)) {
  300. $success = CASHSystem::findReplaceInFile(
  301. CASH_PLATFORM_ROOT.'/settings/cashmusic.ini.php',
  302. $setting_name . ' = "' . $cash_settings[$setting_name],
  303. $setting_name . ' = "' . $value
  304. );
  305. if ($success) {
  306. $cash_settings[$setting_name] = $value;
  307. $json_settings = json_encode($cash_settings);
  308. putenv("cashmusic_platform_settings=$json_settings");
  309. return true;
  310. }
  311. }
  312. //}
  313. return false;
  314. } else {
  315. return false;
  316. }
  317. }
  318. /**
  319. * Super basic XOR encoding — used for encoding connection data
  320. *
  321. */public static function simpleXOR($input, $key = false) {
  322. if (!$key) {
  323. $key = CASHSystem::getSystemSettings('salt');
  324. }
  325. // append key on itself until it is longer than the input
  326. while (strlen($key) < strlen($input)) { $key .= $key; }
  327. // trim key to the length of the input
  328. $key = substr($key, 0, strlen($input));
  329. // Simple XOR'ing, each input byte with each key byte.
  330. $result = '';
  331. for ($i = 0; $i < strlen($input); $i++) {
  332. $result .= $input{$i} ^ $key{$i};
  333. }
  334. return $result;
  335. }
  336. /**
  337. * Formats a proper response, stores it in the session, and returns it
  338. *
  339. * @return array
  340. */public static function getRemoteIP() {
  341. $proxy = '';
  342. if(!defined('STDIN')) {
  343. if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
  344. if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
  345. $proxy = $_SERVER["HTTP_CLIENT_IP"];
  346. } else {
  347. $proxy = $_SERVER["REMOTE_ADDR"];
  348. }
  349. $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
  350. } else {
  351. if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
  352. $ip = $_SERVER["HTTP_CLIENT_IP"];
  353. } else {
  354. $ip = $_SERVER["REMOTE_ADDR"];
  355. }
  356. }
  357. } else {
  358. $ip = 'local';
  359. }
  360. $ip_and_proxy = array(
  361. 'ip' => $ip,
  362. 'proxy' => $proxy
  363. );
  364. return $ip_and_proxy;
  365. }
  366. /**
  367. * Returns the (best guess at) current URL or false for CLI access
  368. *
  369. * @return array
  370. */public static function getCurrentURL($domain_only=false) {
  371. if(!defined('STDIN')) { // check for command line
  372. if ($domain_only) {
  373. return strtok($_SERVER['HTTP_HOST'],':');
  374. } else {
  375. $protocol = 'http';
  376. if (isset($_SERVER['HTTPS'])) {
  377. if ($_SERVER['HTTPS']!=="off" || !$_SERVER['HTTPS']) {
  378. $protocol = 'https';
  379. }
  380. }
  381. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
  382. if ($_SERVER['HTTP_X_FORWARDED_PROTO']=="https") {
  383. $protocol = 'https';
  384. }
  385. }
  386. $root = $protocol.'://'.$_SERVER['HTTP_HOST'];
  387. $page = strtok($_SERVER['REQUEST_URI'],'?');
  388. return $root.$page;
  389. }
  390. } else {
  391. return false;
  392. }
  393. }
  394. /**
  395. * Takes a datestamp or a string capable of being converted to a datestamp and
  396. * returns a "23 minutes ago" type string for it. Now you can be cute like
  397. * Twitter.
  398. *
  399. * @return string
  400. */public static function formatTimeAgo($time) {
  401. if (is_string($time)) {
  402. if (is_numeric($time)) {
  403. $datestamp = (int) $time;
  404. } else {
  405. $datestamp = strtotime($time);
  406. }
  407. } else {
  408. $datestamp = $time;
  409. }
  410. $seconds = floor((time() - $datestamp));
  411. if ($seconds < 60) {
  412. $ago_str = $seconds . ' seconds ago';
  413. } else if ($seconds >= 60 && $seconds < 120) {
  414. $ago_str = '1 minute ago';
  415. } else if ($seconds >= 120 && $seconds < 3600) {
  416. $ago_str = floor($seconds / 60) .' minutes ago';
  417. } else if ($seconds >= 3600 && $seconds < 7200) {
  418. $ago_str = '1 hour ago';
  419. } else if ($seconds >= 7200 && $seconds < 86400) {
  420. $ago_str = floor($seconds / 3600) .' hours ago';
  421. } else if ($seconds >= 86400 && $seconds < 31536000) {
  422. $ago_str = date('d M', $datestamp);
  423. } else {
  424. $ago_str = date('d M, y', $datestamp);
  425. }
  426. return $ago_str;
  427. }
  428. public static function formatCount($val) {
  429. if ($val > 999 && $val <= 99999) {
  430. $result = round((float)$val / 1000, 1) . 'K';
  431. } elseif ($val > 99999 && $val <= 999999) {
  432. $result = floor($val / 1000) . 'K';
  433. } elseif ($val > 999999) {
  434. $result = round((float)$val / 1000000, 1) . 'M';
  435. } else {
  436. $result = $val;
  437. }
  438. return $result;
  439. }
  440. /**
  441. * Turns plain text links into HYPERlinks. Welcome to the future, chump.
  442. *
  443. * Stole all the regex from:
  444. * http://buildinternet.com/2010/05/how-to-automatically-linkify-text-with-php-regular-expressions/
  445. * (Because I stink at regex.)
  446. *
  447. * @return string
  448. */public static function linkifyText($text,$twitter=false) {
  449. $text= preg_replace("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a href=\"$3\">$3</a>", $text);
  450. $text= preg_replace("/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"http://$3\">$3</a>", $text);
  451. $text= preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"mailto:$2@$3\">$2@$3</a>", $text);
  452. if ($twitter) {
  453. $text= preg_replace("/@(\w+)/", '<a href="http://www.twitter.com/$1" target="_blank">@$1</a>', $text);
  454. $text= preg_replace("/\#(\w+)/", '<a href="http://search.twitter.com/search?q=$1" target="_blank">#$1</a>',$text);
  455. }
  456. return $text;
  457. }
  458. /*
  459. * Returns the system default email address from the settings ini file
  460. *
  461. * USAGE:
  462. * ASHSystem::getDefaultEmail();
  463. *
  464. */public static function getDefaultEmail($all_settings=false) {
  465. $cash_settings = CASHSystem::getSystemSettings();
  466. if (!$all_settings) {
  467. return $cash_settings['systememail'];
  468. } else {
  469. $return_array = array(
  470. 'systememail' => $cash_settings['systememail'],
  471. 'smtp' => $cash_settings['smtp'],
  472. 'smtpserver' => $cash_settings['smtpserver'],
  473. 'smtpport' => $cash_settings['smtpport'],
  474. 'smtpusername' => $cash_settings['smtpusername'],
  475. 'smtppassword' => $cash_settings['smtppassword'],
  476. );
  477. return $return_array;
  478. }
  479. }
  480. public static function notExplicitFalse($test) {
  481. if ($test === false) {
  482. return false;
  483. } else {
  484. return true;
  485. }
  486. }
  487. /*
  488. * Sends a plain text and HTML email for system things like email verification,
  489. * password resets, etc.
  490. *
  491. * USAGE:
  492. * CASHSystem::sendEmail('test email','CASH Music <info@cashmusic.org>','dev@cashmusic.org','message, with link: http://cashmusic.org/','title');
  493. *
  494. */public static function sendEmail($subject,$user_id,$toaddress,$message_text,$message_title,$encoded_html=false) {
  495. // pulling out just the TO email from a 'Address Name <address@name.com>' style address:
  496. if (strpos($toaddress, '>')) {
  497. preg_match('/([^<]+)\s<(.*)>/', $toaddress, $matches);
  498. if (count($matches)) {
  499. $toaddress = $matches[2];
  500. }
  501. }
  502. // if the email is bullshit don't try to send to it:
  503. if (!filter_var($toaddress, FILTER_VALIDATE_EMAIL)) {
  504. return false;
  505. }
  506. // TODO: look up user settings for email if user_id is set — allow for multiple SMTP settings
  507. // on a per-user basis in the multi-user system
  508. $email_settings = CASHSystem::getDefaultEmail(true);
  509. if (CASHSystem::getSystemSettings('instancetype') == 'multi' && $user_id) {
  510. $user_request = new CASHRequest(
  511. array(
  512. 'cash_request_type' => 'people',
  513. 'cash_action' => 'getuser',
  514. 'user_id' => $user_id
  515. )
  516. );
  517. $user_details = $user_request->response['payload'];
  518. $setname = false;
  519. if (trim($user_details['display_name'] . '') !== '' && $user_details['display_name'] !== 'Anonymous') {
  520. $setname = $user_details['display_name'];
  521. }
  522. if (!$setname && $user_details['username']) {
  523. $setname = $user_details['username'];
  524. }
  525. if ($setname) {
  526. $fromaddress = $setname . ' <' . $user_details['email_address'] . '>';
  527. } else {
  528. $fromaddress = $user_details['email_address'];
  529. }
  530. } else {
  531. $fromaddress = $email_settings['systememail'];
  532. }
  533. // let's deal with complex versus simple email addresses. if we find '>' present we try
  534. // parsing for name + address from a 'Address Name <address@name.com>' style email:
  535. if (strpos($fromaddress, '>')) {
  536. preg_match('/([^<]+)\s<(.*)>/', $fromaddress, $matches);
  537. if (count($matches)) {
  538. $from = array($matches[2] => $matches[1]);
  539. } else {
  540. $from = $fromaddress;
  541. }
  542. } else {
  543. $from = $fromaddress;
  544. }
  545. // handle encoding of HTML if specific HTML isn't passed in:
  546. if (!$encoded_html) {
  547. $template = @file_get_contents(CASH_PLATFORM_ROOT . '/settings/defaults/system_email.mustache');
  548. $encoded_html = str_replace("\n","<br />\n",preg_replace('/(http:\/\/(\S*))/', '<a href="\1">\1</a>', $message_text));
  549. if (!$template) {
  550. $encoded_html .= '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>' . $message_title . '</title></head><body>'
  551. . "<h1>$message_title</h1>\n" . "<p>" . $encoded_html . "</p>"
  552. . "</body></html>";
  553. } else {
  554. // open up some mustache in here:
  555. include_once(CASH_PLATFORM_ROOT . '/lib/mustache/Mustache.php');
  556. $higgins = new Mustache;
  557. $mustache_vars = array(
  558. 'encoded_html' => $encoded_html,
  559. 'message_title' => $message_title,
  560. 'cdn_url' => (defined('CDN_URL')) ? CDN_URL : CASH_ADMIN_URL
  561. );
  562. $encoded_html = $higgins->render($template, $mustache_vars);
  563. }
  564. }
  565. // deal with SMTP settings later:
  566. $smtp = $email_settings['smtp'];
  567. // include swift mailer
  568. include_once CASH_PLATFORM_ROOT . '/lib/swift/swift_required.php';
  569. if ($smtp) {
  570. // use SMTP settings for goodtimes robust happy mailing
  571. $transport = Swift_SmtpTransport::newInstance($email_settings['smtpserver'], $email_settings['smtpport']);
  572. if ($email_settings['smtpusername']) {
  573. $transport->setUsername($email_settings['smtpusername']);
  574. $transport->setPassword($email_settings['smtppassword']);
  575. }
  576. } else {
  577. // aww shit. use mail() and hope it gets there
  578. $transport = Swift_MailTransport::newInstance();
  579. }
  580. $swift = Swift_Mailer::newInstance($transport);
  581. $message = new Swift_Message($subject);
  582. $message->setFrom($from);
  583. $message->setBody($encoded_html, 'text/html');
  584. $message->setTo($toaddress);
  585. $message->addPart($message_text, 'text/plain');
  586. $headers = $message->getHeaders();
  587. $headers->addTextHeader('X-MC-Track', 'opens'); // Mandrill-specific tracking...leave in by defauly, no harm if not Mandrill
  588. if ($recipients = $swift->send($message, $failures)) {
  589. return true;
  590. } else {
  591. return false;
  592. }
  593. }
  594. public static function getMimeTypeFor($path) {
  595. $types = array(
  596. 'json' => 'application/json',
  597. 'pdf' => 'application/pdf',
  598. 'woff' => 'application/font-woff',
  599. 'zip' => 'application/zip',
  600. 'gzip' => 'application/x-gzip',
  601. 'mp4' => 'audio/mp4',
  602. 'mp3' => 'audio/mpeg',
  603. 'ogg' => 'audio/ogg',
  604. 'flac' => 'audio/ogg',
  605. 'vorbis' => 'audio/vorbis',
  606. 'wav' => 'audio/vnd.wave',
  607. 'webm' => 'audio/webm',
  608. 'gif' => 'image/gif',
  609. 'jpg' => 'image/jpeg',
  610. 'jpeg' => 'image/jpeg',
  611. 'png' => 'image/png',
  612. 'svg' => 'image/svg+xml',
  613. 'tiff' => 'image/tiff',
  614. 'css' => 'text/css',
  615. 'csv' => 'text/csv',
  616. 'htm' => 'text/html',
  617. 'html' => 'text/html',
  618. 'js' => 'text/javascript',
  619. 'txt' => 'text/plain',
  620. 'mpeg' => 'video/mpeg',
  621. 'mpg' => 'video/mpeg',
  622. 'mp4' => 'video/mp4',
  623. 'mov' => 'video/quicktime',
  624. 'wmv' => 'video/x-ms-wmv',
  625. 'flv' => 'video/x-flv'
  626. );
  627. $extension = pathinfo($path,PATHINFO_EXTENSION);
  628. if ($extension) {
  629. if (isset($types[$extension])) {
  630. return $types[$extension];
  631. }
  632. } else {
  633. return 'application/octet-stream';
  634. }
  635. }
  636. public static function renderMustache($template,$vars_array) {
  637. include_once(CASH_PLATFORM_ROOT . '/lib/mustache/Mustache.php');
  638. $axelrod = new Mustache;
  639. return $axelrod->render($template,$vars_array);
  640. }
  641. public static function getConnectionTypeSettings($type_string) {
  642. $definition_location = CASH_PLATFORM_ROOT . '/settings/connections/' . $type_string . '.json';
  643. if (file_exists($definition_location)) {
  644. $settings_array = json_decode(file_get_contents($definition_location),true);
  645. return $settings_array;
  646. } else {
  647. return false;
  648. }
  649. }
  650. public static function getCurrencySymbol($iso_string) {
  651. $iso_string = strtoupper($iso_string);
  652. $currencies = array(
  653. 'USD' => '$',
  654. 'EUR' => '€',
  655. 'JPY' => '¥',
  656. 'GBP' => '£',
  657. 'AUD' => '$',
  658. 'CHF' => '(Fr) ',
  659. 'CAD' => '$',
  660. 'HKD' => '$',
  661. 'SEK' => '(kr) ',
  662. 'NZD' => '$',
  663. 'SGD' => '$',
  664. 'NOK' => '(kr) ',
  665. 'MXN' => '$'
  666. );
  667. if ($iso_string == 'ALL') {
  668. return $currencies;
  669. } else {
  670. if (isset($currencies[$iso_string])) {
  671. return $currencies[$iso_string];
  672. } else {
  673. return false;
  674. }
  675. }
  676. }
  677. } // END class
  678. ?>