3 * @file include/network.php
6 use Friendica\Core\Addon;
7 use Friendica\Core\L10n;
8 use Friendica\Core\System;
9 use Friendica\Core\Config;
10 use Friendica\Network\Probe;
11 use Friendica\Object\Image;
12 use Friendica\Util\XML;
17 * If binary flag is true, return binary results.
18 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
19 * to preserve cookies from one request to the next.
21 * @param string $url URL to fetch
22 * @param boolean $binary default false
23 * TRUE if asked to return binary results (file download)
24 * @param integer $redirects The recursion counter for internal use - default 0
25 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
26 * @param string $accept_content supply Accept: header with 'accept_content' as the value
27 * @param string $cookiejar Path to cookie jar file
29 * @return string The fetched content
31 function fetch_url($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = 0)
38 'accept_content'=>$accept_content,
39 'cookiejar'=>$cookiejar
47 * @brief fetches an URL.
49 * @param string $url URL to fetch
50 * @param boolean $binary default false
51 * TRUE if asked to return binary results (file download)
52 * @param int $redirects The recursion counter for internal use - default 0
53 * @param array $opts (optional parameters) assoziative array with:
54 * 'accept_content' => supply Accept: header with 'accept_content' as the value
55 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
56 * 'http_auth' => username:password
57 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
58 * 'nobody' => only return the header
59 * 'cookiejar' => path to cookie jar file
61 * @return array an assoziative array with:
62 * int 'return_code' => HTTP return code or 0 if timeout or failure
63 * boolean 'success' => boolean true (if HTTP 2xx result) or false
64 * string 'redirect_url' => in case of redirect, content was finally retrieved from this URL
65 * string 'header' => HTTP headers
66 * string 'body' => fetched content
68 function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = [])
70 $ret = ['return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => ''];
72 $stamp1 = microtime(true);
76 if (blocked_url($url)) {
77 logger('z_fetch_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
81 $ch = @curl_init($url);
83 if (($redirects > 8) || (!$ch)) {
87 @curl_setopt($ch, CURLOPT_HEADER, true);
89 if (x($opts, "cookiejar")) {
90 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
91 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
94 // These settings aren't needed. We're following the location already.
95 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
96 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
98 if (x($opts, 'accept_content')) {
102 ['Accept: ' . $opts['accept_content']]
106 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
107 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
109 $range = intval(Config::get('system', 'curl_range_bytes', 0));
112 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
115 // Without this setting it seems as if some webservers send compressed content
116 // This seems to confuse curl so that it shows this uncompressed.
117 /// @todo We could possibly set this value to "gzip" or something similar
118 curl_setopt($ch, CURLOPT_ENCODING, '');
120 if (x($opts, 'headers')) {
121 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
124 if (x($opts, 'nobody')) {
125 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
128 if (x($opts, 'timeout')) {
129 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
131 $curl_time = Config::get('system', 'curl_timeout', 60);
132 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
135 // by default we will allow self-signed certs
136 // but you can override this
138 $check_cert = Config::get('system', 'verifyssl');
139 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
142 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
145 $proxy = Config::get('system', 'proxy');
147 if (strlen($proxy)) {
148 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
149 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
150 $proxyuser = @Config::get('system', 'proxyuser');
152 if (strlen($proxyuser)) {
153 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
157 if (Config::get('system', 'ipv4_resolve', false)) {
158 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
162 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
165 $a->set_curl_code(0);
167 // don't let curl abort the entire application
168 // if it throws any errors.
170 $s = @curl_exec($ch);
171 $curl_info = @curl_getinfo($ch);
173 // Special treatment for HTTP Code 416
174 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
175 if (($curl_info['http_code'] == 416) && ($range > 0)) {
176 @curl_setopt($ch, CURLOPT_RANGE, '');
177 $s = @curl_exec($ch);
178 $curl_info = @curl_getinfo($ch);
181 if (curl_errno($ch) !== CURLE_OK) {
182 logger('fetch_url error fetching ' . $url . ': ' . curl_error($ch), LOGGER_NORMAL);
185 $ret['errno'] = curl_errno($ch);
188 $ret['info'] = $curl_info;
190 $http_code = $curl_info['http_code'];
192 logger('fetch_url ' . $url . ': ' . $http_code . " " . $s, LOGGER_DATA);
195 // Pull out multiple headers, e.g. proxy and continuation headers
196 // allow for HTTP/2.x without fixing code
198 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
199 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
201 $base = substr($base, strlen($chunk));
204 $a->set_curl_code($http_code);
205 $a->set_curl_content_type($curl_info['content_type']);
206 $a->set_curl_headers($header);
208 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
209 $new_location_info = @parse_url($curl_info['redirect_url']);
210 $old_location_info = @parse_url($curl_info['url']);
212 $newurl = $curl_info['redirect_url'];
214 if (($new_location_info['path'] == '') && ( $new_location_info['host'] != '')) {
215 $newurl = $new_location_info['scheme'] . '://' . $new_location_info['host'] . $old_location_info['path'];
220 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
221 $newurl = trim(array_pop($matches));
223 if (strpos($newurl, '/') === 0) {
224 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
227 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
230 return z_fetch_url($newurl, $binary, $redirects, $opts);
234 $a->set_curl_code($http_code);
235 $a->set_curl_content_type($curl_info['content_type']);
237 $rc = intval($http_code);
238 $ret['return_code'] = $rc;
239 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
240 $ret['redirect_url'] = $url;
242 if (!$ret['success']) {
243 $ret['error'] = curl_error($ch);
244 $ret['debug'] = $curl_info;
245 logger('z_fetch_url: error: '.$url.': '.$ret['return_code'].' - '.$ret['error'], LOGGER_DEBUG);
246 logger('z_fetch_url: debug: '.print_r($curl_info, true), LOGGER_DATA);
249 $ret['body'] = substr($s, strlen($header));
250 $ret['header'] = $header;
252 if (x($opts, 'debug')) {
253 $ret['debug'] = $curl_info;
258 $a->save_timestamp($stamp1, 'network');
264 * @brief Send POST request to $url
266 * @param string $url URL to post
267 * @param mixed $params array of POST variables
268 * @param string $headers HTTP headers
269 * @param integer $redirects Recursion counter for internal use - default = 0
270 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
272 * @return string The content
274 function post_url($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
276 $stamp1 = microtime(true);
278 if (blocked_url($url)) {
279 logger('post_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
284 $ch = curl_init($url);
286 if (($redirects > 8) || (!$ch)) {
290 logger('post_url: start ' . $url, LOGGER_DATA);
292 curl_setopt($ch, CURLOPT_HEADER, true);
293 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
294 curl_setopt($ch, CURLOPT_POST, 1);
295 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
296 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
298 if (Config::get('system', 'ipv4_resolve', false)) {
299 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
302 if (intval($timeout)) {
303 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
305 $curl_time = Config::get('system', 'curl_timeout', 60);
306 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
309 if (defined('LIGHTTPD')) {
310 if (!is_array($headers)) {
311 $headers = ['Expect:'];
313 if (!in_array('Expect:', $headers)) {
314 array_push($headers, 'Expect:');
320 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
323 $check_cert = Config::get('system', 'verifyssl');
324 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
327 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
330 $proxy = Config::get('system', 'proxy');
332 if (strlen($proxy)) {
333 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
334 curl_setopt($ch, CURLOPT_PROXY, $proxy);
335 $proxyuser = Config::get('system', 'proxyuser');
336 if (strlen($proxyuser)) {
337 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
341 $a->set_curl_code(0);
343 // don't let curl abort the entire application
344 // if it throws any errors.
346 $s = @curl_exec($ch);
349 $curl_info = curl_getinfo($ch);
350 $http_code = $curl_info['http_code'];
352 logger('post_url: result ' . $http_code . ' - ' . $url, LOGGER_DATA);
356 // Pull out multiple headers, e.g. proxy and continuation headers
357 // allow for HTTP/2.x without fixing code
359 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
360 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
362 $base = substr($base, strlen($chunk));
365 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
367 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
368 $newurl = trim(array_pop($matches));
370 if (strpos($newurl, '/') === 0) {
371 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
374 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
376 logger('post_url: redirect ' . $url . ' to ' . $newurl);
377 return post_url($newurl, $params, $headers, $redirects, $timeout);
381 $a->set_curl_code($http_code);
383 $body = substr($s, strlen($header));
385 $a->set_curl_headers($header);
389 $a->save_timestamp($stamp1, 'network');
391 logger('post_url: end ' . $url, LOGGER_DATA);
396 // Generic XML return
397 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
398 // of $st and an optional text <message> of $message and terminates the current process.
400 function xml_status($st, $message = '')
402 $result = ['status' => $st];
404 if ($message != '') {
405 $result['message'] = $message;
409 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
412 header("Content-type: text/xml");
414 $xmldata = ["result" => $result];
416 echo XML::fromArray($xmldata, $xml);
422 * @brief Send HTTP status header and exit.
424 * @param integer $val HTTP status result value
425 * @param array $description optional message
426 * 'title' => header title
427 * 'description' => optional message
431 * @brief Send HTTP status header and exit.
433 * @param integer $val HTTP status result value
434 * @param array $description optional message
435 * 'title' => header title
436 * 'description' => optional message
438 function http_status_exit($val, $description = [])
443 if (!isset($description["title"])) {
444 $description["title"] = $err." ".$val;
447 if ($val >= 200 && $val < 300)
450 logger('http_status_exit ' . $val);
451 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
453 if (isset($description["title"])) {
454 $tpl = get_markup_template('http_status.tpl');
458 '$title' => $description["title"],
459 '$description' => $description["description"]]
467 * @brief Check URL to se if ts's real
469 * Take a URL from the wild, prepend http:// if necessary
470 * and check DNS to see if it's real (or check if is a valid IP address)
472 * @param string $url The URL to be validated
473 * @return string|boolean The actual working URL, false else
475 function validate_url($url)
477 if (Config::get('system', 'disable_url_validation')) {
481 // no naked subdomains (allow localhost for tests)
482 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
486 if (substr($url, 0, 4) != 'http') {
487 $url = 'http://' . $url;
490 /// @TODO Really suppress function outcomes? Why not find them + debug them?
491 $h = @parse_url($url);
493 if ((is_array($h)) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
501 * @brief Checks that email is an actual resolvable internet address
503 * @param string $addr The email address
504 * @return boolean True if it's a valid email address, false if it's not
506 function validate_email($addr)
508 if (Config::get('system', 'disable_email_validation')) {
512 if (! strpos($addr, '@')) {
516 $h = substr($addr, strpos($addr, '@') + 1);
518 if (($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
525 * @brief Check if URL is allowed
527 * Check $url against our list of allowed sites,
528 * wildcards allowed. If allowed_sites is unset return true;
530 * @param string $url URL which get tested
531 * @return boolean True if url is allowed otherwise return false
533 function allowed_url($url)
535 $h = @parse_url($url);
541 $str_allowed = Config::get('system', 'allowed_sites');
542 if (! $str_allowed) {
548 $host = strtolower($h['host']);
550 // always allow our own site
551 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
555 $fnmatch = function_exists('fnmatch');
556 $allowed = explode(',', $str_allowed);
558 if (count($allowed)) {
559 foreach ($allowed as $a) {
560 $pat = strtolower(trim($a));
561 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
571 * Checks if the provided url domain is on the domain blocklist.
572 * Returns true if it is or malformed URL, false if not.
574 * @param string $url The url to check the domain from
578 function blocked_url($url)
580 $h = @parse_url($url);
586 $domain_blocklist = Config::get('system', 'blocklist', []);
587 if (! $domain_blocklist) {
591 $host = strtolower($h['host']);
593 foreach ($domain_blocklist as $domain_block) {
594 if (strtolower($domain_block['domain']) == $host) {
603 * @brief Check if email address is allowed to register here.
605 * Compare against our list (wildcards allowed).
607 * @param string $email email address
608 * @return boolean False if not allowed, true if allowed
609 * or if allowed list is not configured
611 function allowed_email($email)
613 $domain = strtolower(substr($email, strpos($email, '@') + 1));
618 $str_allowed = Config::get('system', 'allowed_email', '');
619 if (!x($str_allowed)) {
623 $allowed = explode(',', $str_allowed);
625 return allowed_domain($domain, $allowed);
629 * Checks for the existence of a domain in a domain list
631 * @brief Checks for the existence of a domain in a domain list
632 * @param string $domain
633 * @param array $domain_list
636 function allowed_domain($domain, array $domain_list)
640 foreach ($domain_list as $item) {
641 $pat = strtolower(trim($item));
642 if (fnmatch($pat, $domain) || ($pat == $domain)) {
651 function avatar_img($email)
653 $avatar['size'] = 175;
654 $avatar['email'] = $email;
656 $avatar['success'] = false;
658 Addon::callHooks('avatar_lookup', $avatar);
660 if (! $avatar['success']) {
661 $avatar['url'] = System::baseUrl() . '/images/person-175.jpg';
664 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
665 return $avatar['url'];
669 function parse_xml_string($s, $strict = true)
671 // the "strict" parameter is deactivated
673 /// @todo Move this function to the xml class
674 libxml_use_internal_errors(true);
676 $x = @simplexml_load_string($s);
678 logger('libxml: parse: error: ' . $s, LOGGER_DATA);
679 foreach (libxml_get_errors() as $err) {
680 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
682 libxml_clear_errors();
687 function scale_external_images($srctext, $include_link = true, $scale_replace = false)
689 // Suppress "view full size"
690 if (intval(Config::get('system', 'no_view_full_size'))) {
691 $include_link = false;
694 // Picture addresses can contain special characters
695 $s = htmlspecialchars_decode($srctext);
698 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism', $s, $matches, PREG_SET_ORDER);
700 foreach ($matches as $mtch) {
701 logger('scale_external_image: ' . $mtch[1]);
703 $hostname = str_replace('www.', '', substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3));
704 if (stristr($mtch[1], $hostname)) {
708 // $scale_replace, if passed, is an array of two elements. The
709 // first is the name of the full-size image. The second is the
710 // name of a remote, scaled-down version of the full size image.
711 // This allows Friendica to display the smaller remote image if
712 // one exists, while still linking to the full-size image
713 if ($scale_replace) {
714 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
718 $i = fetch_url($scaled);
723 // guess mimetype from headers or filename
724 $type = Image::guessType($mtch[1], true);
727 $Image = new Image($i, $type);
728 if ($Image->isValid()) {
729 $orig_width = $Image->getWidth();
730 $orig_height = $Image->getHeight();
732 if ($orig_width > 640 || $orig_height > 640) {
733 $Image->scaleDown(640);
734 $new_width = $Image->getWidth();
735 $new_height = $Image->getHeight();
736 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
739 '[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
740 . "\n" . (($include_link)
741 ? '[url=' . $mtch[1] . ']' . L10n::t('view full size') . '[/url]' . "\n"
745 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
752 // replace the special char encoding
753 $s = htmlspecialchars($s, ENT_NOQUOTES, 'UTF-8');
758 function fix_contact_ssl_policy(&$contact, $new_policy)
760 $ssl_changed = false;
761 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
763 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
764 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
765 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
766 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
767 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
768 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
771 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
773 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
774 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
775 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
776 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
777 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
778 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
782 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
783 'notify' => $contact['notify'], 'poll' => $contact['poll'],
784 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
785 dba::update('contact', $fields, ['id' => $contact['id']]);
790 * @brief Remove Google Analytics and other tracking platforms params from URL
792 * @param string $url Any user-submitted URL that may contain tracking params
793 * @return string The same URL stripped of tracking parameters
795 function strip_tracking_query_params($url)
797 $urldata = parse_url($url);
798 if (is_string($urldata["query"])) {
799 $query = $urldata["query"];
800 parse_str($query, $querydata);
802 if (is_array($querydata)) {
803 foreach ($querydata as $param => $value) {
807 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
808 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
809 "fb_action_ids", "fb_action_types", "fb_ref",
811 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
814 $pair = $param . "=" . urlencode($value);
815 $url = str_replace($pair, "", $url);
817 // Second try: if the url isn't encoded completely
818 $pair = $param . "=" . str_replace(" ", "+", $value);
819 $url = str_replace($pair, "", $url);
821 // Third try: Maybey the url isn't encoded at all
822 $pair = $param . "=" . $value;
823 $url = str_replace($pair, "", $url);
825 $url = str_replace(["?&", "&&"], ["?", ""], $url);
830 if (substr($url, -1, 1) == "?") {
831 $url = substr($url, 0, -1);
839 * @brief Returns the original URL of the provided URL
841 * This function strips tracking query params and follows redirections, either
842 * through HTTP code or meta refresh tags. Stops after 10 redirections.
844 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
846 * @see ParseUrl::getSiteinfo
848 * @param string $url A user-submitted URL
849 * @param int $depth The current redirection recursion level (internal)
850 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
851 * @return string A canonical URL
853 function original_url($url, $depth = 1, $fetchbody = false)
857 $url = strip_tracking_query_params($url);
863 $url = trim($url, "'");
865 $stamp1 = microtime(true);
868 curl_setopt($ch, CURLOPT_URL, $url);
869 curl_setopt($ch, CURLOPT_HEADER, 1);
870 curl_setopt($ch, CURLOPT_NOBODY, 1);
871 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
872 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
873 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
876 $curl_info = @curl_getinfo($ch);
877 $http_code = $curl_info['http_code'];
880 $a->save_timestamp($stamp1, "network");
885 if ((($curl_info['http_code'] == "301") || ($curl_info['http_code'] == "302"))
886 && (($curl_info['redirect_url'] != "") || ($curl_info['location'] != ""))
888 if ($curl_info['redirect_url'] != "") {
889 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
891 return(original_url($curl_info['location'], ++$depth, $fetchbody));
895 // Check for redirects in the meta elements of the body if there are no redirects in the header.
897 return(original_url($url, ++$depth, true));
900 // if the file is too large then exit
901 if ($curl_info["download_content_length"] > 1000000) {
905 // if it isn't a HTML file then exit
906 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
910 $stamp1 = microtime(true);
913 curl_setopt($ch, CURLOPT_URL, $url);
914 curl_setopt($ch, CURLOPT_HEADER, 0);
915 curl_setopt($ch, CURLOPT_NOBODY, 0);
916 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
917 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
918 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
920 $body = curl_exec($ch);
923 $a->save_timestamp($stamp1, "network");
925 if (trim($body) == "") {
929 // Check for redirect in meta elements
930 $doc = new DOMDocument();
931 @$doc->loadHTML($body);
933 $xpath = new DomXPath($doc);
935 $list = $xpath->query("//meta[@content]");
936 foreach ($list as $node) {
938 if ($node->attributes->length) {
939 foreach ($node->attributes as $attribute) {
940 $attr[$attribute->name] = $attribute->value;
944 if (@$attr["http-equiv"] == 'refresh') {
945 $path = $attr["content"];
946 $pathinfo = explode(";", $path);
947 foreach ($pathinfo as $value) {
948 if (substr(strtolower($value), 0, 4) == "url=") {
949 return(original_url(substr($value, 4), ++$depth));
958 function short_link($url)
960 require_once 'library/slinky.php';
961 $slinky = new Slinky($url);
962 $yourls_url = Config::get('yourls', 'url1');
964 $yourls_username = Config::get('yourls', 'username1');
965 $yourls_password = Config::get('yourls', 'password1');
966 $yourls_ssl = Config::get('yourls', 'ssl1');
967 $yourls = new Slinky_YourLS();
968 $yourls->set('username', $yourls_username);
969 $yourls->set('password', $yourls_password);
970 $yourls->set('ssl', $yourls_ssl);
971 $yourls->set('yourls-url', $yourls_url);
972 $slinky->set_cascade([$yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()]);
974 // setup a cascade of shortening services
975 // try to get a short link from these services
976 // in the order ur1.ca, tinyurl
977 $slinky->set_cascade([new Slinky_Ur1ca(), new Slinky_TinyURL()]);
979 return $slinky->short();
983 * @brief Encodes content to json
985 * This function encodes an array to json format
986 * and adds an application/json HTTP header to the output.
987 * After finishing the process is getting killed.
989 * @param array $x The input content
991 function json_return_and_die($x)
993 header("content-type: application/json");
994 echo json_encode($x);
999 * @brief Find the matching part between two url
1001 * @param string $url1
1002 * @param string $url2
1003 * @return string The matching part
1005 function matching_url($url1, $url2)
1007 if (($url1 == "") || ($url2 == "")) {
1011 $url1 = normalise_link($url1);
1012 $url2 = normalise_link($url2);
1014 $parts1 = parse_url($url1);
1015 $parts2 = parse_url($url2);
1017 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
1021 if ($parts1["scheme"] != $parts2["scheme"]) {
1025 if ($parts1["host"] != $parts2["host"]) {
1029 if ($parts1["port"] != $parts2["port"]) {
1033 $match = $parts1["scheme"]."://".$parts1["host"];
1035 if ($parts1["port"]) {
1036 $match .= ":".$parts1["port"];
1039 $pathparts1 = explode("/", $parts1["path"]);
1040 $pathparts2 = explode("/", $parts2["path"]);
1045 $path1 = $pathparts1[$i];
1046 $path2 = $pathparts2[$i];
1048 if ($path1 == $path2) {
1049 $path .= $path1."/";
1051 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
1055 return normalise_link($match);
1059 * @brief Glue url parts together
1061 * @param array $parsed URL parts
1063 * @return string The glued URL
1065 function unParseUrl($parsed)
1067 $get = function ($key) use ($parsed) {
1068 return isset($parsed[$key]) ? $parsed[$key] : null;
1071 $pass = $get('pass');
1072 $user = $get('user');
1073 $userinfo = $pass !== null ? "$user:$pass" : $user;
1074 $port = $get('port');
1075 $scheme = $get('scheme');
1076 $query = $get('query');
1077 $fragment = $get('fragment');
1078 $authority = ($userinfo !== null ? $userinfo."@" : '') .
1080 ($port ? ":$port" : '');
1082 return (strlen($scheme) ? $scheme.":" : '') .
1083 (strlen($authority) ? "//".$authority : '') .
1085 (strlen($query) ? "?".$query : '') .
1086 (strlen($fragment) ? "#".$fragment : '');