Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1238 lines
37 KiB

8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
8 years ago
8 years ago
8 years ago
  1. <?php
  2. // curl wrapper. If binary flag is true, return binary
  3. // results.
  4. // Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
  5. // to preserve cookies from one request to the next.
  6. if(! function_exists('fetch_url')) {
  7. function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_content=Null, $cookiejar = 0) {
  8. $stamp1 = microtime(true);
  9. $a = get_app();
  10. $ch = @curl_init($url);
  11. if(($redirects > 8) || (! $ch))
  12. return false;
  13. @curl_setopt($ch, CURLOPT_HEADER, true);
  14. if($cookiejar) {
  15. curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiejar);
  16. curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiejar);
  17. }
  18. // These settings aren't needed. We're following the location already.
  19. // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  20. // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
  21. if (!is_null($accept_content)){
  22. curl_setopt($ch,CURLOPT_HTTPHEADER, array (
  23. "Accept: " . $accept_content
  24. ));
  25. }
  26. @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
  27. @curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION.")");
  28. if(intval($timeout)) {
  29. @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  30. }
  31. else {
  32. $curl_time = intval(get_config('system','curl_timeout'));
  33. @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
  34. }
  35. // by default we will allow self-signed certs
  36. // but you can override this
  37. $check_cert = get_config('system','verifyssl');
  38. @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
  39. $prx = get_config('system','proxy');
  40. if(strlen($prx)) {
  41. @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
  42. @curl_setopt($ch, CURLOPT_PROXY, $prx);
  43. $prxusr = @get_config('system','proxyuser');
  44. if(strlen($prxusr))
  45. @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
  46. }
  47. if($binary)
  48. @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
  49. $a->set_curl_code(0);
  50. // don't let curl abort the entire application
  51. // if it throws any errors.
  52. $s = @curl_exec($ch);
  53. $base = $s;
  54. $curl_info = @curl_getinfo($ch);
  55. $http_code = $curl_info['http_code'];
  56. logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
  57. $header = '';
  58. // Pull out multiple headers, e.g. proxy and continuation headers
  59. // allow for HTTP/2.x without fixing code
  60. while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
  61. $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
  62. $header .= $chunk;
  63. $base = substr($base,strlen($chunk));
  64. }
  65. if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
  66. $new_location_info = @parse_url($curl_info["redirect_url"]);
  67. $old_location_info = @parse_url($curl_info["url"]);
  68. $newurl = $curl_info["redirect_url"];
  69. if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
  70. $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
  71. $matches = array();
  72. if (preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches)) {
  73. $newurl = trim(array_pop($matches));
  74. }
  75. if(strpos($newurl,'/') === 0)
  76. $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
  77. if (filter_var($newurl, FILTER_VALIDATE_URL)) {
  78. $redirects++;
  79. return fetch_url($newurl,$binary,$redirects,$timeout,$accept_content,$cookiejar);
  80. }
  81. }
  82. $a->set_curl_code($http_code);
  83. $a->set_curl_content_type($curl_info['content_type']);
  84. $body = substr($s,strlen($header));
  85. $a->set_curl_headers($header);
  86. @curl_close($ch);
  87. $a->save_timestamp($stamp1, "network");
  88. return($body);
  89. }}
  90. // post request to $url. $params is an array of post variables.
  91. if(! function_exists('post_url')) {
  92. function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
  93. $stamp1 = microtime(true);
  94. $a = get_app();
  95. $ch = curl_init($url);
  96. if(($redirects > 8) || (! $ch))
  97. return false;
  98. logger("post_url: start ".$url, LOGGER_DATA);
  99. curl_setopt($ch, CURLOPT_HEADER, true);
  100. curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
  101. curl_setopt($ch, CURLOPT_POST,1);
  102. curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
  103. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION.")");
  104. if(intval($timeout)) {
  105. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  106. }
  107. else {
  108. $curl_time = intval(get_config('system','curl_timeout'));
  109. curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
  110. }
  111. if(defined('LIGHTTPD')) {
  112. if(!is_array($headers)) {
  113. $headers = array('Expect:');
  114. } else {
  115. if(!in_array('Expect:', $headers)) {
  116. array_push($headers, 'Expect:');
  117. }
  118. }
  119. }
  120. if($headers)
  121. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  122. $check_cert = get_config('system','verifyssl');
  123. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
  124. $prx = get_config('system','proxy');
  125. if(strlen($prx)) {
  126. curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
  127. curl_setopt($ch, CURLOPT_PROXY, $prx);
  128. $prxusr = get_config('system','proxyuser');
  129. if(strlen($prxusr))
  130. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
  131. }
  132. $a->set_curl_code(0);
  133. // don't let curl abort the entire application
  134. // if it throws any errors.
  135. $s = @curl_exec($ch);
  136. $base = $s;
  137. $curl_info = curl_getinfo($ch);
  138. $http_code = $curl_info['http_code'];
  139. logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
  140. $header = '';
  141. // Pull out multiple headers, e.g. proxy and continuation headers
  142. // allow for HTTP/2.x without fixing code
  143. while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
  144. $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
  145. $header .= $chunk;
  146. $base = substr($base,strlen($chunk));
  147. }
  148. if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
  149. $matches = array();
  150. preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
  151. $newurl = trim(array_pop($matches));
  152. if(strpos($newurl,'/') === 0)
  153. $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
  154. if (filter_var($newurl, FILTER_VALIDATE_URL)) {
  155. $redirects++;
  156. logger("post_url: redirect ".$url." to ".$newurl);
  157. return post_url($newurl,$params, $headers, $redirects, $timeout);
  158. //return fetch_url($newurl,false,$redirects,$timeout);
  159. }
  160. }
  161. $a->set_curl_code($http_code);
  162. $body = substr($s,strlen($header));
  163. $a->set_curl_headers($header);
  164. curl_close($ch);
  165. $a->save_timestamp($stamp1, "network");
  166. logger("post_url: end ".$url, LOGGER_DATA);
  167. return($body);
  168. }}
  169. // Generic XML return
  170. // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
  171. // of $st and an optional text <message> of $message and terminates the current process.
  172. if(! function_exists('xml_status')) {
  173. function xml_status($st, $message = '') {
  174. $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
  175. if($st)
  176. logger('xml_status returning non_zero: ' . $st . " message=" . $message);
  177. header( "Content-type: text/xml" );
  178. echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
  179. echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
  180. killme();
  181. }}
  182. if(! function_exists('http_status_exit')) {
  183. function http_status_exit($val) {
  184. $err = '';
  185. if($val >= 400)
  186. $err = 'Error';
  187. if($val >= 200 && $val < 300)
  188. $err = 'OK';
  189. logger('http_status_exit ' . $val);
  190. header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
  191. killme();
  192. }}
  193. // convert an XML document to a normalised, case-corrected array
  194. // used by webfinger
  195. if(! function_exists('convert_xml_element_to_array')) {
  196. function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {
  197. // If we're getting too deep, bail out
  198. if ($recursion_depth > 512) {
  199. return(null);
  200. }
  201. if (!is_string($xml_element) &&
  202. !is_array($xml_element) &&
  203. (get_class($xml_element) == 'SimpleXMLElement')) {
  204. $xml_element_copy = $xml_element;
  205. $xml_element = get_object_vars($xml_element);
  206. }
  207. if (is_array($xml_element)) {
  208. $result_array = array();
  209. if (count($xml_element) <= 0) {
  210. return (trim(strval($xml_element_copy)));
  211. }
  212. foreach($xml_element as $key=>$value) {
  213. $recursion_depth++;
  214. $result_array[strtolower($key)] =
  215. convert_xml_element_to_array($value, $recursion_depth);
  216. $recursion_depth--;
  217. }
  218. if ($recursion_depth == 0) {
  219. $temp_array = $result_array;
  220. $result_array = array(
  221. strtolower($xml_element_copy->getName()) => $temp_array,
  222. );
  223. }
  224. return ($result_array);
  225. } else {
  226. return (trim(strval($xml_element)));
  227. }
  228. }}
  229. // Given an email style address, perform webfinger lookup and
  230. // return the resulting DFRN profile URL, or if no DFRN profile URL
  231. // is located, returns an OStatus subscription template (prefixed
  232. // with the string 'stat:' to identify it as on OStatus template).
  233. // If this isn't an email style address just return $s.
  234. // Return an empty string if email-style addresses but webfinger fails,
  235. // or if the resultant personal XRD doesn't contain a supported
  236. // subscription/friend-request attribute.
  237. // amended 7/9/2011 to return an hcard which could save potentially loading
  238. // a lengthy content page to scrape dfrn attributes
  239. if(! function_exists('webfinger_dfrn')) {
  240. function webfinger_dfrn($s,&$hcard) {
  241. if(! strstr($s,'@')) {
  242. return $s;
  243. }
  244. $profile_link = '';
  245. $links = webfinger($s);
  246. logger('webfinger_dfrn: ' . $s . ':' . print_r($links,true), LOGGER_DATA);
  247. if(count($links)) {
  248. foreach($links as $link) {
  249. if($link['@attributes']['rel'] === NAMESPACE_DFRN)
  250. $profile_link = $link['@attributes']['href'];
  251. if($link['@attributes']['rel'] === NAMESPACE_OSTATUSSUB)
  252. $profile_link = 'stat:' . $link['@attributes']['template'];
  253. if($link['@attributes']['rel'] === 'http://microformats.org/profile/hcard')
  254. $hcard = $link['@attributes']['href'];
  255. }
  256. }
  257. return $profile_link;
  258. }}
  259. // Given an email style address, perform webfinger lookup and
  260. // return the array of link attributes from the personal XRD file.
  261. // On error/failure return an empty array.
  262. if(! function_exists('webfinger')) {
  263. function webfinger($s, $debug = false) {
  264. $host = '';
  265. if(strstr($s,'@')) {
  266. $host = substr($s,strpos($s,'@') + 1);
  267. }
  268. if(strlen($host)) {
  269. $tpl = fetch_lrdd_template($host);
  270. logger('webfinger: lrdd template: ' . $tpl);
  271. if(strlen($tpl)) {
  272. $pxrd = str_replace('{uri}', urlencode('acct:' . $s), $tpl);
  273. logger('webfinger: pxrd: ' . $pxrd);
  274. $links = fetch_xrd_links($pxrd);
  275. if(! count($links)) {
  276. // try with double slashes
  277. $pxrd = str_replace('{uri}', urlencode('acct://' . $s), $tpl);
  278. logger('webfinger: pxrd: ' . $pxrd);
  279. $links = fetch_xrd_links($pxrd);
  280. }
  281. return $links;
  282. }
  283. }
  284. return array();
  285. }}
  286. if(! function_exists('lrdd')) {
  287. function lrdd($uri, $debug = false) {
  288. $a = get_app();
  289. // default priority is host priority, host-meta first
  290. $priority = 'host';
  291. // All we have is an email address. Resource-priority is irrelevant
  292. // because our URI isn't directly resolvable.
  293. if(strstr($uri,'@')) {
  294. return(webfinger($uri));
  295. }
  296. // get the host meta file
  297. $host = @parse_url($uri);
  298. if($host) {
  299. $url = ((x($host,'scheme')) ? $host['scheme'] : 'http') . '://';
  300. $url .= $host['host'] . '/.well-known/host-meta' ;
  301. }
  302. else
  303. return array();
  304. logger('lrdd: constructed url: ' . $url);
  305. $xml = fetch_url($url);
  306. $headers = $a->get_curl_headers();
  307. if (! $xml)
  308. return array();
  309. logger('lrdd: host_meta: ' . $xml, LOGGER_DATA);
  310. if(! stristr($xml,'<xrd'))
  311. return array();
  312. $h = parse_xml_string($xml);
  313. if(! $h)
  314. return array();
  315. $arr = convert_xml_element_to_array($h);
  316. if(isset($arr['xrd']['property'])) {
  317. $property = $arr['crd']['property'];
  318. if(! isset($property[0]))
  319. $properties = array($property);
  320. else
  321. $properties = $property;
  322. foreach($properties as $prop)
  323. if((string) $prop['@attributes'] === 'http://lrdd.net/priority/resource')
  324. $priority = 'resource';
  325. }
  326. // save the links in case we need them
  327. $links = array();
  328. if(isset($arr['xrd']['link'])) {
  329. $link = $arr['xrd']['link'];
  330. if(! isset($link[0]))
  331. $links = array($link);
  332. else
  333. $links = $link;
  334. }
  335. // do we have a template or href?
  336. if(count($links)) {
  337. foreach($links as $link) {
  338. if($link['@attributes']['rel'] && attribute_contains($link['@attributes']['rel'],'lrdd')) {
  339. if(x($link['@attributes'],'template'))
  340. $tpl = $link['@attributes']['template'];
  341. elseif(x($link['@attributes'],'href'))
  342. $href = $link['@attributes']['href'];
  343. }
  344. }
  345. }
  346. if((! isset($tpl)) || (! strpos($tpl,'{uri}')))
  347. $tpl = '';
  348. if($priority === 'host') {
  349. if(strlen($tpl))
  350. $pxrd = str_replace('{uri}', urlencode($uri), $tpl);
  351. elseif(isset($href))
  352. $pxrd = $href;
  353. if(isset($pxrd)) {
  354. logger('lrdd: (host priority) pxrd: ' . $pxrd);
  355. $links = fetch_xrd_links($pxrd);
  356. return $links;
  357. }
  358. $lines = explode("\n",$headers);
  359. if(count($lines)) {
  360. foreach($lines as $line) {
  361. if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
  362. return(fetch_xrd_links($matches[1]));
  363. break;
  364. }
  365. }
  366. }
  367. }
  368. // priority 'resource'
  369. $html = fetch_url($uri);
  370. $headers = $a->get_curl_headers();
  371. logger('lrdd: headers=' . $headers, LOGGER_DEBUG);
  372. // don't try and parse raw xml as html
  373. if(! strstr($html,'<?xml')) {
  374. require_once('library/HTML5/Parser.php');
  375. try {
  376. $dom = HTML5_Parser::parse($html);
  377. } catch (DOMException $e) {
  378. logger('lrdd: parse error: ' . $e);
  379. }
  380. if(isset($dom) && $dom) {
  381. $items = $dom->getElementsByTagName('link');
  382. foreach($items as $item) {
  383. $x = $item->getAttribute('rel');
  384. if($x == "lrdd") {
  385. $pagelink = $item->getAttribute('href');
  386. break;
  387. }
  388. }
  389. }
  390. }
  391. if(isset($pagelink))
  392. return(fetch_xrd_links($pagelink));
  393. // next look in HTTP headers
  394. $lines = explode("\n",$headers);
  395. if(count($lines)) {
  396. foreach($lines as $line) {
  397. // TODO alter the following regex to support multiple relations (space separated)
  398. if((stristr($line,'link:')) && preg_match('/<([^>].*)>.*rel\=[\'\"]lrdd[\'\"]/',$line,$matches)) {
  399. $pagelink = $matches[1];
  400. break;
  401. }
  402. // don't try and run feeds through the html5 parser
  403. if(stristr($line,'content-type:') && ((stristr($line,'application/atom+xml')) || (stristr($line,'application/rss+xml'))))
  404. return array();
  405. if(stristr($html,'<rss') || stristr($html,'<feed'))
  406. return array();
  407. }
  408. }
  409. if(isset($pagelink))
  410. return(fetch_xrd_links($pagelink));
  411. // If we haven't found any links, return the host xrd links (which we have already fetched)
  412. if(isset($links))
  413. return $links;
  414. return array();
  415. }}
  416. // Given a host name, locate the LRDD template from that
  417. // host. Returns the LRDD template or an empty string on
  418. // error/failure.
  419. if(! function_exists('fetch_lrdd_template')) {
  420. function fetch_lrdd_template($host) {
  421. $tpl = '';
  422. $url1 = 'https://' . $host . '/.well-known/host-meta' ;
  423. $url2 = 'http://' . $host . '/.well-known/host-meta' ;
  424. $links = fetch_xrd_links($url1);
  425. logger('fetch_lrdd_template from: ' . $url1);
  426. logger('template (https): ' . print_r($links,true));
  427. if(! count($links)) {
  428. logger('fetch_lrdd_template from: ' . $url2);
  429. $links = fetch_xrd_links($url2);
  430. logger('template (http): ' . print_r($links,true));
  431. }
  432. if(count($links)) {
  433. foreach($links as $link)
  434. if($link['@attributes']['rel'] && $link['@attributes']['rel'] === 'lrdd' && (!$link['@attributes']['type'] || $link['@attributes']['type'] === 'application/xrd+xml'))
  435. $tpl = $link['@attributes']['template'];
  436. }
  437. if(! strpos($tpl,'{uri}'))
  438. $tpl = '';
  439. return $tpl;
  440. }}
  441. // Given a URL, retrieve the page as an XRD document.
  442. // Return an array of links.
  443. // on error/failure return empty array.
  444. if(! function_exists('fetch_xrd_links')) {
  445. function fetch_xrd_links($url) {
  446. $xrd_timeout = intval(get_config('system','xrd_timeout'));
  447. $redirects = 0;
  448. $xml = fetch_url($url,false,$redirects,(($xrd_timeout) ? $xrd_timeout : 20), "application/xrd+xml");
  449. logger('fetch_xrd_links: ' . $xml, LOGGER_DATA);
  450. if ((! $xml) || (! stristr($xml,'<xrd')))
  451. return array();
  452. // fix diaspora's bad xml
  453. $xml = str_replace(array('href=&quot;','&quot;/>'),array('href="','"/>'),$xml);
  454. $h = parse_xml_string($xml);
  455. if(! $h)
  456. return array();
  457. $arr = convert_xml_element_to_array($h);
  458. $links = array();
  459. if(isset($arr['xrd']['link'])) {
  460. $link = $arr['xrd']['link'];
  461. if(! isset($link[0]))
  462. $links = array($link);
  463. else
  464. $links = $link;
  465. }
  466. if(isset($arr['xrd']['alias'])) {
  467. $alias = $arr['xrd']['alias'];
  468. if(! isset($alias[0]))
  469. $aliases = array($alias);
  470. else
  471. $aliases = $alias;
  472. if(is_array($aliases) && count($aliases)) {
  473. foreach($aliases as $alias) {
  474. $links[]['@attributes'] = array('rel' => 'alias' , 'href' => $alias);
  475. }
  476. }
  477. }
  478. logger('fetch_xrd_links: ' . print_r($links,true), LOGGER_DATA);
  479. return $links;
  480. }}
  481. // Take a URL from the wild, prepend http:// if necessary
  482. // and check DNS to see if it's real (or check if is a valid IP address)
  483. // return true if it's OK, false if something is wrong with it
  484. if(! function_exists('validate_url')) {
  485. function validate_url(&$url) {
  486. // no naked subdomains (allow localhost for tests)
  487. if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
  488. return false;
  489. if(substr($url,0,4) != 'http')
  490. $url = 'http://' . $url;
  491. $h = @parse_url($url);
  492. if(($h) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
  493. return true;
  494. }
  495. return false;
  496. }}
  497. // checks that email is an actual resolvable internet address
  498. if(! function_exists('validate_email')) {
  499. function validate_email($addr) {
  500. if(get_config('system','disable_email_validation'))
  501. return true;
  502. if(! strpos($addr,'@'))
  503. return false;
  504. $h = substr($addr,strpos($addr,'@') + 1);
  505. if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
  506. return true;
  507. }
  508. return false;
  509. }}
  510. // Check $url against our list of allowed sites,
  511. // wildcards allowed. If allowed_sites is unset return true;
  512. // If url is allowed, return true.
  513. // otherwise, return false
  514. if(! function_exists('allowed_url')) {
  515. function allowed_url($url) {
  516. $h = @parse_url($url);
  517. if(! $h) {
  518. return false;
  519. }
  520. $str_allowed = get_config('system','allowed_sites');
  521. if(! $str_allowed)
  522. return true;
  523. $found = false;
  524. $host = strtolower($h['host']);
  525. // always allow our own site
  526. if($host == strtolower($_SERVER['SERVER_NAME']))
  527. return true;
  528. $fnmatch = function_exists('fnmatch');
  529. $allowed = explode(',',$str_allowed);
  530. if(count($allowed)) {
  531. foreach($allowed as $a) {
  532. $pat = strtolower(trim($a));
  533. if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
  534. $found = true;
  535. break;
  536. }
  537. }
  538. }
  539. return $found;
  540. }}
  541. // check if email address is allowed to register here.
  542. // Compare against our list (wildcards allowed).
  543. // Returns false if not allowed, true if allowed or if
  544. // allowed list is not configured.
  545. if(! function_exists('allowed_email')) {
  546. function allowed_email($email) {
  547. $domain = strtolower(substr($email,strpos($email,'@') + 1));
  548. if(! $domain)
  549. return false;
  550. $str_allowed = get_config('system','allowed_email');
  551. if(! $str_allowed)
  552. return true;
  553. $found = false;
  554. $fnmatch = function_exists('fnmatch');
  555. $allowed = explode(',',$str_allowed);
  556. if(count($allowed)) {
  557. foreach($allowed as $a) {
  558. $pat = strtolower(trim($a));
  559. if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
  560. $found = true;
  561. break;
  562. }
  563. }
  564. }
  565. return $found;
  566. }}
  567. if(! function_exists('avatar_img')) {
  568. function avatar_img($email) {
  569. $a = get_app();
  570. $avatar['size'] = 175;
  571. $avatar['email'] = $email;
  572. $avatar['url'] = '';
  573. $avatar['success'] = false;
  574. call_hooks('avatar_lookup', $avatar);
  575. if(! $avatar['success'])
  576. $avatar['url'] = $a->get_baseurl() . '/images/person-175.jpg';
  577. logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
  578. return $avatar['url'];
  579. }}
  580. if(! function_exists('parse_xml_string')) {
  581. function parse_xml_string($s,$strict = true) {
  582. if($strict) {
  583. if(! strstr($s,'<?xml'))
  584. return false;
  585. $s2 = substr($s,strpos($s,'<?xml'));
  586. }
  587. else
  588. $s2 = $s;
  589. libxml_use_internal_errors(true);
  590. $x = @simplexml_load_string($s2);
  591. if(! $x) {
  592. logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
  593. foreach(libxml_get_errors() as $err)
  594. logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
  595. libxml_clear_errors();
  596. }
  597. return $x;
  598. }}
  599. function add_fcontact($arr,$update = false) {
  600. if($update) {
  601. $r = q("UPDATE `fcontact` SET
  602. `name` = '%s',
  603. `photo` = '%s',
  604. `request` = '%s',
  605. `nick` = '%s',
  606. `addr` = '%s',
  607. `batch` = '%s',
  608. `notify` = '%s',
  609. `poll` = '%s',
  610. `confirm` = '%s',
  611. `alias` = '%s',
  612. `pubkey` = '%s',
  613. `updated` = '%s'
  614. WHERE `url` = '%s' AND `network` = '%s'",
  615. dbesc($arr['name']),
  616. dbesc($arr['photo']),
  617. dbesc($arr['request']),
  618. dbesc($arr['nick']),
  619. dbesc($arr['addr']),
  620. dbesc($arr['batch']),
  621. dbesc($arr['notify']),
  622. dbesc($arr['poll']),
  623. dbesc($arr['confirm']),
  624. dbesc($arr['alias']),
  625. dbesc($arr['pubkey']),
  626. dbesc(datetime_convert()),
  627. dbesc($arr['url']),
  628. dbesc($arr['network'])
  629. );
  630. }
  631. else {
  632. $r = q("insert into fcontact ( `url`,`name`,`photo`,`request`,`nick`,`addr`,
  633. `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated` )
  634. values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
  635. dbesc($arr['url']),
  636. dbesc($arr['name']),
  637. dbesc($arr['photo']),
  638. dbesc($arr['request']),
  639. dbesc($arr['nick']),
  640. dbesc($arr['addr']),
  641. dbesc($arr['batch']),
  642. dbesc($arr['notify']),
  643. dbesc($arr['poll']),
  644. dbesc($arr['confirm']),
  645. dbesc($arr['network']),
  646. dbesc($arr['alias']),
  647. dbesc($arr['pubkey']),
  648. dbesc(datetime_convert())
  649. );
  650. }
  651. return $r;
  652. }
  653. function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
  654. // Suppress "view full size"
  655. if (intval(get_config('system','no_view_full_size')))
  656. $include_link = false;
  657. $a = get_app();
  658. // Picture addresses can contain special characters
  659. $s = htmlspecialchars_decode($srctext);
  660. $matches = null;
  661. $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
  662. if($c) {
  663. require_once('include/Photo.php');
  664. foreach($matches as $mtch) {
  665. logger('scale_external_image: ' . $mtch[1]);
  666. $hostname = str_replace('www.','',substr($a->get_baseurl(),strpos($a->get_baseurl(),'://')+3));
  667. if(stristr($mtch[1],$hostname))
  668. continue;
  669. // $scale_replace, if passed, is an array of two elements. The
  670. // first is the name of the full-size image. The second is the
  671. // name of a remote, scaled-down version of the full size image.
  672. // This allows Friendica to display the smaller remote image if
  673. // one exists, while still linking to the full-size image
  674. if($scale_replace)
  675. $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
  676. else
  677. $scaled = $mtch[1];
  678. $i = @fetch_url($scaled);
  679. if(! $i)
  680. return $srctext;
  681. $cachefile = get_cachefile(hash("md5", $scaled));
  682. if ($cachefile != '') {
  683. $stamp1 = microtime(true);
  684. file_put_contents($cachefile, $i);
  685. $a->save_timestamp($stamp1, "file");
  686. }
  687. // guess mimetype from headers or filename
  688. $type = guess_image_type($mtch[1],true);
  689. if($i) {
  690. $ph = new Photo($i, $type);
  691. if($ph->is_valid()) {
  692. $orig_width = $ph->getWidth();
  693. $orig_height = $ph->getHeight();
  694. if($orig_width > 640 || $orig_height > 640) {
  695. $ph->scaleImage(640);
  696. $new_width = $ph->getWidth();
  697. $new_height = $ph->getHeight();
  698. logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
  699. $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
  700. . "\n" . (($include_link)
  701. ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
  702. : ''),$s);
  703. logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
  704. }
  705. }
  706. }
  707. }
  708. }
  709. // replace the special char encoding
  710. $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
  711. return $s;
  712. }
  713. function fix_contact_ssl_policy(&$contact,$new_policy) {
  714. $ssl_changed = false;
  715. if((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
  716. $ssl_changed = true;
  717. $contact['url'] = str_replace('https:','http:',$contact['url']);
  718. $contact['request'] = str_replace('https:','http:',$contact['request']);
  719. $contact['notify'] = str_replace('https:','http:',$contact['notify']);
  720. $contact['poll'] = str_replace('https:','http:',$contact['poll']);
  721. $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
  722. $contact['poco'] = str_replace('https:','http:',$contact['poco']);
  723. }
  724. if((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
  725. $ssl_changed = true;
  726. $contact['url'] = str_replace('http:','https:',$contact['url']);
  727. $contact['request'] = str_replace('http:','https:',$contact['request']);
  728. $contact['notify'] = str_replace('http:','https:',$contact['notify']);
  729. $contact['poll'] = str_replace('http:','https:',$contact['poll']);
  730. $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
  731. $contact['poco'] = str_replace('http:','https:',$contact['poco']);
  732. }
  733. if($ssl_changed) {
  734. q("update contact set
  735. url = '%s',
  736. request = '%s',
  737. notify = '%s',
  738. poll = '%s',
  739. confirm = '%s',
  740. poco = '%s'
  741. where id = %d limit 1",
  742. dbesc($contact['url']),
  743. dbesc($contact['request']),
  744. dbesc($contact['notify']),
  745. dbesc($contact['poll']),
  746. dbesc($contact['confirm']),
  747. dbesc($contact['poco']),
  748. intval($contact['id'])
  749. );
  750. }
  751. }
  752. /**
  753. * xml2array() will convert the given XML text to an array in the XML structure.
  754. * Link: http://www.bin-co.com/php/scripts/xml2array/
  755. * Portions significantly re-written by mike@macgirvin.com for Friendica (namespaces, lowercase tags, get_attribute default changed, more...)
  756. * Arguments : $contents - The XML text
  757. * $namespaces - true or false include namespace information in the returned array as array elements.
  758. * $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value.
  759. * $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
  760. * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
  761. * Examples: $array = xml2array(file_get_contents('feed.xml'));
  762. * $array = xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
  763. */
  764. function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
  765. if(!$contents) return array();
  766. if(!function_exists('xml_parser_create')) {
  767. logger('xml2array: parser function missing');
  768. return array();
  769. }
  770. libxml_use_internal_errors(true);
  771. libxml_clear_errors();
  772. if($namespaces)
  773. $parser = @xml_parser_create_ns("UTF-8",':');
  774. else
  775. $parser = @xml_parser_create();
  776. if(! $parser) {
  777. logger('xml2array: xml_parser_create: no resource');
  778. return array();
  779. }
  780. xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
  781. // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
  782. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  783. xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  784. @xml_parse_into_struct($parser, trim($contents), $xml_values);
  785. @xml_parser_free($parser);
  786. if(! $xml_values) {
  787. logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
  788. foreach(libxml_get_errors() as $err)
  789. logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
  790. libxml_clear_errors();
  791. return;
  792. }
  793. //Initializations
  794. $xml_array = array();
  795. $parents = array();
  796. $opened_tags = array();
  797. $arr = array();
  798. $current = &$xml_array; // Reference
  799. // Go through the tags.
  800. $repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
  801. foreach($xml_values as $data) {
  802. unset($attributes,$value); // Remove existing values, or there will be trouble
  803. // This command will extract these variables into the foreach scope
  804. // tag(string), type(string), level(int), attributes(array).
  805. extract($data); // We could use the array by itself, but this cooler.
  806. $result = array();
  807. $attributes_data = array();
  808. if(isset($value)) {
  809. if($priority == 'tag') $result = $value;
  810. else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
  811. }
  812. //Set the attributes too.
  813. if(isset($attributes) and $get_attributes) {
  814. foreach($attributes as $attr => $val) {
  815. if($priority == 'tag') $attributes_data[$attr] = $val;
  816. else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
  817. }
  818. }
  819. // See tag status and do the needed.
  820. if($namespaces && strpos($tag,':')) {
  821. $namespc = substr($tag,0,strrpos($tag,':'));
  822. $tag = strtolower(substr($tag,strlen($namespc)+1));
  823. $result['@namespace'] = $namespc;
  824. }
  825. $tag = strtolower($tag);
  826. if($type == "open") { // The starting of the tag '<tag>'
  827. $parent[$level-1] = &$current;
  828. if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
  829. $current[$tag] = $result;
  830. if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
  831. $repeated_tag_index[$tag.'_'.$level] = 1;
  832. $current = &$current[$tag];
  833. } else { // There was another element with the same tag name
  834. if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
  835. $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
  836. $repeated_tag_index[$tag.'_'.$level]++;
  837. } else { // This section will make the value an array if multiple tags with the same name appear together
  838. $current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
  839. $repeated_tag_index[$tag.'_'.$level] = 2;
  840. if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
  841. $current[$tag]['0_attr'] = $current[$tag.'_attr'];
  842. unset($current[$tag.'_attr']);
  843. }
  844. }
  845. $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
  846. $current = &$current[$tag][$last_item_index];
  847. }
  848. } elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
  849. //See if the key is already taken.
  850. if(!isset($current[$tag])) { //New Key
  851. $current[$tag] = $result;
  852. $repeated_tag_index[$tag.'_'.$level] = 1;
  853. if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
  854. } else { // If taken, put all things inside a list(array)
  855. if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...
  856. // ...push the new element into that array.
  857. $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
  858. if($priority == 'tag' and $get_attributes and $attributes_data) {
  859. $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
  860. }
  861. $repeated_tag_index[$tag.'_'.$level]++;
  862. } else { // If it is not an array...
  863. $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
  864. $repeated_tag_index[$tag.'_'.$level] = 1;
  865. if($priority == 'tag' and $get_attributes) {
  866. if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
  867. $current[$tag]['0_attr'] = $current[$tag.'_attr'];
  868. unset($current[$tag.'_attr']);
  869. }
  870. if($attributes_data) {
  871. $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
  872. }
  873. }
  874. $repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
  875. }
  876. }
  877. } elseif($type == 'close') { // End of tag '</tag>'
  878. $current = &$parent[$level-1];
  879. }
  880. }
  881. return($xml_array);
  882. }
  883. function original_url($url, $depth=1, $fetchbody = false) {
  884. // Remove Analytics Data from Google and other tracking platforms
  885. $urldata = parse_url($url);
  886. if (is_string($urldata["query"])) {
  887. $query = $urldata["query"];
  888. parse_str($query, $querydata);
  889. if (is_array($querydata))
  890. foreach ($querydata AS $param=>$value)
  891. if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
  892. "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
  893. "fb_action_ids", "fb_action_types", "fb_ref",
  894. "awesm",
  895. "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
  896. $pair = $param."=".urlencode($value);
  897. $url = str_replace($pair, "", $url);
  898. // Second try: if the url isn't encoded completely
  899. $pair = $param."=".str_replace(" ", "+", $value);
  900. $url = str_replace($pair, "", $url);
  901. // Third try: Maybey the url isn't encoded at all
  902. $pair = $param."=".$value;
  903. $url = str_replace($pair, "", $url);
  904. $url = str_replace(array("?&", "&&"), array("?", ""), $url);
  905. }
  906. if (substr($url, -1, 1) == "?")
  907. $url = substr($url, 0, -1);
  908. }
  909. if ($depth > 10)
  910. return($url);
  911. $url = trim($url, "'");
  912. $siteinfo = array();
  913. $ch = curl_init();
  914. curl_setopt($ch, CURLOPT_URL, $url);
  915. curl_setopt($ch, CURLOPT_HEADER, 1);
  916. if ($fetchbody)
  917. curl_setopt($ch, CURLOPT_NOBODY, 0);
  918. else
  919. curl_setopt($ch, CURLOPT_NOBODY, 1);
  920. curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  921. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  922. curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION.")");
  923. $header = curl_exec($ch);
  924. $curl_info = @curl_getinfo($ch);
  925. $http_code = $curl_info['http_code'];
  926. curl_close($ch);
  927. if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
  928. AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
  929. if ($curl_info['redirect_url'] != "")
  930. return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
  931. else
  932. return(original_url($curl_info['location'], ++$depth, $fetchbody));
  933. }
  934. $pos = strpos($header, "\r\n\r\n");
  935. if ($pos)
  936. $body = trim(substr($header, $pos));
  937. else
  938. $body = $header;
  939. if (trim($body) == "")
  940. return(original_url($url, ++$depth, true));
  941. $doc = new DOMDocument();
  942. @$doc->loadHTML($body);
  943. $xpath = new DomXPath($doc);
  944. $list = $xpath->query("//meta[@content]");
  945. foreach ($list as $node) {
  946. $attr = array();
  947. if ($node->attributes->length)
  948. foreach ($node->attributes as $attribute)
  949. $attr[$attribute->name] = $attribute->value;
  950. if (@$attr["http-equiv"] == 'refresh') {
  951. $path = $attr["content"];
  952. $pathinfo = explode(";", $path);
  953. $content = "";
  954. foreach ($pathinfo AS $value)
  955. if (substr(strtolower($value), 0, 4) == "url=")
  956. return(original_url(substr($value, 4), ++$depth));
  957. }
  958. }
  959. return($url);
  960. }
  961. if (!function_exists('short_link')) {
  962. function short_link($url) {
  963. require_once('library/slinky.php');
  964. $slinky = new Slinky($url);
  965. $yourls_url = get_config('yourls','url1');
  966. if ($yourls_url) {
  967. $yourls_username = get_config('yourls','username1');
  968. $yourls_password = get_config('yourls', 'password1');
  969. $yourls_ssl = get_config('yourls', 'ssl1');
  970. $yourls = new Slinky_YourLS();
  971. $yourls->set('username', $yourls_username);
  972. $yourls->set('password', $yourls_password);
  973. $yourls->set('ssl', $yourls_ssl);
  974. $yourls->set('yourls-url', $yourls_url);
  975. $slinky->set_cascade( array($yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
  976. } else {
  977. // setup a cascade of shortening services
  978. // try to get a short link from these services
  979. // in the order ur1.ca, trim, id.gd, tinyurl
  980. $slinky->set_cascade(array(new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL()));
  981. }
  982. return $slinky->short();
  983. }};