4 * @file include/network.php
8 use Friendica\Core\System;
9 use Friendica\Core\Config;
10 use Friendica\Network\Probe;
11 use Friendica\Util\XML;
16 * If binary flag is true, return binary results.
17 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
18 * to preserve cookies from one request to the next.
20 * @param string $url URL to fetch
21 * @param boolean $binary default false
22 * TRUE if asked to return binary results (file download)
23 * @param integer $redirects The recursion counter for internal use - default 0
24 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
25 * @param string $accept_content supply Accept: header with 'accept_content' as the value
26 * @param string $cookiejar Path to cookie jar file
28 * @return string The fetched content
30 function fetch_url($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = 0)
36 array('timeout'=>$timeout,
37 'accept_content'=>$accept_content,
38 'cookiejar'=>$cookiejar
46 * @brief fetches an URL.
48 * @param string $url URL to fetch
49 * @param boolean $binary default false
50 * TRUE if asked to return binary results (file download)
51 * @param int $redirects The recursion counter for internal use - default 0
52 * @param array $opts (optional parameters) assoziative array with:
53 * 'accept_content' => supply Accept: header with 'accept_content' as the value
54 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
55 * 'http_auth' => username:password
56 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
57 * 'nobody' => only return the header
58 * 'cookiejar' => path to cookie jar file
60 * @return array an assoziative array with:
61 * int 'return_code' => HTTP return code or 0 if timeout or failure
62 * boolean 'success' => boolean true (if HTTP 2xx result) or false
63 * string 'redirect_url' => in case of redirect, content was finally retrieved from this URL
64 * string 'header' => HTTP headers
65 * string 'body' => fetched content
67 function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = array())
69 $ret = array('return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => '');
71 $stamp1 = microtime(true);
75 if (blocked_url($url)) {
76 logger('z_fetch_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
80 $ch = @curl_init($url);
82 if (($redirects > 8) || (!$ch)) {
86 @curl_setopt($ch, CURLOPT_HEADER, true);
88 if (x($opts, "cookiejar")) {
89 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
90 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
93 // These settings aren't needed. We're following the location already.
94 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
95 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
97 if (x($opts, 'accept_content')) {
101 array('Accept: ' . $opts['accept_content'])
105 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
106 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
108 $range = intval(Config::get('system', 'curl_range_bytes', 0));
111 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
114 // Without this setting it seems as if some webservers send compressed content
115 // This seems to confuse curl so that it shows this uncompressed.
116 /// @todo We could possibly set this value to "gzip" or something similar
117 curl_setopt($ch, CURLOPT_ENCODING, '');
119 if (x($opts, 'headers')) {
120 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
123 if (x($opts, 'nobody')) {
124 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
127 if (x($opts, 'timeout')) {
128 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
130 $curl_time = intval(Config::get('system', 'curl_timeout'));
131 @curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
134 // by default we will allow self-signed certs
135 // but you can override this
137 $check_cert = Config::get('system', 'verifyssl');
138 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
141 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
144 $proxy = Config::get('system', 'proxy');
146 if (strlen($proxy)) {
147 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
148 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
149 $proxyuser = @Config::get('system', 'proxyuser');
151 if (strlen($proxyuser)) {
152 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
156 if (Config::get('system', 'ipv4_resolve', false)) {
157 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
161 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
164 $a->set_curl_code(0);
166 // don't let curl abort the entire application
167 // if it throws any errors.
169 $s = @curl_exec($ch);
170 $curl_info = @curl_getinfo($ch);
172 // Special treatment for HTTP Code 416
173 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
174 if (($curl_info['http_code'] == 416) && ($range > 0)) {
175 @curl_setopt($ch, CURLOPT_RANGE, '');
176 $s = @curl_exec($ch);
177 $curl_info = @curl_getinfo($ch);
180 if (curl_errno($ch) !== CURLE_OK) {
181 logger('fetch_url error fetching ' . $url . ': ' . curl_error($ch), LOGGER_NORMAL);
184 $ret['errno'] = curl_errno($ch);
187 $ret['info'] = $curl_info;
189 $http_code = $curl_info['http_code'];
191 logger('fetch_url ' . $url . ': ' . $http_code . " " . $s, LOGGER_DATA);
194 // Pull out multiple headers, e.g. proxy and continuation headers
195 // allow for HTTP/2.x without fixing code
197 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
198 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
200 $base = substr($base, strlen($chunk));
203 $a->set_curl_code($http_code);
204 $a->set_curl_content_type($curl_info['content_type']);
205 $a->set_curl_headers($header);
207 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
208 $new_location_info = @parse_url($curl_info['redirect_url']);
209 $old_location_info = @parse_url($curl_info['url']);
211 $newurl = $curl_info['redirect_url'];
213 if (($new_location_info['path'] == '') && ( $new_location_info['host'] != '')) {
214 $newurl = $new_location_info['scheme'] . '://' . $new_location_info['host'] . $old_location_info['path'];
219 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
220 $newurl = trim(array_pop($matches));
222 if (strpos($newurl, '/') === 0) {
223 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
226 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
229 return z_fetch_url($newurl, $binary, $redirects, $opts);
233 $a->set_curl_code($http_code);
234 $a->set_curl_content_type($curl_info['content_type']);
236 $body = substr($s, strlen($header));
238 $rc = intval($http_code);
239 $ret['return_code'] = $rc;
240 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
241 $ret['redirect_url'] = $url;
243 if (!$ret['success']) {
244 $ret['error'] = curl_error($ch);
245 $ret['debug'] = $curl_info;
246 logger('z_fetch_url: error: '.$url.': '.$ret['return_code'].' - '.$ret['error'], LOGGER_DEBUG);
247 logger('z_fetch_url: debug: '.print_r($curl_info, true), LOGGER_DATA);
250 $ret['body'] = substr($s, strlen($header));
251 $ret['header'] = $header;
253 if (x($opts, 'debug')) {
254 $ret['debug'] = $curl_info;
259 $a->save_timestamp($stamp1, 'network');
265 * @brief Send POST request to $url
267 * @param string $url URL to post
268 * @param mixed $params array of POST variables
269 * @param string $headers HTTP headers
270 * @param integer $redirects Recursion counter for internal use - default = 0
271 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
273 * @return string The content
275 function post_url($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
277 $stamp1 = microtime(true);
279 if (blocked_url($url)) {
280 logger('post_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
285 $ch = curl_init($url);
287 if (($redirects > 8) || (!$ch)) {
291 logger('post_url: start ' . $url, LOGGER_DATA);
293 curl_setopt($ch, CURLOPT_HEADER, true);
294 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
295 curl_setopt($ch, CURLOPT_POST, 1);
296 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
297 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
299 if (Config::get('system', 'ipv4_resolve', false)) {
300 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
303 if (intval($timeout)) {
304 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
306 $curl_time = intval(Config::get('system', 'curl_timeout'));
307 curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
310 if (defined('LIGHTTPD')) {
311 if (!is_array($headers)) {
312 $headers = array('Expect:');
314 if (!in_array('Expect:', $headers)) {
315 array_push($headers, 'Expect:');
321 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
324 $check_cert = Config::get('system', 'verifyssl');
325 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
328 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
331 $proxy = Config::get('system', 'proxy');
333 if (strlen($proxy)) {
334 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
335 curl_setopt($ch, CURLOPT_PROXY, $proxy);
336 $proxyuser = Config::get('system', 'proxyuser');
337 if (strlen($proxyuser)) {
338 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
342 $a->set_curl_code(0);
344 // don't let curl abort the entire application
345 // if it throws any errors.
347 $s = @curl_exec($ch);
350 $curl_info = curl_getinfo($ch);
351 $http_code = $curl_info['http_code'];
353 logger('post_url: result ' . $http_code . ' - ' . $url, LOGGER_DATA);
357 // Pull out multiple headers, e.g. proxy and continuation headers
358 // allow for HTTP/2.x without fixing code
360 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
361 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
363 $base = substr($base, strlen($chunk));
366 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
368 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
369 $newurl = trim(array_pop($matches));
371 if (strpos($newurl, '/') === 0) {
372 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
375 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
377 logger('post_url: redirect ' . $url . ' to ' . $newurl);
378 return post_url($newurl, $params, $headers, $redirects, $timeout);
382 $a->set_curl_code($http_code);
384 $body = substr($s, strlen($header));
386 $a->set_curl_headers($header);
390 $a->save_timestamp($stamp1, 'network');
392 logger('post_url: end ' . $url, LOGGER_DATA);
397 // Generic XML return
398 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
399 // of $st and an optional text <message> of $message and terminates the current process.
401 function xml_status($st, $message = '')
403 $result = array('status' => $st);
405 if ($message != '') {
406 $result['message'] = $message;
410 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
413 header("Content-type: text/xml");
415 $xmldata = array("result" => $result);
417 echo XML::from_array($xmldata, $xml);
423 * @brief Send HTTP status header and exit.
425 * @param integer $val HTTP status result value
426 * @param array $description optional message
427 * 'title' => header title
428 * 'description' => optional message
432 * @brief Send HTTP status header and exit.
434 * @param integer $val HTTP status result value
435 * @param array $description optional message
436 * 'title' => header title
437 * 'description' => optional message
439 function http_status_exit($val, $description = array())
444 if (!isset($description["title"])) {
445 $description["title"] = $err." ".$val;
448 if ($val >= 200 && $val < 300)
451 logger('http_status_exit ' . $val);
452 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
454 if (isset($description["title"])) {
455 $tpl = get_markup_template('http_status.tpl');
459 '$title' => $description["title"],
460 '$description' => $description["description"])
468 * @brief Check URL to se if ts's real
470 * Take a URL from the wild, prepend http:// if necessary
471 * and check DNS to see if it's real (or check if is a valid IP address)
473 * @param string $url The URL to be validated
474 * @return boolean True if it's a valid URL, fals if something wrong with it
476 function validate_url(&$url)
478 if (Config::get('system', 'disable_url_validation')) {
482 // no naked subdomains (allow localhost for tests)
483 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false)
486 if (substr($url, 0, 4) != 'http')
487 $url = 'http://' . $url;
489 /// @TODO Really supress function outcomes? Why not find them + debug them?
490 $h = @parse_url($url);
492 if ((is_array($h)) && (dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
500 * @brief Checks that email is an actual resolvable internet address
502 * @param string $addr The email address
503 * @return boolean True if it's a valid email address, false if it's not
505 function validate_email($addr)
507 if (Config::get('system', 'disable_email_validation')) {
511 if (! strpos($addr, '@')) {
515 $h = substr($addr, strpos($addr, '@') + 1);
517 if (($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
524 * @brief Check if URL is allowed
526 * Check $url against our list of allowed sites,
527 * wildcards allowed. If allowed_sites is unset return true;
529 * @param string $url URL which get tested
530 * @return boolean True if url is allowed otherwise return false
532 function allowed_url($url)
534 $h = @parse_url($url);
540 $str_allowed = Config::get('system', 'allowed_sites');
541 if (! $str_allowed) {
547 $host = strtolower($h['host']);
549 // always allow our own site
550 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
554 $fnmatch = function_exists('fnmatch');
555 $allowed = explode(',', $str_allowed);
557 if (count($allowed)) {
558 foreach ($allowed as $a) {
559 $pat = strtolower(trim($a));
560 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
570 * Checks if the provided url domain is on the domain blocklist.
571 * Returns true if it is or malformed URL, false if not.
573 * @param string $url The url to check the domain from
577 function blocked_url($url)
579 $h = @parse_url($url);
585 $domain_blocklist = Config::get('system', 'blocklist', array());
586 if (! $domain_blocklist) {
590 $host = strtolower($h['host']);
592 foreach ($domain_blocklist as $domain_block) {
593 if (strtolower($domain_block['domain']) == $host) {
602 * @brief Check if email address is allowed to register here.
604 * Compare against our list (wildcards allowed).
606 * @param string $email email address
607 * @return boolean False if not allowed, true if allowed
608 * or if allowed list is not configured
610 function allowed_email($email)
612 $domain = strtolower(substr($email, strpos($email, '@') + 1));
617 $str_allowed = Config::get('system', 'allowed_email');
618 if (! $str_allowed) {
624 $fnmatch = function_exists('fnmatch');
625 $allowed = explode(',', $str_allowed);
627 if (count($allowed)) {
628 foreach ($allowed as $a) {
629 $pat = strtolower(trim($a));
630 if (($fnmatch && fnmatch($pat, $domain)) || ($pat == $domain)) {
639 function avatar_img($email)
641 $avatar['size'] = 175;
642 $avatar['email'] = $email;
644 $avatar['success'] = false;
646 call_hooks('avatar_lookup', $avatar);
648 if (! $avatar['success']) {
649 $avatar['url'] = System::baseUrl() . '/images/person-175.jpg';
652 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
653 return $avatar['url'];
657 function parse_xml_string($s, $strict = true)
659 // the "strict" parameter is deactivated
661 /// @todo Move this function to the xml class
662 libxml_use_internal_errors(true);
664 $x = @simplexml_load_string($s);
666 logger('libxml: parse: error: ' . $s, LOGGER_DATA);
667 foreach (libxml_get_errors() as $err) {
668 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
670 libxml_clear_errors();
675 function scale_external_images($srctext, $include_link = true, $scale_replace = false)
677 // Suppress "view full size"
678 if (intval(Config::get('system', 'no_view_full_size'))) {
679 $include_link = false;
684 // Picture addresses can contain special characters
685 $s = htmlspecialchars_decode($srctext);
688 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism', $s, $matches, PREG_SET_ORDER);
690 require_once 'include/Photo.php';
691 foreach ($matches as $mtch) {
692 logger('scale_external_image: ' . $mtch[1]);
694 $hostname = str_replace('www.', '', substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3));
695 if (stristr($mtch[1], $hostname)) {
699 // $scale_replace, if passed, is an array of two elements. The
700 // first is the name of the full-size image. The second is the
701 // name of a remote, scaled-down version of the full size image.
702 // This allows Friendica to display the smaller remote image if
703 // one exists, while still linking to the full-size image
704 if ($scale_replace) {
705 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
709 $i = fetch_url($scaled);
714 // guess mimetype from headers or filename
715 $type = guess_image_type($mtch[1], true);
718 $ph = new Photo($i, $type);
719 if ($ph->is_valid()) {
720 $orig_width = $ph->getWidth();
721 $orig_height = $ph->getHeight();
723 if ($orig_width > 640 || $orig_height > 640) {
724 $ph->scaleImage(640);
725 $new_width = $ph->getWidth();
726 $new_height = $ph->getHeight();
727 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
730 '[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
731 . "\n" . (($include_link)
732 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
736 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
743 // replace the special char encoding
744 $s = htmlspecialchars($s, ENT_NOQUOTES, 'UTF-8');
749 function fix_contact_ssl_policy(&$contact, $new_policy)
751 $ssl_changed = false;
752 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
754 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
755 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
756 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
757 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
758 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
759 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
762 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
764 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
765 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
766 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
767 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
768 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
769 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
773 $fields = array('url' => $contact['url'], 'request' => $contact['request'],
774 'notify' => $contact['notify'], 'poll' => $contact['poll'],
775 'confirm' => $contact['confirm'], 'poco' => $contact['poco']);
776 dba::update('contact', $fields, array('id' => $contact['id']));
781 * @brief Remove Google Analytics and other tracking platforms params from URL
783 * @param string $url Any user-submitted URL that may contain tracking params
784 * @return string The same URL stripped of tracking parameters
786 function strip_tracking_query_params($url)
788 $urldata = parse_url($url);
789 if (is_string($urldata["query"])) {
790 $query = $urldata["query"];
791 parse_str($query, $querydata);
793 if (is_array($querydata)) {
794 foreach ($querydata as $param => $value) {
798 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
799 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
800 "fb_action_ids", "fb_action_types", "fb_ref",
802 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term")
805 $pair = $param . "=" . urlencode($value);
806 $url = str_replace($pair, "", $url);
808 // Second try: if the url isn't encoded completely
809 $pair = $param . "=" . str_replace(" ", "+", $value);
810 $url = str_replace($pair, "", $url);
812 // Third try: Maybey the url isn't encoded at all
813 $pair = $param . "=" . $value;
814 $url = str_replace($pair, "", $url);
816 $url = str_replace(array("?&", "&&"), array("?", ""), $url);
821 if (substr($url, -1, 1) == "?") {
822 $url = substr($url, 0, -1);
830 * @brief Returns the original URL of the provided URL
832 * This function strips tracking query params and follows redirections, either
833 * through HTTP code or meta refresh tags. Stops after 10 redirections.
835 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
837 * @see ParseUrl::getSiteinfo
839 * @param string $url A user-submitted URL
840 * @param int $depth The current redirection recursion level (internal)
841 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
842 * @return string A canonical URL
844 function original_url($url, $depth = 1, $fetchbody = false)
848 $url = strip_tracking_query_params($url);
854 $url = trim($url, "'");
856 $stamp1 = microtime(true);
860 curl_setopt($ch, CURLOPT_URL, $url);
861 curl_setopt($ch, CURLOPT_HEADER, 1);
862 curl_setopt($ch, CURLOPT_NOBODY, 1);
863 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
864 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
865 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
867 $header = curl_exec($ch);
868 $curl_info = @curl_getinfo($ch);
869 $http_code = $curl_info['http_code'];
872 $a->save_timestamp($stamp1, "network");
877 if ((($curl_info['http_code'] == "301") || ($curl_info['http_code'] == "302"))
878 && (($curl_info['redirect_url'] != "") || ($curl_info['location'] != ""))
880 if ($curl_info['redirect_url'] != "") {
881 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
883 return(original_url($curl_info['location'], ++$depth, $fetchbody));
887 // Check for redirects in the meta elements of the body if there are no redirects in the header.
889 return(original_url($url, ++$depth, true));
892 // if the file is too large then exit
893 if ($curl_info["download_content_length"] > 1000000) {
897 // if it isn't a HTML file then exit
898 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
902 $stamp1 = microtime(true);
905 curl_setopt($ch, CURLOPT_URL, $url);
906 curl_setopt($ch, CURLOPT_HEADER, 0);
907 curl_setopt($ch, CURLOPT_NOBODY, 0);
908 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
909 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
910 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
912 $body = curl_exec($ch);
915 $a->save_timestamp($stamp1, "network");
917 if (trim($body) == "") {
921 // Check for redirect in meta elements
922 $doc = new DOMDocument();
923 @$doc->loadHTML($body);
925 $xpath = new DomXPath($doc);
927 $list = $xpath->query("//meta[@content]");
928 foreach ($list as $node) {
930 if ($node->attributes->length) {
931 foreach ($node->attributes as $attribute) {
932 $attr[$attribute->name] = $attribute->value;
936 if (@$attr["http-equiv"] == 'refresh') {
937 $path = $attr["content"];
938 $pathinfo = explode(";", $path);
940 foreach ($pathinfo as $value) {
941 if (substr(strtolower($value), 0, 4) == "url=") {
942 return(original_url(substr($value, 4), ++$depth));
951 function short_link($url)
953 require_once 'library/slinky.php';
954 $slinky = new Slinky($url);
955 $yourls_url = Config::get('yourls', 'url1');
957 $yourls_username = Config::get('yourls', 'username1');
958 $yourls_password = Config::get('yourls', 'password1');
959 $yourls_ssl = Config::get('yourls', 'ssl1');
960 $yourls = new Slinky_YourLS();
961 $yourls->set('username', $yourls_username);
962 $yourls->set('password', $yourls_password);
963 $yourls->set('ssl', $yourls_ssl);
964 $yourls->set('yourls-url', $yourls_url);
965 $slinky->set_cascade(array($yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()));
967 // setup a cascade of shortening services
968 // try to get a short link from these services
969 // in the order ur1.ca, tinyurl
970 $slinky->set_cascade(array(new Slinky_Ur1ca(), new Slinky_TinyURL()));
972 return $slinky->short();
976 * @brief Encodes content to json
978 * This function encodes an array to json format
979 * and adds an application/json HTTP header to the output.
980 * After finishing the process is getting killed.
982 * @param array $x The input content
984 function json_return_and_die($x)
986 header("content-type: application/json");
987 echo json_encode($x);
992 * @brief Find the matching part between two url
994 * @param string $url1
995 * @param string $url2
996 * @return string The matching part
998 function matching_url($url1, $url2)
1000 if (($url1 == "") || ($url2 == "")) {
1004 $url1 = normalise_link($url1);
1005 $url2 = normalise_link($url2);
1007 $parts1 = parse_url($url1);
1008 $parts2 = parse_url($url2);
1010 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
1014 if ($parts1["scheme"] != $parts2["scheme"]) {
1018 if ($parts1["host"] != $parts2["host"]) {
1022 if ($parts1["port"] != $parts2["port"]) {
1026 $match = $parts1["scheme"]."://".$parts1["host"];
1028 if ($parts1["port"]) {
1029 $match .= ":".$parts1["port"];
1032 $pathparts1 = explode("/", $parts1["path"]);
1033 $pathparts2 = explode("/", $parts2["path"]);
1038 $path1 = $pathparts1[$i];
1039 $path2 = $pathparts2[$i];
1041 if ($path1 == $path2) {
1042 $path .= $path1."/";
1044 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
1048 return normalise_link($match);
1052 * @brief Glue url parts together
1054 * @param array $parsed URL parts
1056 * @return string The glued URL
1058 function unParseUrl($parsed)
1060 $get = function ($key) use ($parsed) {
1061 return isset($parsed[$key]) ? $parsed[$key] : null;
1064 $pass = $get('pass');
1065 $user = $get('user');
1066 $userinfo = $pass !== null ? "$user:$pass" : $user;
1067 $port = $get('port');
1068 $scheme = $get('scheme');
1069 $query = $get('query');
1070 $fragment = $get('fragment');
1071 $authority = ($userinfo !== null ? $userinfo."@" : '') .
1073 ($port ? ":$port" : '');
1075 return (strlen($scheme) ? $scheme.":" : '') .
1076 (strlen($authority) ? "//".$authority : '') .
1078 (strlen($query) ? "?".$query : '') .
1079 (strlen($fragment) ? "#".$fragment : '');