3 * @file include/network.php
6 use Friendica\Core\System;
7 use Friendica\Core\Config;
8 use Friendica\Network\Probe;
9 use Friendica\Object\Image;
10 use Friendica\Util\XML;
15 * If binary flag is true, return binary results.
16 * Set the cookiejar argument to a string (e.g. "/tmp/friendica-cookies.txt")
17 * to preserve cookies from one request to the next.
19 * @param string $url URL to fetch
20 * @param boolean $binary default false
21 * TRUE if asked to return binary results (file download)
22 * @param integer $redirects The recursion counter for internal use - default 0
23 * @param integer $timeout Timeout in seconds, default system config value or 60 seconds
24 * @param string $accept_content supply Accept: header with 'accept_content' as the value
25 * @param string $cookiejar Path to cookie jar file
27 * @return string The fetched content
29 function fetch_url($url, $binary = false, &$redirects = 0, $timeout = 0, $accept_content = null, $cookiejar = 0)
36 'accept_content'=>$accept_content,
37 'cookiejar'=>$cookiejar
45 * @brief fetches an URL.
47 * @param string $url URL to fetch
48 * @param boolean $binary default false
49 * TRUE if asked to return binary results (file download)
50 * @param int $redirects The recursion counter for internal use - default 0
51 * @param array $opts (optional parameters) assoziative array with:
52 * 'accept_content' => supply Accept: header with 'accept_content' as the value
53 * 'timeout' => int Timeout in seconds, default system config value or 60 seconds
54 * 'http_auth' => username:password
55 * 'novalidate' => do not validate SSL certs, default is to validate using our CA list
56 * 'nobody' => only return the header
57 * 'cookiejar' => path to cookie jar file
59 * @return array an assoziative array with:
60 * int 'return_code' => HTTP return code or 0 if timeout or failure
61 * boolean 'success' => boolean true (if HTTP 2xx result) or false
62 * string 'redirect_url' => in case of redirect, content was finally retrieved from this URL
63 * string 'header' => HTTP headers
64 * string 'body' => fetched content
66 function z_fetch_url($url, $binary = false, &$redirects = 0, $opts = [])
68 $ret = ['return_code' => 0, 'success' => false, 'header' => '', 'info' => '', 'body' => ''];
70 $stamp1 = microtime(true);
74 if (blocked_url($url)) {
75 logger('z_fetch_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
79 $ch = @curl_init($url);
81 if (($redirects > 8) || (!$ch)) {
85 @curl_setopt($ch, CURLOPT_HEADER, true);
87 if (x($opts, "cookiejar")) {
88 curl_setopt($ch, CURLOPT_COOKIEJAR, $opts["cookiejar"]);
89 curl_setopt($ch, CURLOPT_COOKIEFILE, $opts["cookiejar"]);
92 // These settings aren't needed. We're following the location already.
93 // @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
94 // @curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
96 if (x($opts, 'accept_content')) {
100 ['Accept: ' . $opts['accept_content']]
104 @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
105 @curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
107 $range = intval(Config::get('system', 'curl_range_bytes', 0));
110 @curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
113 // Without this setting it seems as if some webservers send compressed content
114 // This seems to confuse curl so that it shows this uncompressed.
115 /// @todo We could possibly set this value to "gzip" or something similar
116 curl_setopt($ch, CURLOPT_ENCODING, '');
118 if (x($opts, 'headers')) {
119 @curl_setopt($ch, CURLOPT_HTTPHEADER, $opts['headers']);
122 if (x($opts, 'nobody')) {
123 @curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);
126 if (x($opts, 'timeout')) {
127 @curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
129 $curl_time = Config::get('system', 'curl_timeout', 60);
130 @curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
133 // by default we will allow self-signed certs
134 // but you can override this
136 $check_cert = Config::get('system', 'verifyssl');
137 @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
140 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
143 $proxy = Config::get('system', 'proxy');
145 if (strlen($proxy)) {
146 @curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
147 @curl_setopt($ch, CURLOPT_PROXY, $proxy);
148 $proxyuser = @Config::get('system', 'proxyuser');
150 if (strlen($proxyuser)) {
151 @curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
155 if (Config::get('system', 'ipv4_resolve', false)) {
156 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
160 @curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
163 $a->set_curl_code(0);
165 // don't let curl abort the entire application
166 // if it throws any errors.
168 $s = @curl_exec($ch);
169 $curl_info = @curl_getinfo($ch);
171 // Special treatment for HTTP Code 416
172 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
173 if (($curl_info['http_code'] == 416) && ($range > 0)) {
174 @curl_setopt($ch, CURLOPT_RANGE, '');
175 $s = @curl_exec($ch);
176 $curl_info = @curl_getinfo($ch);
179 if (curl_errno($ch) !== CURLE_OK) {
180 logger('fetch_url error fetching ' . $url . ': ' . curl_error($ch), LOGGER_NORMAL);
183 $ret['errno'] = curl_errno($ch);
186 $ret['info'] = $curl_info;
188 $http_code = $curl_info['http_code'];
190 logger('fetch_url ' . $url . ': ' . $http_code . " " . $s, LOGGER_DATA);
193 // Pull out multiple headers, e.g. proxy and continuation headers
194 // allow for HTTP/2.x without fixing code
196 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
197 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
199 $base = substr($base, strlen($chunk));
202 $a->set_curl_code($http_code);
203 $a->set_curl_content_type($curl_info['content_type']);
204 $a->set_curl_headers($header);
206 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
207 $new_location_info = @parse_url($curl_info['redirect_url']);
208 $old_location_info = @parse_url($curl_info['url']);
210 $newurl = $curl_info['redirect_url'];
212 if (($new_location_info['path'] == '') && ( $new_location_info['host'] != '')) {
213 $newurl = $new_location_info['scheme'] . '://' . $new_location_info['host'] . $old_location_info['path'];
218 if (preg_match('/(Location:|URI:)(.*?)\n/i', $header, $matches)) {
219 $newurl = trim(array_pop($matches));
221 if (strpos($newurl, '/') === 0) {
222 $newurl = $old_location_info["scheme"]."://".$old_location_info["host"].$newurl;
225 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
228 return z_fetch_url($newurl, $binary, $redirects, $opts);
232 $a->set_curl_code($http_code);
233 $a->set_curl_content_type($curl_info['content_type']);
235 $rc = intval($http_code);
236 $ret['return_code'] = $rc;
237 $ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
238 $ret['redirect_url'] = $url;
240 if (!$ret['success']) {
241 $ret['error'] = curl_error($ch);
242 $ret['debug'] = $curl_info;
243 logger('z_fetch_url: error: '.$url.': '.$ret['return_code'].' - '.$ret['error'], LOGGER_DEBUG);
244 logger('z_fetch_url: debug: '.print_r($curl_info, true), LOGGER_DATA);
247 $ret['body'] = substr($s, strlen($header));
248 $ret['header'] = $header;
250 if (x($opts, 'debug')) {
251 $ret['debug'] = $curl_info;
256 $a->save_timestamp($stamp1, 'network');
262 * @brief Send POST request to $url
264 * @param string $url URL to post
265 * @param mixed $params array of POST variables
266 * @param string $headers HTTP headers
267 * @param integer $redirects Recursion counter for internal use - default = 0
268 * @param integer $timeout The timeout in seconds, default system config value or 60 seconds
270 * @return string The content
272 function post_url($url, $params, $headers = null, &$redirects = 0, $timeout = 0)
274 $stamp1 = microtime(true);
276 if (blocked_url($url)) {
277 logger('post_url: domain of ' . $url . ' is blocked', LOGGER_DATA);
282 $ch = curl_init($url);
284 if (($redirects > 8) || (!$ch)) {
288 logger('post_url: start ' . $url, LOGGER_DATA);
290 curl_setopt($ch, CURLOPT_HEADER, true);
291 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
292 curl_setopt($ch, CURLOPT_POST, 1);
293 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
294 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
296 if (Config::get('system', 'ipv4_resolve', false)) {
297 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
300 if (intval($timeout)) {
301 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
303 $curl_time = Config::get('system', 'curl_timeout', 60);
304 curl_setopt($ch, CURLOPT_TIMEOUT, intval($curl_time));
307 if (defined('LIGHTTPD')) {
308 if (!is_array($headers)) {
309 $headers = ['Expect:'];
311 if (!in_array('Expect:', $headers)) {
312 array_push($headers, 'Expect:');
318 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
321 $check_cert = Config::get('system', 'verifyssl');
322 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
325 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
328 $proxy = Config::get('system', 'proxy');
330 if (strlen($proxy)) {
331 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
332 curl_setopt($ch, CURLOPT_PROXY, $proxy);
333 $proxyuser = Config::get('system', 'proxyuser');
334 if (strlen($proxyuser)) {
335 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyuser);
339 $a->set_curl_code(0);
341 // don't let curl abort the entire application
342 // if it throws any errors.
344 $s = @curl_exec($ch);
347 $curl_info = curl_getinfo($ch);
348 $http_code = $curl_info['http_code'];
350 logger('post_url: result ' . $http_code . ' - ' . $url, LOGGER_DATA);
354 // Pull out multiple headers, e.g. proxy and continuation headers
355 // allow for HTTP/2.x without fixing code
357 while (preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/', $base)) {
358 $chunk = substr($base, 0, strpos($base, "\r\n\r\n") + 4);
360 $base = substr($base, strlen($chunk));
363 if ($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307) {
365 preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
366 $newurl = trim(array_pop($matches));
368 if (strpos($newurl, '/') === 0) {
369 $newurl = $old_location_info["scheme"] . "://" . $old_location_info["host"] . $newurl;
372 if (filter_var($newurl, FILTER_VALIDATE_URL)) {
374 logger('post_url: redirect ' . $url . ' to ' . $newurl);
375 return post_url($newurl, $params, $headers, $redirects, $timeout);
379 $a->set_curl_code($http_code);
381 $body = substr($s, strlen($header));
383 $a->set_curl_headers($header);
387 $a->save_timestamp($stamp1, 'network');
389 logger('post_url: end ' . $url, LOGGER_DATA);
394 // Generic XML return
395 // Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
396 // of $st and an optional text <message> of $message and terminates the current process.
398 function xml_status($st, $message = '')
400 $result = ['status' => $st];
402 if ($message != '') {
403 $result['message'] = $message;
407 logger('xml_status returning non_zero: ' . $st . " message=" . $message);
410 header("Content-type: text/xml");
412 $xmldata = ["result" => $result];
414 echo XML::fromArray($xmldata, $xml);
420 * @brief Send HTTP status header and exit.
422 * @param integer $val HTTP status result value
423 * @param array $description optional message
424 * 'title' => header title
425 * 'description' => optional message
429 * @brief Send HTTP status header and exit.
431 * @param integer $val HTTP status result value
432 * @param array $description optional message
433 * 'title' => header title
434 * 'description' => optional message
436 function http_status_exit($val, $description = [])
441 if (!isset($description["title"])) {
442 $description["title"] = $err." ".$val;
445 if ($val >= 200 && $val < 300)
448 logger('http_status_exit ' . $val);
449 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
451 if (isset($description["title"])) {
452 $tpl = get_markup_template('http_status.tpl');
456 '$title' => $description["title"],
457 '$description' => $description["description"]]
465 * @brief Check URL to se if ts's real
467 * Take a URL from the wild, prepend http:// if necessary
468 * and check DNS to see if it's real (or check if is a valid IP address)
470 * @param string $url The URL to be validated
471 * @return string|boolean The actual working URL, false else
473 function validate_url($url)
475 if (Config::get('system', 'disable_url_validation')) {
479 // no naked subdomains (allow localhost for tests)
480 if (strpos($url, '.') === false && strpos($url, '/localhost/') === false) {
484 if (substr($url, 0, 4) != 'http') {
485 $url = 'http://' . $url;
488 /// @TODO Really suppress function outcomes? Why not find them + debug them?
489 $h = @parse_url($url);
491 if ((is_array($h)) && (@dns_get_record($h['host'], DNS_A + DNS_CNAME + DNS_PTR) || filter_var($h['host'], FILTER_VALIDATE_IP) )) {
499 * @brief Checks that email is an actual resolvable internet address
501 * @param string $addr The email address
502 * @return boolean True if it's a valid email address, false if it's not
504 function validate_email($addr)
506 if (Config::get('system', 'disable_email_validation')) {
510 if (! strpos($addr, '@')) {
514 $h = substr($addr, strpos($addr, '@') + 1);
516 if (($h) && (dns_get_record($h, DNS_A + DNS_CNAME + DNS_PTR + DNS_MX) || filter_var($h, FILTER_VALIDATE_IP) )) {
523 * @brief Check if URL is allowed
525 * Check $url against our list of allowed sites,
526 * wildcards allowed. If allowed_sites is unset return true;
528 * @param string $url URL which get tested
529 * @return boolean True if url is allowed otherwise return false
531 function allowed_url($url)
533 $h = @parse_url($url);
539 $str_allowed = Config::get('system', 'allowed_sites');
540 if (! $str_allowed) {
546 $host = strtolower($h['host']);
548 // always allow our own site
549 if ($host == strtolower($_SERVER['SERVER_NAME'])) {
553 $fnmatch = function_exists('fnmatch');
554 $allowed = explode(',', $str_allowed);
556 if (count($allowed)) {
557 foreach ($allowed as $a) {
558 $pat = strtolower(trim($a));
559 if (($fnmatch && fnmatch($pat, $host)) || ($pat == $host)) {
569 * Checks if the provided url domain is on the domain blocklist.
570 * Returns true if it is or malformed URL, false if not.
572 * @param string $url The url to check the domain from
576 function blocked_url($url)
578 $h = @parse_url($url);
584 $domain_blocklist = Config::get('system', 'blocklist', []);
585 if (! $domain_blocklist) {
589 $host = strtolower($h['host']);
591 foreach ($domain_blocklist as $domain_block) {
592 if (strtolower($domain_block['domain']) == $host) {
601 * @brief Check if email address is allowed to register here.
603 * Compare against our list (wildcards allowed).
605 * @param string $email email address
606 * @return boolean False if not allowed, true if allowed
607 * or if allowed list is not configured
609 function allowed_email($email)
611 $domain = strtolower(substr($email, strpos($email, '@') + 1));
616 $str_allowed = Config::get('system', 'allowed_email', '');
617 if (!x($str_allowed)) {
621 $allowed = explode(',', $str_allowed);
623 return allowed_domain($domain, $allowed);
627 * Checks for the existence of a domain in a domain list
629 * @brief Checks for the existence of a domain in a domain list
630 * @param string $domain
631 * @param array $domain_list
634 function allowed_domain($domain, array $domain_list)
638 foreach ($domain_list as $item) {
639 $pat = strtolower(trim($item));
640 if (fnmatch($pat, $domain) || ($pat == $domain)) {
649 function avatar_img($email)
651 $avatar['size'] = 175;
652 $avatar['email'] = $email;
654 $avatar['success'] = false;
656 call_hooks('avatar_lookup', $avatar);
658 if (! $avatar['success']) {
659 $avatar['url'] = System::baseUrl() . '/images/person-175.jpg';
662 logger('Avatar: ' . $avatar['email'] . ' ' . $avatar['url'], LOGGER_DEBUG);
663 return $avatar['url'];
667 function parse_xml_string($s, $strict = true)
669 // the "strict" parameter is deactivated
671 /// @todo Move this function to the xml class
672 libxml_use_internal_errors(true);
674 $x = @simplexml_load_string($s);
676 logger('libxml: parse: error: ' . $s, LOGGER_DATA);
677 foreach (libxml_get_errors() as $err) {
678 logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
680 libxml_clear_errors();
685 function scale_external_images($srctext, $include_link = true, $scale_replace = false)
687 // Suppress "view full size"
688 if (intval(Config::get('system', 'no_view_full_size'))) {
689 $include_link = false;
692 // Picture addresses can contain special characters
693 $s = htmlspecialchars_decode($srctext);
696 $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism', $s, $matches, PREG_SET_ORDER);
698 foreach ($matches as $mtch) {
699 logger('scale_external_image: ' . $mtch[1]);
701 $hostname = str_replace('www.', '', substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3));
702 if (stristr($mtch[1], $hostname)) {
706 // $scale_replace, if passed, is an array of two elements. The
707 // first is the name of the full-size image. The second is the
708 // name of a remote, scaled-down version of the full size image.
709 // This allows Friendica to display the smaller remote image if
710 // one exists, while still linking to the full-size image
711 if ($scale_replace) {
712 $scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[1]);
716 $i = fetch_url($scaled);
721 // guess mimetype from headers or filename
722 $type = Image::guessType($mtch[1], true);
725 $Image = new Image($i, $type);
726 if ($Image->isValid()) {
727 $orig_width = $Image->getWidth();
728 $orig_height = $Image->getHeight();
730 if ($orig_width > 640 || $orig_height > 640) {
731 $Image->scaleDown(640);
732 $new_width = $Image->getWidth();
733 $new_height = $Image->getHeight();
734 logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
737 '[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
738 . "\n" . (($include_link)
739 ? '[url=' . $mtch[1] . ']' . t('view full size') . '[/url]' . "\n"
743 logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG);
750 // replace the special char encoding
751 $s = htmlspecialchars($s, ENT_NOQUOTES, 'UTF-8');
756 function fix_contact_ssl_policy(&$contact, $new_policy)
758 $ssl_changed = false;
759 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
761 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
762 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
763 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
764 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
765 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
766 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
769 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
771 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
772 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
773 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
774 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
775 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
776 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
780 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
781 'notify' => $contact['notify'], 'poll' => $contact['poll'],
782 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
783 dba::update('contact', $fields, ['id' => $contact['id']]);
788 * @brief Remove Google Analytics and other tracking platforms params from URL
790 * @param string $url Any user-submitted URL that may contain tracking params
791 * @return string The same URL stripped of tracking parameters
793 function strip_tracking_query_params($url)
795 $urldata = parse_url($url);
796 if (is_string($urldata["query"])) {
797 $query = $urldata["query"];
798 parse_str($query, $querydata);
800 if (is_array($querydata)) {
801 foreach ($querydata as $param => $value) {
805 "utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
806 "wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
807 "fb_action_ids", "fb_action_types", "fb_ref",
809 "woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
812 $pair = $param . "=" . urlencode($value);
813 $url = str_replace($pair, "", $url);
815 // Second try: if the url isn't encoded completely
816 $pair = $param . "=" . str_replace(" ", "+", $value);
817 $url = str_replace($pair, "", $url);
819 // Third try: Maybey the url isn't encoded at all
820 $pair = $param . "=" . $value;
821 $url = str_replace($pair, "", $url);
823 $url = str_replace(["?&", "&&"], ["?", ""], $url);
828 if (substr($url, -1, 1) == "?") {
829 $url = substr($url, 0, -1);
837 * @brief Returns the original URL of the provided URL
839 * This function strips tracking query params and follows redirections, either
840 * through HTTP code or meta refresh tags. Stops after 10 redirections.
842 * @todo Remove the $fetchbody parameter that generates an extraneous HEAD request
844 * @see ParseUrl::getSiteinfo
846 * @param string $url A user-submitted URL
847 * @param int $depth The current redirection recursion level (internal)
848 * @param bool $fetchbody Wether to fetch the body or not after the HEAD requests
849 * @return string A canonical URL
851 function original_url($url, $depth = 1, $fetchbody = false)
855 $url = strip_tracking_query_params($url);
861 $url = trim($url, "'");
863 $stamp1 = microtime(true);
866 curl_setopt($ch, CURLOPT_URL, $url);
867 curl_setopt($ch, CURLOPT_HEADER, 1);
868 curl_setopt($ch, CURLOPT_NOBODY, 1);
869 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
870 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
871 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
874 $curl_info = @curl_getinfo($ch);
875 $http_code = $curl_info['http_code'];
878 $a->save_timestamp($stamp1, "network");
883 if ((($curl_info['http_code'] == "301") || ($curl_info['http_code'] == "302"))
884 && (($curl_info['redirect_url'] != "") || ($curl_info['location'] != ""))
886 if ($curl_info['redirect_url'] != "") {
887 return(original_url($curl_info['redirect_url'], ++$depth, $fetchbody));
889 return(original_url($curl_info['location'], ++$depth, $fetchbody));
893 // Check for redirects in the meta elements of the body if there are no redirects in the header.
895 return(original_url($url, ++$depth, true));
898 // if the file is too large then exit
899 if ($curl_info["download_content_length"] > 1000000) {
903 // if it isn't a HTML file then exit
904 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
908 $stamp1 = microtime(true);
911 curl_setopt($ch, CURLOPT_URL, $url);
912 curl_setopt($ch, CURLOPT_HEADER, 0);
913 curl_setopt($ch, CURLOPT_NOBODY, 0);
914 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
915 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
916 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
918 $body = curl_exec($ch);
921 $a->save_timestamp($stamp1, "network");
923 if (trim($body) == "") {
927 // Check for redirect in meta elements
928 $doc = new DOMDocument();
929 @$doc->loadHTML($body);
931 $xpath = new DomXPath($doc);
933 $list = $xpath->query("//meta[@content]");
934 foreach ($list as $node) {
936 if ($node->attributes->length) {
937 foreach ($node->attributes as $attribute) {
938 $attr[$attribute->name] = $attribute->value;
942 if (@$attr["http-equiv"] == 'refresh') {
943 $path = $attr["content"];
944 $pathinfo = explode(";", $path);
945 foreach ($pathinfo as $value) {
946 if (substr(strtolower($value), 0, 4) == "url=") {
947 return(original_url(substr($value, 4), ++$depth));
956 function short_link($url)
958 require_once 'library/slinky.php';
959 $slinky = new Slinky($url);
960 $yourls_url = Config::get('yourls', 'url1');
962 $yourls_username = Config::get('yourls', 'username1');
963 $yourls_password = Config::get('yourls', 'password1');
964 $yourls_ssl = Config::get('yourls', 'ssl1');
965 $yourls = new Slinky_YourLS();
966 $yourls->set('username', $yourls_username);
967 $yourls->set('password', $yourls_password);
968 $yourls->set('ssl', $yourls_ssl);
969 $yourls->set('yourls-url', $yourls_url);
970 $slinky->set_cascade([$yourls, new Slinky_Ur1ca(), new Slinky_TinyURL()]);
972 // setup a cascade of shortening services
973 // try to get a short link from these services
974 // in the order ur1.ca, tinyurl
975 $slinky->set_cascade([new Slinky_Ur1ca(), new Slinky_TinyURL()]);
977 return $slinky->short();
981 * @brief Encodes content to json
983 * This function encodes an array to json format
984 * and adds an application/json HTTP header to the output.
985 * After finishing the process is getting killed.
987 * @param array $x The input content
989 function json_return_and_die($x)
991 header("content-type: application/json");
992 echo json_encode($x);
997 * @brief Find the matching part between two url
999 * @param string $url1
1000 * @param string $url2
1001 * @return string The matching part
1003 function matching_url($url1, $url2)
1005 if (($url1 == "") || ($url2 == "")) {
1009 $url1 = normalise_link($url1);
1010 $url2 = normalise_link($url2);
1012 $parts1 = parse_url($url1);
1013 $parts2 = parse_url($url2);
1015 if (!isset($parts1["host"]) || !isset($parts2["host"])) {
1019 if ($parts1["scheme"] != $parts2["scheme"]) {
1023 if ($parts1["host"] != $parts2["host"]) {
1027 if ($parts1["port"] != $parts2["port"]) {
1031 $match = $parts1["scheme"]."://".$parts1["host"];
1033 if ($parts1["port"]) {
1034 $match .= ":".$parts1["port"];
1037 $pathparts1 = explode("/", $parts1["path"]);
1038 $pathparts2 = explode("/", $parts2["path"]);
1043 $path1 = $pathparts1[$i];
1044 $path2 = $pathparts2[$i];
1046 if ($path1 == $path2) {
1047 $path .= $path1."/";
1049 } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
1053 return normalise_link($match);
1057 * @brief Glue url parts together
1059 * @param array $parsed URL parts
1061 * @return string The glued URL
1063 function unParseUrl($parsed)
1065 $get = function ($key) use ($parsed) {
1066 return isset($parsed[$key]) ? $parsed[$key] : null;
1069 $pass = $get('pass');
1070 $user = $get('user');
1071 $userinfo = $pass !== null ? "$user:$pass" : $user;
1072 $port = $get('port');
1073 $scheme = $get('scheme');
1074 $query = $get('query');
1075 $fragment = $get('fragment');
1076 $authority = ($userinfo !== null ? $userinfo."@" : '') .
1078 ($port ? ":$port" : '');
1080 return (strlen($scheme) ? $scheme.":" : '') .
1081 (strlen($authority) ? "//".$authority : '') .
1083 (strlen($query) ? "?".$query : '') .
1084 (strlen($fragment) ? "#".$fragment : '');