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.

922 lines
26 KiB

8 years ago
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
4 years ago
4 years ago
  1. <?php
  2. /**
  3. * @file include/network.php
  4. */
  5. use \Friendica\Core\Config;
  6. require_once("include/xml.php");
  7. require_once('include/Probe.php');
  8. /**
  9. * @brief Curl wrapper
  10. *
  11. * If binary flag is true, return binary results.
  12. * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
  13. * to preserve cookies from one request to the next.
  14. *
  15. * @param string $url URL to fetch
  16. * @param boolean $binary default false
  17. * TRUE if asked to return binary results (file download)
  18. * @param integer $redirects The recursion counter for internal use - default 0
  19. * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
  20. * @param string $accept_content supply Accept: header with 'accept_content' as the value
  21. * @param string $cookiejar Path to cookie jar file
  22. *
  23. * @return string The fetched content
  24. */
  25. function fetch_url($url,$binary = false, &$redirects = 0, $timeout = 0, $accept_content=Null, $cookiejar = 0) {
  26. $ret = z_fetch_url(
  27. $url,
  28. $binary,
  29. $redirects,
  30. array('timeout'=>$timeout,
  31. 'accept_content'=>$accept_content,
  32. 'cookiejar'=>$cookiejar
  33. ));
  34. return($ret['body']);
  35. }
  36. /**
  37. * @brief fetches an URL.
  38. *
  39. * @param string $url URL to fetch
  40. * @param boolean $binary default false
  41. * TRUE if asked to return binary results (file download)
  42. * @param int $redirects The recursion counter for internal use - default 0
  43. * @param array $opts (optional parameters) assoziative array with:
  44. * 'accept_content' => supply Accept: header with 'accept_content' as the value
  45. * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
  46. * 'http_auth' => username:password
  47. * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
  48. * 'nobody' => only return the header
  49. * 'cookiejar' => path to cookie jar file
  50. *
  51. * @return array an assoziative array with:
  52. * int 'return_code' => HTTP return code or 0 if timeout or failure
  53. * boolean 'success' => boolean true (if HTTP 2xx result) or false
  54. * string 'redirect_url' => in case of redirect, content was finally retrieved from this URL
  55. * string 'header' => HTTP headers
  56. * string 'body' => fetched content
  57. */
  58. function z_fetch_url($url,$binary = false, &$redirects = 0, $opts=array()) {
  59. $ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => "");
  60. $stamp1 = microtime(true);
  61. $a = get_app();
  62. $ch = @curl_init($url);
  63. if(($redirects > 8) || (! $ch))
  64. return false;
  65. @curl_setopt($ch, CURLOPT_HEADER, true);
  66. if(x($opts,"cookiejar")) {
  67. curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
  68. curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
  69. }
  70. // These settings aren't needed. We're following the location already.
  71. // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  72. // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
  73. if (x($opts,'accept_content')){
  74. curl_setopt($ch,CURLOPT_HTTPHEADER, array (
  75. "Accept: " . $opts['accept_content']
  76. ));
  77. }
  78. @curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
  79. @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
  80. $range = intval(Config::get('system', 'curl_range_bytes', 0));
  81. if ($range > 0) {
  82. @curl_setopt($ch, CURLOPT_RANGE, '0-'.$range);
  83. }
  84. if(x($opts,'headers')){
  85. @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
  86. }
  87. if(x($opts,'nobody')){
  88. @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
  89. }
  90. if(x($opts,'timeout')){
  91. @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
  92. } else {
  93. $curl_time = intval(get_config('system','curl_timeout'));
  94. @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
  95. }
  96. // by default we will allow self-signed certs
  97. // but you can override this
  98. $check_cert = get_config('system','verifyssl');
  99. @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
  100. if ($check_cert) {
  101. @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  102. }
  103. $prx = get_config('system','proxy');
  104. if(strlen($prx)) {
  105. @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
  106. @curl_setopt($ch, CURLOPT_PROXY, $prx);
  107. $prxusr = @get_config('system','proxyuser');
  108. if(strlen($prxusr))
  109. @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
  110. }
  111. if($binary)
  112. @curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
  113. $a->set_curl_code(0);
  114. // don't let curl abort the entire application
  115. // if it throws any errors.
  116. $s = @curl_exec($ch);
  117. if (curl_errno($ch) !== CURLE_OK) {
  118. logger('fetch_url error fetching '.$url.': '.curl_error($ch), LOGGER_NORMAL);
  119. }
  120. $base = $s;
  121. $curl_info = @curl_getinfo($ch);
  122. $http_code = $curl_info['http_code'];
  123. logger('fetch_url '.$url.': '.$http_code." ".$s, LOGGER_DATA);
  124. $header = '';
  125. // Pull out multiple headers, e.g. proxy and continuation headers
  126. // allow for HTTP/2.x without fixing code
  127. while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
  128. $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
  129. $header .= $chunk;
  130. $base = substr($base,strlen($chunk));
  131. }
  132. $a->set_curl_code($http_code);
  133. $a->set_curl_content_type($curl_info['content_type']);
  134. $a->set_curl_headers($header);
  135. if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
  136. $new_location_info = @parse_url($curl_info["redirect_url"]);
  137. $old_location_info = @parse_url($curl_info["url"]);
  138. $newurl = $curl_info["redirect_url"];
  139. if (($new_location_info["path"] == "") AND ($new_location_info["host"] != ""))
  140. $newurl = $new_location_info["scheme"]."://".$new_location_info["host"].$old_location_info["path"];
  141. $matches = array();
  142. if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
  143. $newurl = trim(array_pop($matches));
  144. }
  145. if(strpos($newurl,'/') === 0)
  146. $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
  147. if (filter_var($newurl, FILTER_VALIDATE_URL)) {
  148. $redirects++;
  149. @curl_close($ch);
  150. return z_fetch_url($newurl,$binary, $redirects, $opts);
  151. }
  152. }
  153. $a->set_curl_code($http_code);
  154. $a->set_curl_content_type($curl_info['content_type']);
  155. $body = substr($s,strlen($header));
  156. $rc = intval($http_code);
  157. $ret['return_code'] = $rc;
  158. $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
  159. $ret['redirect_url'] = $url;
  160. if(! $ret['success']) {
  161. $ret['error'] = curl_error($ch);
  162. $ret['debug'] = $curl_info;
  163. logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
  164. logger('z_fetch_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
  165. }
  166. $ret['body'] = substr($s,strlen($header));
  167. $ret['header'] = $header;
  168. if(x($opts,'debug')) {
  169. $ret['debug'] = $curl_info;
  170. }
  171. @curl_close($ch);
  172. $a->save_timestamp($stamp1, "network");
  173. return($ret);
  174. }
  175. // post request to $url. $params is an array of post variables.
  176. /**
  177. * @brief Post request to $url
  178. *
  179. * @param string $url URL to post
  180. * @param mixed $params
  181. * @param string $headers HTTP headers
  182. * @param integer $redirects Recursion counter for internal use - default = 0
  183. * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
  184. *
  185. * @return string The content
  186. */
  187. function post_url($url,$params, $headers = null, &$redirects = 0, $timeout = 0) {
  188. $stamp1 = microtime(true);
  189. $a = get_app();
  190. $ch = curl_init($url);
  191. if(($redirects > 8) || (! $ch))
  192. return false;
  193. logger("post_url: start ".$url, LOGGER_DATA);
  194. curl_setopt($ch, CURLOPT_HEADER, true);
  195. curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
  196. curl_setopt($ch, CURLOPT_POST,1);
  197. curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
  198. curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
  199. if(intval($timeout)) {
  200. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  201. }
  202. else {
  203. $curl_time = intval(get_config('system','curl_timeout'));
  204. curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
  205. }
  206. if(defined('LIGHTTPD')) {
  207. if(!is_array($headers)) {
  208. $headers = array('Expect:');
  209. } else {
  210. if(!in_array('Expect:', $headers)) {
  211. array_push($headers, 'Expect:');
  212. }
  213. }
  214. }
  215. if($headers)
  216. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  217. $check_cert = get_config('system','verifyssl');
  218. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
  219. if ($check_cert) {
  220. @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
  221. }
  222. $prx = get_config('system','proxy');
  223. if(strlen($prx)) {
  224. curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
  225. curl_setopt($ch, CURLOPT_PROXY, $prx);
  226. $prxusr = get_config('system','proxyuser');
  227. if(strlen($prxusr))
  228. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
  229. }
  230. $a->set_curl_code(0);
  231. // don't let curl abort the entire application
  232. // if it throws any errors.
  233. $s = @curl_exec($ch);
  234. $base = $s;
  235. $curl_info = curl_getinfo($ch);
  236. $http_code = $curl_info['http_code'];
  237. logger("post_url: result ".$http_code." - ".$url, LOGGER_DATA);
  238. $header = '';
  239. // Pull out multiple headers, e.g. proxy and continuation headers
  240. // allow for HTTP/2.x without fixing code
  241. while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
  242. $chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
  243. $header .= $chunk;
  244. $base = substr($base,strlen($chunk));
  245. }
  246. if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
  247. $matches = array();
  248. preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
  249. $newurl = trim(array_pop($matches));
  250. if(strpos($newurl,'/') === 0)
  251. $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
  252. if (filter_var($newurl, FILTER_VALIDATE_URL)) {
  253. $redirects++;
  254. logger("post_url: redirect ".$url." to ".$newurl);
  255. return post_url($newurl,$params, $headers, $redirects, $timeout);
  256. //return fetch_url($newurl,false,$redirects,$timeout);
  257. }
  258. }
  259. $a->set_curl_code($http_code);
  260. $body = substr($s,strlen($header));
  261. $a->set_curl_headers($header);
  262. curl_close($ch);
  263. $a->save_timestamp($stamp1, "network");
  264. logger("post_url: end ".$url, LOGGER_DATA);
  265. return($body);
  266. }
  267. // Generic XML return
  268. // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
  269. // of $st and an optional text <message> of $message and terminates the current process.
  270. function xml_status($st, $message = '') {
  271. $xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');
  272. if($st)
  273. logger('xml_status returning non_zero: ' . $st . " message=" . $message);
  274. header( "Content-type: text/xml" );
  275. echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
  276. echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
  277. killme();
  278. }
  279. /**
  280. * @brief Send HTTP status header and exit.
  281. *
  282. * @param integer $val HTTP status result value
  283. * @param array $description optional message
  284. * 'title' => header title
  285. * 'description' => optional message
  286. */
  287. /**
  288. * @brief Send HTTP status header and exit.
  289. *
  290. * @param integer $val HTTP status result value
  291. * @param array $description optional message
  292. * 'title' => header title
  293. * 'description' => optional message
  294. */
  295. function http_status_exit($val, $description = array()) {
  296. $err = '';
  297. if($val >= 400) {
  298. $err = 'Error';
  299. if (!isset($description["title"]))
  300. $description["title"] = $err." ".$val;
  301. }
  302. if($val >= 200 && $val < 300)
  303. $err = 'OK';
  304. logger('http_status_exit ' . $val);
  305. header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
  306. if (isset($description["title"])) {
  307. $tpl = get_markup_template('http_status.tpl');
  308. echo replace_macros($tpl, array('$title' => $description["title"],
  309. '$description' => $description["description"]));
  310. }
  311. killme();
  312. }
  313. /**
  314. * @brief Check URL to se if ts's real
  315. *
  316. * Take a URL from the wild, prepend http:// if necessary
  317. * and check DNS to see if it's real (or check if is a valid IP address)
  318. *
  319. * @param string $url The URL to be validated
  320. * @return boolean True if it's a valid URL, fals if something wrong with it
  321. */
  322. function validate_url(&$url) {
  323. if(get_config('system','disable_url_validation'))
  324. return true;
  325. // no naked subdomains (allow localhost for tests)
  326. if(strpos($url,'.') === false && strpos($url,'/localhost/') === false)
  327. return false;
  328. if(substr($url,0,4) != 'http')
  329. $url = 'http://' . $url;
  330. /// @TODO Really supress function outcomes? Why not find them + debug them?
  331. $h = @parse_url($url);
  332. if((is_array($h)) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
  333. return true;
  334. }
  335. return false;
  336. }
  337. /**
  338. * @brief Checks that email is an actual resolvable internet address
  339. *
  340. * @param string $addr The email address
  341. * @return boolean True if it's a valid email address, false if it's not
  342. */
  343. function validate_email($addr) {
  344. if(get_config('system','disable_email_validation'))
  345. return true;
  346. if(! strpos($addr,'@'))
  347. return false;
  348. $h = substr($addr,strpos($addr,'@') + 1);
  349. if(($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
  350. return true;
  351. }
  352. return false;
  353. }
  354. /**
  355. * @brief Check if URL is allowed
  356. *
  357. * Check $url against our list of allowed sites,
  358. * wildcards allowed. If allowed_sites is unset return true;
  359. *
  360. * @param string $url URL which get tested
  361. * @return boolean True if url is allowed otherwise return false
  362. */
  363. function allowed_url($url) {
  364. $h = @parse_url($url);
  365. if(! $h) {
  366. return false;
  367. }
  368. $str_allowed = get_config('system','allowed_sites');
  369. if(! $str_allowed)
  370. return true;
  371. $found = false;
  372. $host = strtolower($h['host']);
  373. // always allow our own site
  374. if($host == strtolower($_SERVER['SERVER_NAME']))
  375. return true;
  376. $fnmatch = function_exists('fnmatch');
  377. $allowed = explode(',',$str_allowed);
  378. if(count($allowed)) {
  379. foreach($allowed as $a) {
  380. $pat = strtolower(trim($a));
  381. if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
  382. $found = true;
  383. break;
  384. }
  385. }
  386. }
  387. return $found;
  388. }
  389. /**
  390. * @brief Check if email address is allowed to register here.
  391. *
  392. * Compare against our list (wildcards allowed).
  393. *
  394. * @param type $email
  395. * @return boolean False if not allowed, true if allowed
  396. * or if allowed list is not configured
  397. */
  398. function allowed_email($email) {
  399. $domain = strtolower(substr($email,strpos($email,'@') + 1));
  400. if(! $domain)
  401. return false;
  402. $str_allowed = get_config('system','allowed_email');
  403. if(! $str_allowed)
  404. return true;
  405. $found = false;
  406. $fnmatch = function_exists('fnmatch');
  407. $allowed = explode(',',$str_allowed);
  408. if(count($allowed)) {
  409. foreach($allowed as $a) {
  410. $pat = strtolower(trim($a));
  411. if(($fnmatch && fnmatch($pat,$domain)) || ($pat == $domain)) {
  412. $found = true;
  413. break;
  414. }
  415. }
  416. }
  417. return $found;
  418. }
  419. function avatar_img($email) {
  420. $avatar['size'] = 175;
  421. $avatar['email'] = $email;
  422. $avatar['url'] = '';
  423. $avatar['success'] = false;
  424. call_hooks('avatar_lookup', $avatar);
  425. if (! $avatar['success']) {
  426. $avatar['url'] = App::get_baseurl() . '/images/person-175.jpg';
  427. }
  428. logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
  429. return $avatar['url'];
  430. }
  431. function parse_xml_string($s,$strict = true) {
  432. /// @todo Move this function to the xml class
  433. if($strict) {
  434. if(! strstr($s,'<?xml'))
  435. return false;
  436. $s2 = substr($s,strpos($s,'<?xml'));
  437. }
  438. else
  439. $s2 = $s;
  440. libxml_use_internal_errors(true);
  441. $x = @simplexml_load_string($s2);
  442. if (! $x) {
  443. logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
  444. foreach (libxml_get_errors() as $err) {
  445. logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
  446. }
  447. libxml_clear_errors();
  448. }
  449. return $x;
  450. }
  451. function scale_external_images($srctext, $include_link = true, $scale_replace = false) {
  452. // Suppress "view full size"
  453. if (intval(get_config('system','no_view_full_size'))) {
  454. $include_link = false;
  455. }
  456. $a = get_app();
  457. // Picture addresses can contain special characters
  458. $s = htmlspecialchars_decode($srctext);
  459. $matches = null;
  460. $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism',$s,$matches,PREG_SET_ORDER);
  461. if ($c) {
  462. require_once('include/Photo.php');
  463. foreach ($matches as $mtch) {
  464. logger('scale_external_image: ' . $mtch[1]);
  465. $hostname = str_replace('www.','',substr(App::get_baseurl(),strpos(App::get_baseurl(),'://')+3));
  466. if (stristr($mtch[1],$hostname)) {
  467. continue;
  468. }
  469. // $scale_replace, if passed, is an array of two elements. The
  470. // first is the name of the full-size image. The second is the
  471. // name of a remote, scaled-down version of the full size image.
  472. // This allows Friendica to display the smaller remote image if
  473. // one exists, while still linking to the full-size image
  474. if ($scale_replace) {
  475. $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
  476. } else {
  477. $scaled = $mtch[1];
  478. }
  479. $i = fetch_url($scaled);
  480. if (! $i) {
  481. return $srctext;
  482. }
  483. // guess mimetype from headers or filename
  484. $type = guess_image_type($mtch[1],true);
  485. if ($i) {
  486. $ph = new Photo($i, $type);
  487. if ($ph->is_valid()) {
  488. $orig_width = $ph->getWidth();
  489. $orig_height = $ph->getHeight();
  490. if ($orig_width > 640 || $orig_height > 640) {
  491. $ph->scaleImage(640);
  492. $new_width = $ph->getWidth();
  493. $new_height = $ph->getHeight();
  494. logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
  495. $s = str_replace($mtch[0],'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
  496. . "\n" . (($include_link)
  497. ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
  498. : ''),$s);
  499. logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
  500. }
  501. }
  502. }
  503. }
  504. }
  505. // replace the special char encoding
  506. $s = htmlspecialchars($s,ENT_NOQUOTES,'UTF-8');
  507. return $s;
  508. }
  509. function fix_contact_ssl_policy(&$contact,$new_policy) {
  510. $ssl_changed = false;
  511. if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'],'https:')) {
  512. $ssl_changed = true;
  513. $contact['url'] = str_replace('https:','http:',$contact['url']);
  514. $contact['request'] = str_replace('https:','http:',$contact['request']);
  515. $contact['notify'] = str_replace('https:','http:',$contact['notify']);
  516. $contact['poll'] = str_replace('https:','http:',$contact['poll']);
  517. $contact['confirm'] = str_replace('https:','http:',$contact['confirm']);
  518. $contact['poco'] = str_replace('https:','http:',$contact['poco']);
  519. }
  520. if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'],'http:')) {
  521. $ssl_changed = true;
  522. $contact['url'] = str_replace('http:','https:',$contact['url']);
  523. $contact['request'] = str_replace('http:','https:',$contact['request']);
  524. $contact['notify'] = str_replace('http:','https:',$contact['notify']);
  525. $contact['poll'] = str_replace('http:','https:',$contact['poll']);
  526. $contact['confirm'] = str_replace('http:','https:',$contact['confirm']);
  527. $contact['poco'] = str_replace('http:','https:',$contact['poco']);
  528. }
  529. if ($ssl_changed) {
  530. q("UPDATE `contact` SET
  531. `url` = '%s',
  532. `request` = '%s',
  533. `notify` = '%s',
  534. `poll` = '%s',
  535. `confirm` = '%s',
  536. `poco` = '%s'
  537. WHERE `id` = %d LIMIT 1",
  538. dbesc($contact['url']),
  539. dbesc($contact['request']),
  540. dbesc($contact['notify']),
  541. dbesc($contact['poll']),
  542. dbesc($contact['confirm']),
  543. dbesc($contact['poco']),
  544. intval($contact['id'])
  545. );
  546. }
  547. }
  548. /**
  549. * @brief Remove Google Analytics and other tracking platforms params from URL
  550. *
  551. * @param string $url Any user-submitted URL that may contain tracking params
  552. * @return string The same URL stripped of tracking parameters
  553. */
  554. function strip_tracking_query_params($url)
  555. {
  556. $urldata = parse_url($url);
  557. if (is_string($urldata["query"])) {
  558. $query = $urldata["query"];
  559. parse_str($query, $querydata);
  560. if (is_array($querydata)) {
  561. foreach ($querydata AS $param => $value) {
  562. if (in_array($param, array("utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
  563. "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
  564. "fb_action_ids", "fb_action_types", "fb_ref",
  565. "awesm", "wtrid",
  566. "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"))) {
  567. $pair = $param . "=" . urlencode($value);
  568. $url = str_replace($pair, "", $url);
  569. // Second try: if the url isn't encoded completely
  570. $pair = $param . "=" . str_replace(" ", "+", $value);
  571. $url = str_replace($pair, "", $url);
  572. // Third try: Maybey the url isn't encoded at all
  573. $pair = $param . "=" . $value;
  574. $url = str_replace($pair, "", $url);
  575. $url = str_replace(array("?&", "&&"), array("?", ""), $url);
  576. }
  577. }
  578. }
  579. if (substr($url, -1, 1) == "?") {
  580. $url = substr($url, 0, -1);
  581. }
  582. }
  583. return $url;
  584. }
  585. /**
  586. * @brief Returns the original URL of the provided URL
  587. *
  588. * This function strips tracking query params and follows redirections, either
  589. * through HTTP code or meta refresh tags. Stops after 10 redirections.
  590. *
  591. * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
  592. *
  593. * @see ParseUrl::getSiteinfo
  594. *
  595. * @param string $url A user-submitted URL
  596. * @param int $depth The current redirection recursion level (internal)
  597. * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
  598. * @return string A canonical URL
  599. */
  600. function original_url($url, $depth = 1, $fetchbody = false) {
  601. $a = get_app();
  602. $url = strip_tracking_query_params($url);
  603. if ($depth > 10)
  604. return($url);
  605. $url = trim($url, "'");
  606. $stamp1 = microtime(true);
  607. $siteinfo = array();
  608. $ch = curl_init();
  609. curl_setopt($ch, CURLOPT_URL, $url);
  610. curl_setopt($ch, CURLOPT_HEADER, 1);
  611. curl_setopt($ch, CURLOPT_NOBODY, 1);
  612. curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  613. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  614. curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
  615. $header = curl_exec($ch);
  616. $curl_info = @curl_getinfo($ch);
  617. $http_code = $curl_info['http_code'];
  618. curl_close($ch);
  619. $a->save_timestamp($stamp1, "network");
  620. if ($http_code == 0)
  621. return($url);
  622. if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302"))
  623. AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
  624. if ($curl_info['redirect_url'] != "")
  625. return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
  626. else
  627. return(original_url($curl_info['location'], ++$depth, $fetchbody));
  628. }
  629. // Check for redirects in the meta elements of the body if there are no redirects in the header.
  630. if (!$fetchbody)
  631. return(original_url($url, ++$depth, true));
  632. // if the file is too large then exit
  633. if ($curl_info["download_content_length"] > 1000000)
  634. return($url);
  635. // if it isn't a HTML file then exit
  636. if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
  637. return($url);
  638. $stamp1 = microtime(true);
  639. $ch = curl_init();
  640. curl_setopt($ch, CURLOPT_URL, $url);
  641. curl_setopt($ch, CURLOPT_HEADER, 0);
  642. curl_setopt($ch, CURLOPT_NOBODY, 0);
  643. curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  644. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  645. curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
  646. $body = curl_exec($ch);
  647. curl_close($ch);
  648. $a->save_timestamp($stamp1, "network");
  649. if (trim($body) == "")
  650. return($url);
  651. // Check for redirect in meta elements
  652. $doc = new DOMDocument();
  653. @$doc->loadHTML($body);
  654. $xpath = new DomXPath($doc);
  655. $list = $xpath->query("//meta[@content]");
  656. foreach ($list as $node) {
  657. $attr = array();
  658. if ($node->attributes->length)
  659. foreach ($node->attributes as $attribute)
  660. $attr[$attribute->name] = $attribute->value;
  661. if (@$attr["http-equiv"] == 'refresh') {
  662. $path = $attr["content"];
  663. $pathinfo = explode(";", $path);
  664. $content = "";
  665. foreach ($pathinfo AS $value)
  666. if (substr(strtolower($value), 0, 4) == "url=")
  667. return(original_url(substr($value, 4), ++$depth));
  668. }
  669. }
  670. return($url);
  671. }
  672. function short_link($url) {
  673. require_once('library/slinky.php');
  674. $slinky = new Slinky($url);
  675. $yourls_url = get_config('yourls','url1');
  676. if ($yourls_url) {
  677. $yourls_username = get_config('yourls','username1');
  678. $yourls_password = get_config('yourls', 'password1');
  679. $yourls_ssl = get_config('yourls', 'ssl1');
  680. $yourls = new Slinky_YourLS();
  681. $yourls->set('username', $yourls_username);
  682. $yourls->set('password', $yourls_password);
  683. $yourls->set('ssl', $yourls_ssl);
  684. $yourls->set('yourls-url', $yourls_url);
  685. $slinky->set_cascade(array($yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()));
  686. } else {
  687. // setup a cascade of shortening services
  688. // try to get a short link from these services
  689. // in the order ur1.ca, tinyurl
  690. $slinky->set_cascade(array(new Slinky_Ur1ca(), new Slinky_TinyURL()));
  691. }
  692. return $slinky->short();
  693. }
  694. /**
  695. * @brief Encodes content to json
  696. *
  697. * This function encodes an array to json format
  698. * and adds an application/json HTTP header to the output.
  699. * After finishing the process is getting killed.
  700. *
  701. * @param array $x The input content
  702. */
  703. function json_return_and_die($x) {
  704. header("content-type: application/json");
  705. echo json_encode($x);
  706. killme();
  707. }
  708. /**
  709. * @brief Find the matching part between two url
  710. *
  711. * @param string $url1
  712. * @param string $url2
  713. * @return string The matching part
  714. */
  715. function matching_url($url1, $url2) {
  716. if (($url1 == "") OR ($url2 == ""))
  717. return "";
  718. $url1 = normalise_link($url1);
  719. $url2 = normalise_link($url2);
  720. $parts1 = parse_url($url1);
  721. $parts2 = parse_url($url2);
  722. if (!isset($parts1["host"]) OR !isset($parts2["host"]))
  723. return "";
  724. if ($parts1["scheme"] != $parts2["scheme"])
  725. return "";
  726. if ($parts1["host"] != $parts2["host"])
  727. return "";
  728. if ($parts1["port"] != $parts2["port"])
  729. return "";
  730. $match = $parts1["scheme"]."://".$parts1["host"];
  731. if ($parts1["port"])
  732. $match .= ":".$parts1["port"];
  733. $pathparts1 = explode("/", $parts1["path"]);
  734. $pathparts2 = explode("/", $parts2["path"]);
  735. $i = 0;
  736. $path = "";
  737. do {
  738. $path1 = $pathparts1[$i];
  739. $path2 = $pathparts2[$i];
  740. if ($path1 == $path2)
  741. $path .= $path1."/";
  742. } while (($path1 == $path2) AND ($i++ <= count($pathparts1)));
  743. $match .= $path;
  744. return normalise_link($match);
  745. }