network.php 67.7 KB
Newer Older
1 2 3 4
<?php
/**
 * @file include/network.php
 */
5

6 7 8 9 10
/**
 * @brief Returns path to CA file.
 *
 * @return string
 */
11 12 13 14
function get_capath() {
	return appdirpath() . '/library/cacert.pem';
}

15
/**
16 17
 * @brief fetches an URL.
 *
18 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 int $redirects default 0
23
 *    internal use, recursion counter
24
 * @param array $opts (optional parameters) associative array with:
25
 *  * \b timeout => int seconds, default system config value or 60 seconds
26
 *  * \b headers => array of additional header fields
27 28 29
 *  * \b http_auth => username:password
 *  * \b novalidate => do not validate SSL certs, default is to validate using our CA list
 *  * \b nobody => only return the header
30
 *  * \b filep => stream resource to write body to. header and body are not returned when using this option.
31
 *  * \b custom => custom request method: e.g. 'PUT', 'DELETE'
32
 *  * \b cookiejar => cookie file (write)
33
 *  * \b cookiefile => cookie file (read)
34
 *  * \b session => boolean; append session cookie *if* $url is our own site
35
 *
36
 * @return array an associative array with:
37 38
 *  * \e int \b return_code => HTTP return code or 0 if timeout or failure
 *  * \e boolean \b success => boolean true (if HTTP 2xx result) or false
39
 *  * \e string \b header => HTTP headers
40
 *  * \e string \b body => fetched content
41
 */
42
function z_fetch_url($url, $binary = false, $redirects = 0, $opts = array()) {
43 44 45 46

	$ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => "");

	$ch = @curl_init($url);
47
	if(($redirects > 8) || (! $ch))
48
		return $ret;
49 50

	@curl_setopt($ch, CURLOPT_HEADER, true);
51
	@curl_setopt($ch, CURLINFO_HEADER_OUT, true);
52
	@curl_setopt($ch, CURLOPT_CAINFO, get_capath());
53 54
	@curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
	@curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
Zot's avatar
Zot committed
55
	@curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; zot)");
56

57
	$ciphers = @get_config('system','curl_ssl_ciphers');
58 59
	if($ciphers)
		@curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, $ciphers);
60

61 62
	if(x($opts,'filep')) {
		@curl_setopt($ch, CURLOPT_FILE, $opts['filep']);
Zot's avatar
Zot committed
63
		@curl_setopt($ch, CURLOPT_HEADER, false);
64 65
	}

66 67
	if(x($opts,'upload'))
		@curl_setopt($ch, CURLOPT_UPLOAD, $opts['upload']);
68

69 70
	if(x($opts,'infile'))
		@curl_setopt($ch, CURLOPT_INFILE, $opts['infile']);
71

72 73 74 75 76
	if(x($opts,'infilesize'))
		@curl_setopt($ch, CURLOPT_INFILESIZE, $opts['infilesize']);

	if(x($opts,'readfunc'))
		@curl_setopt($ch, CURLOPT_READFUNCTION, $opts['readfunc']);
77

78
	// When using the session option and fetching from our own site,
79 80 81 82 83 84 85 86 87 88 89 90 91 92
	// append the PHPSESSID cookie to any existing headers.
	// Don't add to $opts['headers'] so that the cookie does not get
	// sent to other sites via redirects

	$instance_headers = ((array_key_exists('headers',$opts) && is_array($opts['headers'])) ? $opts['headers'] : []);

	if(x($opts,'session')) {
		if(strpos($url,z_root()) === 0) {
			$instance_headers[] = 'Cookie: PHPSESSID=' . session_id();
		}
	}
	if($instance_headers)
		@curl_setopt($ch, CURLOPT_HTTPHEADER, $instance_headers);

93

94 95 96
	if(x($opts,'nobody'))
		@curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);

97 98 99
	if(x($opts,'custom'))
		@curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $opts['custom']);

100
	if(x($opts,'timeout') && intval($opts['timeout'])) {
Zot's avatar
Zot committed
101
		@curl_setopt($ch, CURLOPT_TIMEOUT, intval($opts['timeout']));
102 103
	}
	else {
Zot's avatar
Zot committed
104
		$curl_time = intval(@get_config('system','curl_timeout'));
105 106 107
		@curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
	}

108

109 110 111 112
	if(x($opts,'http_auth')) {
		// "username" . ':' . "password"
		@curl_setopt($ch, CURLOPT_USERPWD, $opts['http_auth']);
	}
113

114 115 116 117 118
	if(x($opts,'cookiejar'))
		@curl_setopt($ch, CURLOPT_COOKIEJAR, $opts['cookiejar']);
	if(x($opts,'cookiefile'))
		@curl_setopt($ch, CURLOPT_COOKIEFILE, $opts['cookiefile']);

119 120 121
	if(x($opts,'cookie'))
		@curl_setopt($ch, CURLOPT_COOKIE, $opts['cookie']);

122
	@curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,
friendica's avatar
friendica committed
123 124
		((x($opts,'novalidate') && intval($opts['novalidate'])) ? false : true));

Zot's avatar
Zot committed
125
	$prx = @get_config('system','proxy');
126 127 128 129 130 131 132 133 134 135 136
	if(strlen($prx)) {
		@curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
		@curl_setopt($ch, CURLOPT_PROXY, $prx);
		$prxusr = @get_config('system','proxyuser');
		if(strlen($prxusr))
			@curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
	}
	if($binary)
		@curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);


137
	// don't let curl abort the entire application'
138 139 140 141 142 143 144
	// if it throws any errors.

	$s = @curl_exec($ch);

	$base = $s;
	$curl_info = @curl_getinfo($ch);
	$http_code = $curl_info['http_code'];
145
	//logger('fetch_url:' . $http_code . ' data: ' . $s);
146 147 148 149 150 151 152 153 154 155 156
	$header = '';

	// Pull out multiple headers, e.g. proxy and continuation headers
	// allow for HTTP/2.x without fixing code

	while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
		$chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
		$header .= $chunk;
		$base = substr($base,strlen($chunk));
	}

157
	if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307 || $http_code == 308) {
158 159 160 161 162 163 164 165
		$matches = array();
		preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
		$newurl = trim(array_pop($matches));
		if(strpos($newurl,'/') === 0)
			$newurl = $url . $newurl;
		$url_parsed = @parse_url($newurl);
		if (isset($url_parsed)) {
			@curl_close($ch);
166
			return z_fetch_url($newurl,$binary,++$redirects,$opts);
167 168 169 170 171 172
		}
	}

	$rc = intval($http_code);
	$ret['return_code'] = $rc;
	$ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
173
	if(! $ret['success']) {
174
		$ret['error'] = curl_error($ch);
175
		$ret['debug'] = $curl_info;
176 177
		logger('z_fetch_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
		logger('z_fetch_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
178
	}
179 180
	$ret['body'] = substr($s,strlen($header));
	$ret['header'] = $header;
181 182 183 184

	if(x($opts,'debug')) {
		$ret['debug'] = $curl_info;
	}
185

186 187
	@curl_close($ch);
	return($ret);
friendica's avatar
friendica committed
188 189
}

190

191
/**
192 193
 * @brief
 *
194
 * @param string $url
friendica's avatar
friendica committed
195
 *    URL to post
196
 * @param mixed $params
197 198 199 200
 *   The full data to post in a HTTP "POST" operation. This parameter can
 *   either be passed as a urlencoded string like 'para1=val1&para2=val2&...'
 *   or as an array with the field name as key and field data as value. If value
 *   is an array, the Content-Type header will be set to multipart/form-data.
201 202 203 204 205 206
 * @param int $redirects = 0
 *    internal use, recursion counter
 * @param array $opts (optional parameters)
 *    'timeout' => int seconds, default system config value or 60 seconds
 *    'http_auth' => username:password
 *    'novalidate' => do not validate SSL certs, default is to validate using our CA list
207
 *    'filep' => stream resource to write body to. header and body are not returned when using this option.
208 209 210
 *    'custom' => custom request method: e.g. 'PUT', 'DELETE'
 *
 * @return array an associative array with:
211 212 213 214 215
 *  * \e int \b return_code => HTTP return code or 0 if timeout or failure
 *  * \e boolean \b success => boolean true (if HTTP 2xx result) or false
 *  * \e string \b header => HTTP headers
 *  * \e string \b body => content
 *  * \e string \b debug => from curl_info()
216
 */
217
function z_post_url($url,$params, $redirects = 0, $opts = array()) {
218

219 220 221 222
//	logger('url: ' . $url);
//	logger('params: ' . print_r($params,true));
//	logger('opts: ' . print_r($opts,true));

223 224 225
	$ret = array('return_code' => 0, 'success' => false, 'header' => "", 'body' => "");

	$ch = curl_init($url);
226
	if(($redirects > 8) || (! $ch))
227
		return $ret;
228

229
	@curl_setopt($ch, CURLOPT_HEADER, true);
230
	@curl_setopt($ch, CURLINFO_HEADER_OUT, true);
231
	@curl_setopt($ch, CURLOPT_CAINFO, get_capath());
232 233 234
	@curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
	@curl_setopt($ch, CURLOPT_POST,1);
	@curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
Zot's avatar
Zot committed
235
	@curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; zot)");
236 237

	$ciphers = @get_config('system','curl_ssl_ciphers');
238 239
	if($ciphers)
		@curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, $ciphers);
240

241 242
	if(x($opts,'filep')) {
		@curl_setopt($ch, CURLOPT_FILE, $opts['filep']);
Zot's avatar
Zot committed
243
		@curl_setopt($ch, CURLOPT_HEADER, false);
244 245
	}

246 247 248 249 250 251
	$instance_headers = ((array_key_exists('headers',$opts) && is_array($opts['headers'])) ? $opts['headers'] : []);

	if(x($opts,'session')) {
		if(strpos($url,z_root()) === 0) {
			$instance_headers[] = 'Cookie: PHPSESSID=' . session_id();
		}
252
	}
253 254 255
	if($instance_headers)
		@curl_setopt($ch, CURLOPT_HTTPHEADER, $instance_headers);

256

257 258 259
	if(x($opts,'nobody'))
		@curl_setopt($ch, CURLOPT_NOBODY, $opts['nobody']);

260
	if(x($opts,'custom')) {
261
		@curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $opts['custom']);
262 263
		@curl_setopt($ch, CURLOPT_POST,0);
	}
264 265


266 267
	if(x($opts,'timeout') && intval($opts['timeout'])) {
		@curl_setopt($ch, CURLOPT_TIMEOUT, $opts['timeout']);
268 269
	}
	else {
Zot's avatar
Zot committed
270
		$curl_time = intval(@get_config('system','curl_timeout'));
271
		@curl_setopt($ch, CURLOPT_TIMEOUT, (($curl_time !== false) ? $curl_time : 60));
272 273
	}

274 275 276
	if(x($opts,'http_auth')) {
		// "username" . ':' . "password"
		@curl_setopt($ch, CURLOPT_USERPWD, $opts['http_auth']);
277
	}
278

279 280 281 282 283 284

	if(x($opts,'cookiejar'))
		@curl_setopt($ch, CURLOPT_COOKIEJAR, $opts['cookiejar']);
	if(x($opts,'cookiefile'))
		@curl_setopt($ch, CURLOPT_COOKIEFILE, $opts['cookiefile']);

285 286 287 288

	if(x($opts,'cookie'))
		@curl_setopt($ch, CURLOPT_COOKIE, $opts['cookie']);

289
	@curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,
290
		((x($opts,'novalidate') && intval($opts['novalidate'])) ? false : true));
291

292 293
	$prx = get_config('system','proxy');
	if(strlen($prx)) {
294 295
		@curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
		@curl_setopt($ch, CURLOPT_PROXY, $prx);
296 297
		$prxusr = get_config('system','proxyuser');
		if(strlen($prxusr))
298
			@curl_setopt($ch, CURLOPT_PROXYUSERPWD, $prxusr);
299 300 301 302 303 304 305 306
	}

	// don't let curl abort the entire application
	// if it throws any errors.

	$s = @curl_exec($ch);

	$base = $s;
307
	$curl_info = @curl_getinfo($ch);
308 309 310 311 312 313 314 315 316 317 318 319 320
	$http_code = $curl_info['http_code'];

	$header = '';

	// Pull out multiple headers, e.g. proxy and continuation headers
	// allow for HTTP/2.x without fixing code

	while(preg_match('/^HTTP\/[1-2].+? [1-5][0-9][0-9]/',$base)) {
		$chunk = substr($base,0,strpos($base,"\r\n\r\n")+4);
		$header .= $chunk;
		$base = substr($base,strlen($chunk));
	}

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
	// would somebody take lighttpd and just shoot it?

	if($http_code == 417) {
		curl_close($ch);
		if($opts) {
			if($opts['headers'])
				$opts['headers'][] = 'Expect:';
			else
				$opts['headers'] = array('Expect:');
		}
		else
			$opts = array('headers' => array('Expect:'));
		return z_post_url($url,$params,++$redirects,$opts);
	}

336
	if($http_code == 301 || $http_code == 302 || $http_code == 303 || $http_code == 307 || $http_code == 308) {
Olaf Conradi's avatar
Olaf Conradi committed
337 338 339
		$matches = array();
		preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
		$newurl = trim(array_pop($matches));
340 341
		if(strpos($newurl,'/') === 0)
			$newurl = $url . $newurl;
Olaf Conradi's avatar
Olaf Conradi committed
342 343
		$url_parsed = @parse_url($newurl);
		if (isset($url_parsed)) {
344
			curl_close($ch);
345
			if($http_code == 303) {
346
				return z_fetch_url($newurl,false,$redirects++,$opts);
347
			} else {
348
				return z_post_url($newurl,$params,++$redirects,$opts);
349
			}
Olaf Conradi's avatar
Olaf Conradi committed
350 351
		}
	}
352 353 354
	$rc = intval($http_code);
	$ret['return_code'] = $rc;
	$ret['success'] = (($rc >= 200 && $rc <= 299) ? true : false);
355
	if(! $ret['success']) {
356
		$ret['error'] = curl_error($ch);
357
		$ret['debug'] = $curl_info;
358 359
		logger('z_post_url: error: ' . $url . ': ' . $ret['error'], LOGGER_DEBUG);
		logger('z_post_url: debug: ' . print_r($curl_info,true), LOGGER_DATA);
360 361
	}

362
	$ret['body'] = substr($s, strlen($header));
363
	$ret['header'] = $header;
364 365 366 367 368

	if(x($opts,'debug')) {
		$ret['debug'] = $curl_info;
	}

369 370
	curl_close($ch);
	return($ret);
friendica's avatar
friendica committed
371
}
372

373 374 375 376 377 378 379 380 381 382 383 384 385 386
/**
 * @brief Like z_post_url() but with an application/json HTTP header.
 *
 * Add a "Content-Type: application/json" HTTP-header to $opts and call z_post_url().
 *
 * @see z_post_url()
 *
 * @param string $url
 * @param array $params
 * @param number $redirects default 0
 * @param array $opts (optional) curl options
 * @return z_post_url()
 */
function z_post_url_json($url, $params, $redirects = 0, $opts = array()) {
387

388
	$opts = array_merge($opts, array('headers' => array('Content-Type: application/json')));
389 390 391 392

	return z_post_url($url,json_encode($params),$redirects,$opts);
}

393

394 395
function json_return_and_die($x, $content_type = 'application/json') {
	header("Content-type: $content_type");
friendica's avatar
friendica committed
396 397 398 399 400
	echo json_encode($x);
	killme();
}


401 402 403 404 405 406 407 408 409 410
/**
 * @brief Generic XML return.
 *
 * Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
 * of $st and an optional text <message> of $message and terminates the current
 * process.
 *
 * @param string $st
 * @param string $message
 */
411 412 413 414 415
function xml_status($st, $message = '') {

	$xml_message = ((strlen($message)) ? "\t<message>" . xmlify($message) . "</message>\r\n" : '');

	if($st)
416
		logger('Returning non_zero: ' . $st . " message=" . $message);
417 418 419 420 421

	header( "Content-type: text/xml" );
	echo '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
	echo "<result>\r\n\t<status>$st</status>\r\n$xml_message</result>\r\n";
	killme();
friendica's avatar
friendica committed
422 423
}

424

425
/**
426
 * @brief Send HTTP status header.
427
 *
428 429
 * @param int $val
 *    integer HTTP status result value
430 431
 * @param string $msg
 *    optional message
432
 */
433
function http_status($val, $msg = '') {
434
	if ($val >= 400)
435
		$msg = (($msg) ? $msg : 'Error');
436
	if ($val >= 200 && $val < 300)
437
		$msg = (($msg) ? $msg : 'OK');
Friendika's avatar
Friendika committed
438

439
	logger('' . $val . ' ' . $msg);
440
	header($_SERVER['SERVER_PROTOCOL'] . ' ' . $val . ' ' . $msg);
441 442 443 444 445 446 447 448 449 450
}


/**
 * @brief Send HTTP status header and exit.
 *
 * @param int $val
 *    integer HTTP status result value
 * @param string $msg
 *    optional message
451
 * @return does not return, process is terminated
452 453 454
 */
function http_status_exit($val, $msg = '') {
	http_status($val, $msg);
Friendika's avatar
Friendika committed
455
	killme();
friendica's avatar
friendica committed
456
}
Friendika's avatar
Friendika committed
457

458 459 460 461 462 463 464
/**
 * @brief convert an XML document to a normalised, case-corrected array used by webfinger.
 *
 * @param string|array|SimpleXMLElement $xml_element
 * @param int $recursion_depth[in,out]
 * @return NULL|string|array
 */
465 466
function convert_xml_element_to_array($xml_element, &$recursion_depth=0) {

467 468 469 470
	// If we're getting too deep, bail out
	if ($recursion_depth > 512) {
		return(null);
	}
471

472 473 474 475 476 477
	if (!is_string($xml_element) &&
			!is_array($xml_element) &&
			(get_class($xml_element) == 'SimpleXMLElement')) {
		$xml_element_copy = $xml_element;
		$xml_element = get_object_vars($xml_element);
	}
478

479 480 481 482 483
	if (is_array($xml_element)) {
		$result_array = array();
		if (count($xml_element) <= 0) {
			return (trim(strval($xml_element_copy)));
		}
484

485 486 487
		foreach($xml_element as $key=>$value) {
			$recursion_depth++;
			$result_array[strtolower($key)] =
488
				convert_xml_element_to_array($value, $recursion_depth);
489
			$recursion_depth--;
490
		}
491 492 493 494 495 496 497 498 499 500 501
		if ($recursion_depth == 0) {
			$temp_array = $result_array;
			$result_array = array(
				strtolower($xml_element_copy->getName()) => $temp_array,
			);
		}

		return ($result_array);
	} else {
		return (trim(strval($xml_element)));
	}
friendica's avatar
friendica committed
502
}
503

504 505 506 507 508 509


function z_dns_check($h,$check_mx = 0) {

	// dns_get_record() has issues on some platforms
	// so allow somebody to ignore it completely
510 511
	// Use config values from memory as this can be called during setup
	// before a database or even any config structure exists.
512

513 514
	if(is_array(\App::$config) && array_key_exists('system',\App::$config)
		&& is_array(\App::$config['system'])
515
		&& array_key_exists('do_not_check_dns',\App::$config['system'])
516
		&& \App::$config['system']['do_not_check_dns'])
517 518
		return true;

519 520 521 522

	//$opts = DNS_A + DNS_CNAME + DNS_PTR;
	//if($check_mx)
	//	$opts += DNS_MX;
523 524
	// Specific record type flags are unreliable on FreeBSD and Mac,
	// so now we'll ignore these and just check for the existence of any DNS record.
525
	return((@dns_get_record($h) || filter_var($h, FILTER_VALIDATE_IP)) ? true : false);
526 527
}

528 529 530 531 532 533 534 535 536 537 538
/**
 * @brief Validates a given URL
 *
 * Take a URL from the wild, prepend http:// if necessary and check DNS to see
 * if it's real (or check if is a valid IP address).
 *
 * @see z_dns_check()
 *
 * @param string $url[in,out] URL to check
 * @return boolean Return true if it's OK, false if something is wrong with it
 */
539
function validate_url(&$url) {
540

541
	// no naked subdomains (allow localhost for tests)
542
	if(strpos($url, '.') === false && strpos($url, '/localhost/') === false)
friendica's avatar
friendica committed
543
		return false;
544 545

	if(substr($url, 0, 4) != 'http')
546
		$url = 'http://' . $url;
547

548
	$h = @parse_url($url);
549

550
	if(($h) && z_dns_check($h['host'])) {
551 552
		return true;
	}
553

554
	return false;
friendica's avatar
friendica committed
555
}
556

557 558 559 560 561 562
/**
 * @brief Checks that email is an actual resolvable internet address.
 *
 * @param string $addr
 * @return boolean
 */
563 564
function validate_email($addr) {

565
	if(get_config('system', 'disable_email_validation'))
566 567
		return true;

568
	if(! strpos($addr, '@'))
569 570
		return false;

571 572 573
	$h = substr($addr, strpos($addr, '@') + 1);

	if(($h) && z_dns_check($h, true)) {
574 575
		return true;
	}
576

577
	return false;
friendica's avatar
friendica committed
578
}
579

580 581 582 583 584 585 586 587
/**
 * @brief Check $url against our list of allowed sites.
 *
 * Wildcards allowed. If allowed_sites is unset return true.
 *
 * @param string $url
 * @return boolean Return true if url is allowed, otherwise return false
 */
588 589 590 591 592 593 594 595
function allowed_url($url) {

	$h = @parse_url($url);

	if(! $h) {
		return false;
	}

596
	$str_allowed = get_config('system', 'allowed_sites');
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
	if(! $str_allowed)
		return true;

	$found = false;

	$host = strtolower($h['host']);

	// always allow our own site

	if($host == strtolower($_SERVER['SERVER_NAME']))
		return true;

	$fnmatch = function_exists('fnmatch');
	$allowed = explode(',',$str_allowed);

	if(count($allowed)) {
		foreach($allowed as $a) {
			$pat = strtolower(trim($a));
			if(($fnmatch && fnmatch($pat,$host)) || ($pat == $host)) {
616
				$found = true;
617 618 619 620 621
				break;
			}
		}
	}
	return $found;
friendica's avatar
friendica committed
622
}
623

624 625 626 627 628 629 630 631 632
/**
 * @brief Check if email address is allowed to register here.
 *
 * Compare against our list (wildcards allowed).
 *
 * @param string $email
 * @return boolean Returns false if not allowed, true if allowed or if allowed list is
 * not configured.
 */
633 634
function allowed_email($email) {

635
	$domain = strtolower(substr($email, strpos($email, '@') + 1));
636 637 638
	if(! $domain)
		return false;

639 640
	$str_allowed = get_config('system', 'allowed_email');
	$str_not_allowed = get_config('system', 'not_allowed_email');
641

642
	if(! $str_allowed && ! $str_not_allowed)
643 644
		return true;

645
	$return = false;
646
	$found_allowed = false;
647
	$found_not_allowed = false;
648

649
	$fnmatch = function_exists('fnmatch');
650

651
	$allowed = explode(',', $str_allowed);
652 653 654 655

	if(count($allowed)) {
		foreach($allowed as $a) {
			$pat = strtolower(trim($a));
656
			if(($fnmatch && fnmatch($pat,$email)) || ($pat == $domain)) {
657
				$found_allowed = true;
658 659 660 661
				break;
			}
		}
	}
662

663
	$not_allowed = explode(',', $str_not_allowed);
664 665 666 667 668

	if(count($not_allowed)) {
		foreach($not_allowed as $na) {
			$pat = strtolower(trim($na));
			if(($fnmatch && fnmatch($pat,$email)) || ($pat == $domain)) {
669
				$found_not_allowed = true;
670 671 672
				break;
			}
		}
673 674
	}

675
	if ($found_allowed) {
676
		$return = true;
677
	} elseif (!$str_allowed && !$found_not_allowed) {
678
		$return = true;
679
	}
680

681
	return $return;
friendica's avatar
friendica committed
682 683
}

684 685 686 687 688 689


function parse_xml_string($s,$strict = true) {
	if($strict) {
		if(! strstr($s,'<?xml'))
			return false;
690

691 692 693 694
		$s2 = substr($s,strpos($s,'<?xml'));
	}
	else
		$s2 = $s;
695

696 697 698 699 700 701 702
	libxml_use_internal_errors(true);

	$x = @simplexml_load_string($s2);
	if(! $x) {
		logger('libxml: parse: error: ' . $s2, LOGGER_DATA);
		foreach(libxml_get_errors() as $err)
			logger('libxml: parse: ' . $err->code." at ".$err->line.":".$err->column." : ".$err->message, LOGGER_DATA);
703

704 705
		libxml_clear_errors();
	}
706

707
	return $x;
friendica's avatar
friendica committed
708
}
709

friendica's avatar
friendica committed
710

711
function scale_external_images($s, $include_link = true, $scale_replace = false) {
friendica's avatar
friendica committed
712

713
	// Picture addresses can contain special characters
714
	$s = htmlspecialchars_decode($s, ENT_COMPAT);
715

friendica's avatar
friendica committed
716
	$matches = null;
717
	$c = preg_match_all('/\[([zi])mg(.*?)\](.*?)\[\/[zi]mg\]/ism',$s,$matches,PREG_SET_ORDER);
friendica's avatar
friendica committed
718
	if($c) {
friendica's avatar
friendica committed
719 720
		require_once('include/photo/photo_driver.php');

friendica's avatar
friendica committed
721
		foreach($matches as $mtch) {
722
			logger('data: ' . $mtch[2] . ' ' . $mtch[3]);
723

724
			if(substr($mtch[1],0,1) == '=') {
725
				$owidth = intval(substr($mtch[2],1));
726
				if(intval($owidth) > 0 && intval($owidth) < 1024)
727 728
					continue;
			}
729

redmatrix's avatar
redmatrix committed
730
			$hostname = str_replace('www.','',substr(z_root(),strpos(z_root(),'://')+3));
731
			if(stristr($mtch[3],$hostname))
friendica's avatar
friendica committed
732
				continue;
733 734 735 736 737 738 739

			// $scale_replace, if passed, is an array of two elements. The
			// first is the name of the full-size image. The second is the
			// name of a remote, scaled-down version of the full size image.
			// This allows Friendica to display the smaller remote image if
			// one exists, while still linking to the full-size image
			if($scale_replace)
740
				$scaled = str_replace($scale_replace[0], $scale_replace[1], $mtch[3]);
741
			else
742
				$scaled = $mtch[3];
743
			$i = z_fetch_url($scaled,true);
744

745

friendica's avatar
friendica committed
746 747 748
			$cache = get_config('system','itemcache');
			if (($cache != '') and is_dir($cache)) {
				$cachefile = $cache."/".hash("md5", $scaled);
749
				file_put_contents($cachefile, $i['body']);
friendica's avatar
friendica committed
750 751
			}

752
			// guess mimetype from headers or filename
753

754
			$type = guess_image_type($mtch[3],$i['header']);
755 756
			if(strpos($type,'image') === false)
				continue;
757

758 759
			if($i['success']) {
				$ph = photo_factory($i['body'], $type);
760 761 762 763

				if(! is_object($ph))
					continue;

friendica's avatar
friendica committed
764 765 766 767
				if($ph->is_valid()) {
					$orig_width = $ph->getWidth();
					$orig_height = $ph->getHeight();

768
					if($orig_width > 1024 || $orig_height > 1024) {
769
						$tag = (($match[1] == 'z') ? 'zmg' : 'img');
770
						$ph->scaleImage(1024);
friendica's avatar
friendica committed
771 772
						$new_width = $ph->getWidth();
						$new_height = $ph->getHeight();
773
						logger('data: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG);
774
						$s = str_replace($mtch[0],'[' . $tag . '=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/' . $tag . ']'
775
							. "\n" . (($include_link)
776
								? '[zrl=' . $mtch[2] . ']' . t('view full size') . '[/zrl]' . "\n"
friendica's avatar
friendica committed
777
								: ''),$s);
778
						logger('new string: ' . $s, LOGGER_DEBUG);
friendica's avatar
friendica committed
779 780 781 782 783
					}
				}
			}
		}
	}
friendica's avatar
friendica committed
784 785 786

	// replace the special char encoding

787
	$s = htmlspecialchars($s,ENT_COMPAT,'UTF-8');
friendica's avatar
friendica committed
788

friendica's avatar
friendica committed
789 790
	return $s;
}
791

792
/**
793 794
 * @brief xml2array() will convert the given XML text to an array in the XML structure.
 *
795
 * Link: http://www.bin-co.com/php/scripts/xml2array/
796 797 798
 * Portions significantly re-written by mike@macgirvin.com for Friendica
 * (namespaces, lowercase tags, get_attribute default changed, more...)
 *
799
 * Examples: $array =  xml2array(file_get_contents('feed.xml'));
800 801 802 803 804 805 806 807
 *           $array =  xml2array(file_get_contents('feed.xml', true, 1, 'attribute'));
 *
 * @param string $contents The XML text
 * @param boolean $namespaces true or false include namespace information in the returned array as array elements
 * @param int $get_attributes 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value.
 * @param string $priority Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
 *
 * @return array The parsed XML in an array form. Use print_r() to see the resulting array structure.
808
 */
809
function xml2array($contents, $namespaces = true, $get_attributes=1, $priority = 'attribute') {
810 811
	if(!$contents)
		return array();
812

813 814 815 816
	if(!function_exists('xml_parser_create')) {
		logger('xml2array: parser function missing');
		return array();
	}
817 818 819 820 821

	libxml_use_internal_errors(true);
	libxml_clear_errors();

	if($namespaces)
822
		$parser = @xml_parser_create_ns("UTF-8",':');
823
	else
824
		$parser = @xml_parser_create();
825 826 827 828 829 830

	if(! $parser) {
		logger('xml2array: xml_parser_create: no resource');
		return array();
	}

831
	xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
832
	// http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
833 834 835 836
	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
	xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
	@xml_parse_into_struct($parser, trim($contents), $xml_values);
	@xml_parser_free($parser);
837

838
	if(! $xml_values) {
839 840 841 842
		logger('xml2array: libxml: parse error: ' . $contents, LOGGER_DATA);
		foreach(libxml_get_errors() as $err)
			logger('libxml: parse: ' . $err->code . " at " . $err->line . ":" . $err->column . " : " . $err->message, LOGGER_DATA);
		libxml_clear_errors();
843

844 845 846
		return;
	}

847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
	//Initializations
	$xml_array = array();
	$parents = array();
	$opened_tags = array();
	$arr = array();

	$current = &$xml_array; // Reference

	// Go through the tags.
	$repeated_tag_index = array(); // Multiple tags with same name will be turned into an array
	foreach($xml_values as $data) {
		unset($attributes,$value); // Remove existing values, or there will be trouble

		// This command will extract these variables into the foreach scope
		// tag(string), type(string), level(int), attributes(array).
		extract($data); // We could use the array by itself, but this cooler.

		$result = array();
		$attributes_data = array();
866

867 868 869 870 871 872 873 874 875 876 877 878 879 880
		if(isset($value)) {
			if($priority == 'tag') $result = $value;
			else $result['value'] = $value; // Put the value in a assoc array if we are in the 'Attribute' mode
		}

		//Set the attributes too.
		if(isset($attributes) and $get_attributes) {
			foreach($attributes as $attr => $val) {
				if($priority == 'tag') $attributes_data[$attr] = $val;
				else $result['@attributes'][$attr] = $val; // Set all the attributes in a array called 'attr'
			}
		}

		// See tag status and do the needed.
881
		if($namespaces && strpos($tag,':')) {
882
			$namespc = substr($tag,0,strrpos($tag,':'));
883 884 885 886 887 888
			$tag = strtolower(substr($tag,strlen($namespc)+1));
			$result['@namespace'] = $namespc;
		}
		$tag = strtolower($tag);

		if($type == "open") {   // The starting of the tag '<tag>'
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904
			$parent[$level-1] = &$current;
			if(!is_array($current) or (!in_array($tag, array_keys($current)))) { // Insert New tag
				$current[$tag] = $result;
				if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
				$repeated_tag_index[$tag.'_'.$level] = 1;

				$current = &$current[$tag];

			} else { // There was another element with the same tag name

				if(isset($current[$tag][0])) { // If there is a 0th element it is already an array
					$current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
					$repeated_tag_index[$tag.'_'.$level]++;
				} else { // This section will make the value an array if multiple tags with the same name appear together
					$current[$tag] = array($current[$tag],$result); // This will combine the existing item and the new item together to make an array
					$repeated_tag_index[$tag.'_'.$level] = 2;
905

906 907 908 909 910 911 912 913 914 915 916 917 918 919
					if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
						$current[$tag]['0_attr'] = $current[$tag.'_attr'];
						unset($current[$tag.'_attr']);
					}
				}
				$last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
				$current = &$current[$tag][$last_item_index];
			}

		} elseif($type == "complete") { // Tags that ends in 1 line '<tag />'
			//See if the key is already taken.
			if(!isset($current[$tag])) { //New Key
				$current[$tag] = $result;
				$repeated_tag_index[$tag.'_'.$level] = 1;
920 921
				if($priority == 'tag' and $attributes_data)
					$current[$tag. '_attr'] = $attributes_data;
922 923 924 925 926 927

			} else { // If taken, put all things inside a list(array)
				if(isset($current[$tag][0]) and is_array($current[$tag])) { // If it is already an array...

					// ...push the new element into that array.
					$current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
928

929 930 931 932 933 934 935 936 937 938 939 940
					if($priority == 'tag' and $get_attributes and $attributes_data) {
						$current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
					}
					$repeated_tag_index[$tag.'_'.$level]++;
				} else { // If it is not an array...
					$current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
					$repeated_tag_index[$tag.'_'.$level] = 1;
					if($priority == 'tag' and $get_attributes) {
						if(isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well
							$current[$tag]['0_attr'] = $current[$tag.'_attr'];
							unset($current[$tag.'_attr']);
						}
941

942 943 944 945 946 947 948 949 950 951 952 953
						if($attributes_data) {
							$current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
						}
					}
					$repeated_tag_index[$tag.'_'.$level]++; // 0 and 1 indexes are already taken
				}
			}

		} elseif($type == 'close') { // End of tag '</tag>'
			$current = &$parent[$level-1];
		}
	}
954

955
	return($xml_array);
956
}
957

friendica's avatar
friendica committed
958

959
function email_header_encode($in_str, $charset = 'UTF-8') {
960
	$out_str = $in_str;
friendica's avatar
friendica committed
961 962 963 964 965 966 967 968 969 970 971
	$need_to_convert = false;

	for($x = 0; $x < strlen($in_str); $x ++) {
		if((ord($in_str[$x]) == 0) || ((ord($in_str[$x]) > 128))) {
			$need_to_convert = true;
		}
	}

	if(! $need_to_convert)
		return $in_str;

972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
	if ($out_str && $charset) {

		// define start delimimter, end delimiter and spacer
		$end = "?=";
		$start = "=?" . $charset . "?B?";
		$spacer = $end . "\r\n " . $start;

		// determine length of encoded text within chunks
		// and ensure length is even
		$length = 75 - strlen($start) - strlen($end);

		/*
			[EDIT BY danbrown AT php DOT net: The following
			is a bugfix provided by (gardan AT gmx DOT de)
			on 31-MAR-2005 with the following note:
			"This means: $length should not be even,
			but divisible by 4. The reason is that in
			base64-encoding 3 8-bit-chars are represented
			by 4 6-bit-chars. These 4 chars must not be
			split between two encoded words, according
			to RFC-2047.
		*/
		$length = $length - ($length % 4);

		// encode the string and split it into chunks
		// with spacers after each chunk
		$out_str = base64_encode($out_str);
		$out_str = chunk_split($out_str, $length, $spacer);

		// remove trailing spacer and
		// add start and end delimiters
		$spacer = preg_quote($spacer,'/');
		$out_str = preg_replace("/" . $spacer . "$/", "", $out_str);
		$out_str = $start . $out_str . $end;
	}
	return $out_str;
friendica's avatar
friendica committed
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
}

function email_send($addr, $subject, $headers, $item) {
	//$headers .= 'MIME-Version: 1.0' . "\n";
	//$headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
	//$headers .= 'Content-Type: text/plain; charset=UTF-8' . "\n";
	//$headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";

	$part = uniqid("", true);

1018
	$html	= prepare_body($item);
friendica's avatar
friendica committed
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041

	$headers .= "Mime-Version: 1.0\n";
	$headers .= 'Content-Type: multipart/alternative; boundary="=_'.$part.'"'."\n\n";

	$body = "\n--=_".$part."\n";
	$body .= "Content-Transfer-Encoding: 8bit\n";
	$body .= "Content-Type: text/plain; charset=utf-8; format=flowed\n\n";

	$body .= html2plain($html)."\n";

	$body .= "--=_".$part."\n";
	$body .= "Content-Transfer-Encoding: 8bit\n";
	$body .= "Content-Type: text/html; charset=utf-8\n\n";

	$body .= '<html><head></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space; ">'.$html."</body></html>\n";

	$body .= "--=_".$part."--";

	//$message = '<html><body>' . $html . '</body></html>';
	//$message = html2plain($html);
	logger('notifier: email delivery to ' . $addr);
	mail($addr, $subject, $body, $headers);
}
1042

1043 1044 1045 1046 1047 1048 1049 1050 1051
/**
 * @brief Creates an xchan entry for URL.
 *
 * @param string $url URL to discover
 * @param array $arr fallback values if scrape_feed() is empty
 *
 * @return boolean
 */
function discover_by_url($url, $arr = null) {
friendica's avatar
friendica committed
1052 1053 1054 1055 1056 1057
	require_once('library/HTML5/Parser.php');

	$x = scrape_feed($url);
	if(! $x) {
		if(! $arr)
			return false;
1058

friendica's avatar
friendica committed
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
		$network = (($arr['network']) ? $arr['network'] : 'unknown');
		$name = (($arr['name']) ? $arr['name'] : 'unknown');
		$photo = (($arr['photo']) ? $arr['photo'] : '');
		$addr = (($arr['addr']) ? $arr['addr'] : '');
		$guid = $url;
	}

	$profile = $url;

	logger('scrape_feed results: ' . print_r($x,true));

	if($x['feed_atom'])
		$guid = $x['feed_atom'];
	if($x['feed_rss'])
		$guid = $x['feed_rss'];

	if(! $guid)
		return false;


	// try and discover stuff from the feeed

	$feed = new SimplePie();
	$level = 0;
1083
	$x = z_fetch_url($guid, false, $level, array('novalidate' => true));
friendica's avatar
friendica committed
1084
	if(! $x['success']) {
1085
		logger('Feed fetch failed for ' . $guid);
friendica's avatar
friendica committed
1086 1087 1088
		return false;
	}
	$xml = $x['body'];
1089 1090
	logger('Fetch feed: ' . $guid . ' returns: ' . $xml, LOGGER_DATA);
	logger('scrape_feed: headers: ' . $x['header'], LOGGER_DATA);
friendica's avatar
friendica committed
1091 1092 1093 1094

	// Don't try and parse an empty string
	$feed->set_raw_data(($xml) ? $xml : '<?xml version="1.0" encoding="utf-8" ?><xml></xml>');

1095 1096 1097 1098 1099 1100
	// We can preserve iframes because we will strip them in the purifier after
	// checking for supported video sources.
	$strip_htmltags = $feed->strip_htmltags;
	array_splice($strip_htmltags, array_search('iframe', $strip_htmltags), 1);
	$feed->strip_htmltags($strip_htmltags);

friendica's avatar
friendica committed
1101 1102
	$feed->init();
	if($feed->error())
1103
		logger('scrape_feed: Error parsing XML: ' . $feed->error());
friendica's avatar
friendica committed
1104

1105
	$name = unxmlify(trim($feed->get_title()));
friendica's avatar
friendica committed
1106 1107 1108 1109 1110
	$photo = $feed->get_image_url();
	$author = $feed->get_author();

	if($author) {
		if(! $name)
1111 1112
			$name = unxmlify(trim($author->get_name()));
		if(! $name) {
friendica's avatar
friendica committed
1113
			$name = trim(unxmlify($author->get_email()));
1114 1115 1116
			if(strpos($name,'@') !== false)
				$name = substr($name,0,strpos($name,'@'));
		}
friendica's avatar
friendica committed
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
		if(! $profile && $author->get_link())
			$profile = trim(unxmlify($author->get_link()));
		if(! $photo) {
			$rawtags = $feed->get_feed_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
			if($rawtags) {
				$elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
				if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo'))
					$photo = $elems['link'][0]['attribs']['']['href'];
			}
		}
	}
	else {
		$item = $feed->get_item(0);
		if($item) {
			$author = $item->get_author();
			if($author) {
friendica's avatar
friendica committed
1133 1134 1135 1136 1137 1138 1139
				if(! $name) {
					$name = trim(unxmlify($author->get_name()));
					if(! $name)
						$name = trim(unxmlify($author->get_email()));
					if(strpos($name,'@') !== false)
						$name = substr($name,0,strpos($name,'@'));
				}
friendica's avatar
friendica committed
1140 1141 1142 1143
				if(! $profile && $author->get_link())
					$profile = trim(unxmlify($author->get_link()));
			}
			if(! $photo) {
1144
				$rawmedia = $item->get_item_tags('http://search.yahoo.com/mrss/', 'thumbnail');
friendica's avatar
friendica committed
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
				if($rawmedia && $rawmedia[0]['attribs']['']['url'])
					$photo = unxmlify($rawmedia[0]['attribs']['']['url']);
			}
			if(! $photo) {
				$rawtags = $item->get_item_tags( SIMPLEPIE_NAMESPACE_ATOM_10, 'author');
				if($rawtags) {
					$elems = $rawtags[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_10];
					if((x($elems,'link')) && ($elems['link'][0]['attribs']['']['rel'] === 'photo'))
						$photo = $elems['link'][0]['attribs']['']['href'];
				}
			}
		}
	}
1158
	if($guid === $profile)
friendica's avatar
friendica committed
1159 1160 1161 1162 1163 1164 1165
		$lnk = $feed->get_permalink();
	if(isset($lnk) && strlen($lnk))
		$profile = $lnk;

	if(! $network) {
		$network = 'rss';
	}
1166

friendica's avatar
friendica committed
1167 1168 1169 1170 1171 1172 1173 1174 1175
	if(! $name)
		$name = notags($feed->get_description());

	$r = q("select * from xchan where xchan_hash = '%s' limit 1",
		dbesc($guid)
	);
	if($r)
		return true;

1176 1177 1178
	if(! $photo)
		$photo = z_root() . '/images/rss_icon.png';

1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
	$r = xchan_store_lowlevel(
		[
			'xchan_hash'         => $guid,
			'xchan_guid'         => $guid,
			'xchan_addr'         => $addr,
			'xchan_url'          => $profile,
			'xchan_name'         => $name,
			'xchan_name_date'    => datetime_convert(),
			'xchan_network'      => $network
		]
friendica's avatar
friendica committed
1189 1190
	);

1191
	$photos = import_xchan_photo($photo,$guid);
1192
	$r = q("update xchan set xchan_photo_date = '%s', xchan_photo_l = '%s', xchan_photo_m = '%s', xchan_photo_s = '%s', xchan_photo_mimetype = '%s' where xchan_hash = '%s'",
1193
		dbesc(datetime_convert()),
friendica's avatar
friendica committed
1194 1195 1196 1197 1198 1199 1200
		dbesc($photos[0]),
		dbesc($photos[1]),
		dbesc($photos[2]),
		dbesc($photos[3]),
		dbesc($guid)
	);

1201
	return true;
friendica's avatar
friendica committed
1202 1203
}

1204
function discover_by_webbie($webbie) {
friendica's avatar
friendica committed
1205
	require_once('library/HTML5/Parser.php');
1206

1207 1208 1209 1210
	$result   = array();

	$network  = null;

1211
	$diaspora = false;
1212 1213
	$gnusoc   = false;
	$dfrn     = false;
1214

1215 1216 1217 1218 1219 1220 1221
	$has_salmon = false;
	$salmon_key = false;
	$atom_feed = false;
	$diaspora_base = '';
	$diaspora_guid = '';
	$diaspora_key = '';

1222 1223
	$webbie = strtolower($webbie);

1224
	$x = webfinger_rfc7033($webbie,true);
1225 1226
	if($x && array_key_exists('links',$x) && $x['links']) {
		foreach($x['links'] as $link) {
1227
			if(array_key_exists('rel',$link)) {
1228 1229

				// If we discover zot - don't search further; grab the info and get out of
1230
				// here.
1231

redmatrix's avatar
redmatrix committed
1232
				if($link['rel'] === PROTOCOL_ZOT) {
1233
					logger('discover_by_webbie: zot found for ' . $webbie, LOGGER_DEBUG);
1234
					if(array_key_exists('zot',$x) && $x['zot']['success']) {
1235
						$i = import_xchan($x['zot']);
1236 1237
						return true;
					}
1238 1239 1240 1241 1242 1243 1244 1245 1246
					else {
						$z = z_fetch_url($link['href']);
						if($z['success']) {
							$j = json_decode($z['body'],true);
							$i = import_xchan($j);
							return true;
						}
					}
				}
1247 1248 1249
				if($link['rel'] == NAMESPACE_DFRN) {
					 $dfrn = $link['href'];
				}
1250
				if($link['rel'] == 'magic-public-key') {
1251
					if(substr($link['href'],0,5) === 'data:') {
1252
						$salmon_key = convert_salmon_key($link['href']);
1253
					}
1254
				}
1255 1256
				if($link['rel'] == 'salmon') {
					$has_salmon = true;
1257
					$salmon = $link['href'];
1258 1259 1260 1261
				}
				if($link['rel'] == 'http://schemas.google.com/g/2010#updates-from') {
					$atom_feed = $link['href'];
				}
1262 1263 1264 1265
			}
		}
	}

1266
	logger('webfinger: ' . print_r($x,true), LOGGER_DATA, LOG_INFO);
1267 1268 1269

	$arr = array('address' => $webbie, 'success' => false, 'webfinger' => $x);
	call_hooks('discover_channel_webfinger', $arr);
1270 1271 1272
	if($arr['success'])
		return true;

1273
	$aliases = array();
redmatrix's avatar
redmatrix committed
1274

1275 1276
	// Now let's make some decisions on what we may need
	// to obtain further info
redmatrix's avatar
redmatrix committed
1277

1278 1279 1280
	$probe_atom  = false;
	$probe_old   = false;
	$probe_hcard = false;
redmatrix's avatar
redmatrix committed
1281

1282 1283 1284 1285 1286 1287
	$address  = '';
	$location = '';
	$nickname = '';
	$fullname = '';
	$avatar   = '';
	$pubkey   = '';
1288

redmatrix's avatar
redmatrix committed
1289
	if(is_array($x)) {
1290
		if(array_key_exists('address',$x))
redmatrix's avatar
redmatrix committed
1291
			$address = $x['address'];
1292
		if(array_key_exists('location',$x))
redmatrix's avatar
redmatrix committed
1293
			$location = $x['location'];
1294
		if(array_key_exists('nickname',$x))
redmatrix's avatar
redmatrix committed
1295 1296
			$nickname = $x['nickname'];
	}
1297

1298 1299
	if(! $x)
		$probe_old = true;
1300

1301
	if((! $dfrn) && (! $has_salmon))
redmatrix's avatar
redmatrix committed
1302 1303
		$probe_old = true;

1304
	if($probe_old) {
1305
		$y = old_webfinger($webbie);