$func, 'auth'=>$auth); // Workaround for hotot $path = str_replace("api/", "api/1.1/", $path); $API[$path] = array('func'=>$func, 'auth'=>$auth); } /** * Simple HTTP Login */ function api_login(&$a){ // login with oauth try{ $oauth = new FKOAuth1(); list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request()); if (!is_null($token)){ $oauth->loginUser($token->uid); call_hooks('logged_in', $a->user); return; } echo __file__.__line__.__function__."
"; var_dump($consumer, $token); die();
		}catch(Exception $e){
			logger(__file__.__line__.__function__."\n".$e);
			//die(__file__.__line__.__function__."".$e); die();
		}
		// workaround for HTTP-auth in CGI mode
		if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
			$userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
			if(strlen($userpass)) {
				list($name, $password) = explode(':', $userpass);
				$_SERVER['PHP_AUTH_USER'] = $name;
				$_SERVER['PHP_AUTH_PW'] = $password;
			}
		}
		if (!isset($_SERVER['PHP_AUTH_USER'])) {
			logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
			header('WWW-Authenticate: Basic realm="Friendica"');
			header('HTTP/1.0 401 Unauthorized');
			die((api_error($a, 'json', "This api requires login")));
			//die('This api requires login');
		}
		$user = $_SERVER['PHP_AUTH_USER'];
		$encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
		/**
		 *  next code from mod/auth.php. needs better solution
		 */
		// process normal login request
		$r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
			AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
			dbesc(trim($user)),
			dbesc(trim($user)),
			dbesc($encrypted)
		);
		if(count($r)){
			$record = $r[0];
		} else {
			logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
			header('WWW-Authenticate: Basic realm="Friendica"');
			header('HTTP/1.0 401 Unauthorized');
			die('This api requires login');
		}
		require_once('include/security.php');
		authenticate_success($record); $_SESSION["allow_api"] = true;
		call_hooks('logged_in', $a->user);
	}
	/**************************
	 *  MAIN API ENTRY POINT  *
	 **************************/
	function api_call(&$a){
		GLOBAL $API, $called_api;
		// preset
		$type="json";
		foreach ($API as $p=>$info){
			if (strpos($a->query_string, $p)===0){
				$called_api= explode("/",$p);
				//unset($_SERVER['PHP_AUTH_USER']);
				if ($info['auth']===true && api_user()===false) {
						api_login($a);
				}
				load_contact_links(api_user());
				logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
				logger('API parameters: ' . print_r($_REQUEST,true));
				$type="json";
				if (strpos($a->query_string, ".xml")>0) $type="xml";
				if (strpos($a->query_string, ".json")>0) $type="json";
				if (strpos($a->query_string, ".rss")>0) $type="rss";
				if (strpos($a->query_string, ".atom")>0) $type="atom";
				if (strpos($a->query_string, ".as")>0) $type="as";
				$r = call_user_func($info['func'], $a, $type);
				if ($r===false) return;
				switch($type){
					case "xml":
						$r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
						header ("Content-Type: text/xml");
						return ''."\n".$r;
						break;
					case "json":
						header ("Content-Type: application/json");
						foreach($r as $rr)
							$json = json_encode($rr);
							if ($_GET['callback'])
								$json = $_GET['callback']."(".$json.")";
							return $json;
						break;
					case "rss":
						header ("Content-Type: application/rss+xml");
						return ''."\n".$r;
						break;
					case "atom":
						header ("Content-Type: application/atom+xml");
						return ''."\n".$r;
						break;
					case "as":
						//header ("Content-Type: application/json");
						//foreach($r as $rr)
						//	return json_encode($rr);
						return json_encode($r);
						break;
				}
				//echo ""; var_dump($r); die();
			}
		}
		header("HTTP/1.1 404 Not Found");
		logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
		return(api_error($a, $type, "not implemented"));
	}
	function api_error(&$a, $type, $error) {
		# TODO:  https://dev.twitter.com/overview/api/response-codes
		$r = "".$error." ".$a->query_string." not implemented ".bbcode($item['title'])."
\n".$statushtml;
		$entities = api_get_entitities($statustext, $body);
		return(array("text" => $statustext, "html" => $statushtml, "attachments" => $attachments, "entities" => $entities));
	}
	function api_get_attachments(&$body) {
		$text = $body;
		$text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
		$URLSearchString = "^\[\]";
		$ret = preg_match_all("/\[img\]([$URLSearchString]*)\[\/img\]/ism", $text, $images);
		if (!$ret)
			return false;
		require_once("include/Photo.php");
		$attachments = array();
		foreach ($images[1] AS $image) {
			$imagedata = get_photo_info($image);
			if ($imagedata)
				$attachments[] = array("url" => $image, "mimetype" => $imagedata["mime"], "size" => $imagedata["size"]);
		}
		if (strstr($_SERVER['HTTP_USER_AGENT'], "AndStatus"))
			foreach ($images[0] AS $orig)
				$body = str_replace($orig, "", $body);
		return $attachments;
	}
	function api_get_entitities(&$text, $bbcode) {
		/*
		To-Do:
		* Links at the first character of the post
		*/
		$a = get_app();
		$include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
		if ($include_entities != "true") {
			require_once("mod/proxy.php");
			preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
			foreach ($images[1] AS $image) {
				$replace = proxy_url($image);
				$text = str_replace($image, $replace, $text);
			}
			return array();
		}
		$bbcode = bb_CleanPictureLinks($bbcode);
		// Change pure links in text to bbcode uris
		$bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
		$entities = array();
		$entities["hashtags"] = array();
		$entities["symbols"] = array();
		$entities["urls"] = array();
		$entities["user_mentions"] = array();
		$URLSearchString = "^\[\]";
		$bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
		$bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
		//$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
		$bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
		$bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
					'[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
		$bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
		$bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
					'[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
		$bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
		$bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
		//preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
		preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
		$ordered_urls = array();
		foreach ($urls[1] AS $id=>$url) {
			//$start = strpos($text, $url, $offset);
			$start = iconv_strpos($text, $url, 0, "UTF-8");
			if (!($start === false))
				$ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
		}
		ksort($ordered_urls);
		$offset = 0;
		//foreach ($urls[1] AS $id=>$url) {
		foreach ($ordered_urls AS $url) {
			if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
				!strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
				$display_url = $url["title"];
			else {
				$display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
				$display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
				if (strlen($display_url) > 26)
					$display_url = substr($display_url, 0, 25)."…";
			}
			//$start = strpos($text, $url, $offset);
			$start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
			if (!($start === false)) {
				$entities["urls"][] = array("url" => $url["url"],
								"expanded_url" => $url["url"],
								"display_url" => $display_url,
								"indices" => array($start, $start+strlen($url["url"])));
				$offset = $start + 1;
			}
		}
		preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
		$ordered_images = array();
		foreach ($images[1] AS $image) {
			//$start = strpos($text, $url, $offset);
			$start = iconv_strpos($text, $image, 0, "UTF-8");
			if (!($start === false))
				$ordered_images[$start] = $image;
		}
		//$entities["media"] = array();
		$offset = 0;
		foreach ($ordered_images AS $url) {
			$display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
			$display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
			if (strlen($display_url) > 26)
				$display_url = substr($display_url, 0, 25)."…";
			$start = iconv_strpos($text, $url, $offset, "UTF-8");
			if (!($start === false)) {
				require_once("include/Photo.php");
				$image = get_photo_info($url);
				if ($image) {
					// If image cache is activated, then use the following sizes:
					// thumb  (150), small (340), medium (600) and large (1024)
					if (!get_config("system", "proxy_disabled")) {
						require_once("mod/proxy.php");
						$media_url = proxy_url($url);
						$sizes = array();
						$scale = scale_image($image[0], $image[1], 150);
						$sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
						if (($image[0] > 150) OR ($image[1] > 150)) {
							$scale = scale_image($image[0], $image[1], 340);
							$sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
						}
						$scale = scale_image($image[0], $image[1], 600);
						$sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
						if (($image[0] > 600) OR ($image[1] > 600)) {
							$scale = scale_image($image[0], $image[1], 1024);
							$sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
						}
					} else {
						$media_url = $url;
						$sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
					}
					$entities["media"][] = array(
								"id" => $start+1,
								"id_str" => (string)$start+1,
								"indices" => array($start, $start+strlen($url)),
								"media_url" => normalise_link($media_url),
								"media_url_https" => $media_url,
								"url" => $url,
								"display_url" => $display_url,
								"expanded_url" => $url,
								"type" => "photo",
								"sizes" => $sizes);
				}
				$offset = $start + 1;
			}
		}
		return($entities);
	}
	function api_format_items_embeded_images($item, $text){
		$a = get_app();
		$text = preg_replace_callback(
				"|data:image/([^;]+)[^=]+=*|m",
				function($match) use ($a, $item) {
					return $a->get_baseurl()."/display/".$item['guid'];
				},
				$text);
		return $text;
	}
	function api_format_items($r,$user_info, $filter_user = false) {
		$a = get_app();
		$ret = Array();
		foreach($r as $item) {
			api_share_as_retweet($a, api_user(), $item);
			localize_item($item);
			$status_user = api_item_get_user($a,$item);
			// Look if the posts are matching if they should be filtered by user id
			if ($filter_user AND ($status_user["id"] != $user_info["id"]))
				continue;
			if ($item['thr-parent'] != $item['uri']) {
				$r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
					intval(api_user()),
					dbesc($item['thr-parent']));
				if ($r)
					$in_reply_to_status_id = intval($r[0]['id']);
				else
					$in_reply_to_status_id = intval($item['parent']);
				$in_reply_to_status_id_str = (string) intval($item['parent']);
				$in_reply_to_screen_name = NULL;
				$in_reply_to_user_id = NULL;
				$in_reply_to_user_id_str = NULL;
				$r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
					intval(api_user()),
					intval($in_reply_to_status_id));
				if ($r) {
					$r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
					if ($r) {
						if ($r[0]['nick'] == "")
							$r[0]['nick'] = api_get_nick($r[0]["url"]);
						$in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
						$in_reply_to_user_id = intval($r[0]['id']);
						$in_reply_to_user_id_str = (string) intval($r[0]['id']);
					}
				}
			} else {
				$in_reply_to_screen_name = NULL;
				$in_reply_to_user_id = NULL;
				$in_reply_to_status_id = NULL;
				$in_reply_to_user_id_str = NULL;
				$in_reply_to_status_id_str = NULL;
			}
			$converted = api_convert_item($item);
			$status = array(
				'text'		=> $converted["text"],
				'truncated' => False,
				'created_at'=> api_date($item['created']),
				'in_reply_to_status_id' => $in_reply_to_status_id,
				'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
				'source'    => (($item['app']) ? $item['app'] : 'web'),
				'id'		=> intval($item['id']),
				'id_str'	=> (string) intval($item['id']),
				'in_reply_to_user_id' => $in_reply_to_user_id,
				'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
				'in_reply_to_screen_name' => $in_reply_to_screen_name,
				'geo' => NULL,
				'favorited' => $item['starred'] ? true : false,
				'user' =>  $status_user ,
				//'entities' => NULL,
				'statusnet_html'		=> $converted["html"],
				'statusnet_conversation_id'	=> $item['parent'],
			);
			if (count($converted["attachments"]) > 0)
				$status["attachments"] = $converted["attachments"];
			if (count($converted["entities"]) > 0)
				$status["entities"] = $converted["entities"];
			if (($item['item_network'] != "") AND ($status["source"] == 'web'))
				$status["source"] = network_to_name($item['item_network']);
			else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
				$status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
			// Retweets are only valid for top postings
			// It doesn't work reliable with the link if its a feed
			$IsRetweet = ($item['owner-link'] != $item['author-link']);
			if ($IsRetweet)
				$IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
			if ($IsRetweet AND ($item["id"] == $item["parent"])) {
				$retweeted_status = $status;
				$retweeted_status["user"] = api_get_user($a,$item["author-link"]);
				$status["retweeted_status"] = $retweeted_status;
			}
			// "uid" and "self" are only needed for some internal stuff, so remove it from here
			unset($status["user"]["uid"]);
			unset($status["user"]["self"]);
			// 'geo' => array('type' => 'Point',
			//                   'coordinates' => array((float) $notice->lat,
			//                                          (float) $notice->lon));
			$ret[] = $status;
		};
		return $ret;
	}
	function api_account_rate_limit_status(&$a,$type) {
		$hash = array(
			  'reset_time_in_seconds' => strtotime('now + 1 hour'),
			  'remaining_hits' => (string) 150,
			  'hourly_limit' => (string) 150,
			  'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
		);
		if ($type == "xml")
			$hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
		return api_apply_template('ratelimit', $type, array('$hash' => $hash));
	}
	api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
	function api_help_test(&$a,$type) {
		if ($type == 'xml')
			$ok = "true";
		else
			$ok = "ok";
		return api_apply_template('test', $type, array("$ok" => $ok));
	}
	api_register_func('api/help/test','api_help_test',false);
	function api_lists(&$a,$type) {
		$ret = array();
		return array($ret);
	}
	api_register_func('api/lists','api_lists',true);
	function api_lists_list(&$a,$type) {
		$ret = array();
		return array($ret);
	}
	api_register_func('api/lists/list','api_lists_list',true);
	/**
	 *  https://dev.twitter.com/docs/api/1/get/statuses/friends
	 *  This function is deprecated by Twitter
	 *  returns: json, xml
	 **/
	function api_statuses_f(&$a, $type, $qtype) {
		if (api_user()===false) return false;
		$user_info = api_get_user($a);
		if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
			/* this is to stop Hotot to load friends multiple times
			*  I'm not sure if I'm missing return something or
			*  is a bug in hotot. Workaround, meantime
			*/
			/*$ret=Array();
			return array('$users' => $ret);*/
			return false;
		}
		if($qtype == 'friends')
			$sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
		if($qtype == 'followers')
			$sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
		// friends and followers only for self
		if ($user_info['self'] == 0)
			$sql_extra = " AND false ";
		$r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
			intval(api_user())
		);
		$ret = array();
		foreach($r as $cid){
			$user = api_get_user($a, $cid['nurl']);
			// "uid" and "self" are only needed for some internal stuff, so remove it from here
			unset($user["uid"]);
			unset($user["self"]);
			if ($user)
				$ret[] = $user;
		}
		return array('$users' => $ret);
	}
	function api_statuses_friends(&$a, $type){
		$data =  api_statuses_f($a,$type,"friends");
		if ($data===false) return false;
		return  api_apply_template("friends", $type, $data);
	}
	function api_statuses_followers(&$a, $type){
		$data = api_statuses_f($a,$type,"followers");
		if ($data===false) return false;
		return  api_apply_template("friends", $type, $data);
	}
	api_register_func('api/statuses/friends','api_statuses_friends',true);
	api_register_func('api/statuses/followers','api_statuses_followers',true);
	function api_statusnet_config(&$a,$type) {
		$name = $a->config['sitename'];
		$server = $a->get_hostname();
		$logo = $a->get_baseurl() . '/images/friendica-64.png';
		$email = $a->config['admin_email'];
		$closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
		$private = (($a->config['system']['block_public']) ? 'true' : 'false');
		$textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
		if($a->config['api_import_size'])
			$texlimit = string($a->config['api_import_size']);
		$ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
		$sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
		$config = array(
			'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
				'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
				'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
				'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
				'shorturllength' => '30',
				'friendica' => array(
						'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
						'FRIENDICA_VERSION' => FRIENDICA_VERSION,
						'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
						'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
						)
			),
		);
		return api_apply_template('config', $type, array('$config' => $config));
	}
	api_register_func('api/statusnet/config','api_statusnet_config',false);
	function api_statusnet_version(&$a,$type) {
		// liar
		if($type === 'xml') {
			header("Content-type: application/xml");
			echo '' . "\r\n" . '0.9.7 ' . "\r\n";
			killme();
		}
		elseif($type === 'json') {
			header("Content-type: application/json");
			echo '"0.9.7"';
			killme();
		}
	}
	api_register_func('api/statusnet/version','api_statusnet_version',false);
	function api_ff_ids(&$a,$type,$qtype) {
		if(! api_user())
			return false;
		$user_info = api_get_user($a);
		if($qtype == 'friends')
			$sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
		if($qtype == 'followers')
			$sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
		if (!$user_info["self"])
			$sql_extra = " AND false ";
		$stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
		$r = q("SELECT unique_contacts.id FROM contact, unique_contacts WHERE contact.nurl = unique_contacts.url AND `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
			intval(api_user())
		);
		if(is_array($r)) {
			if($type === 'xml') {
				header("Content-type: application/xml");
				echo '' . "\r\n" . '' . "\r\n";
				foreach($r as $rr)
					echo '' . $rr['id'] . ' ' . "\r\n";
				echo ' ' . "\r\n";
				killme();
			}
			elseif($type === 'json') {
				$ret = array();
				header("Content-type: application/json");
				foreach($r as $rr)
					if ($stringify_ids)
						$ret[] = $rr['id'];
					else
						$ret[] = intval($rr['id']);
				echo json_encode($ret);
				killme();
			}
		}
	}
	function api_friends_ids(&$a,$type) {
		api_ff_ids($a,$type,'friends');
	}
	function api_followers_ids(&$a,$type) {
		api_ff_ids($a,$type,'followers');
	}
	api_register_func('api/friends/ids','api_friends_ids',true);
	api_register_func('api/followers/ids','api_followers_ids',true);
	function api_direct_messages_new(&$a, $type) {
		if (api_user()===false) return false;
		if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
		$sender = api_get_user($a);
		require_once("include/message.php");
		if ($_POST['screen_name']) {
			$r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
					intval(api_user()),
					dbesc($_POST['screen_name']));
			// Selecting the id by priority, friendica first
			api_best_nickname($r);
			$recipient = api_get_user($a, $r[0]['nurl']);
		} else
			$recipient = api_get_user($a, $_POST['user_id']);
		$replyto = '';
		$sub     = '';
		if (x($_REQUEST,'replyto')) {
			$r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
					intval(api_user()),
					intval($_REQUEST['replyto']));
			$replyto = $r[0]['parent-uri'];
			$sub     = $r[0]['title'];
		}
		else {
			if (x($_REQUEST,'title')) {
				$sub = $_REQUEST['title'];
			}
			else {
				$sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
			}
		}
		$id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
		if ($id>-1) {
			$r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
			$ret = api_format_messages($r[0], $recipient, $sender);
		} else {
			$ret = array("error"=>$id);
		}
		$data = Array('$messages'=>$ret);
		switch($type){
			case "atom":
			case "rss":
				$data = api_rss_extra($a, $data, $user_info);
		}
		return  api_apply_template("direct_messages", $type, $data);
	}
	api_register_func('api/direct_messages/new','api_direct_messages_new',true);
	function api_direct_messages_box(&$a, $type, $box) {
		if (api_user()===false) return false;
		// params
		$count = (x($_GET,'count')?$_GET['count']:20);
		$page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
		if ($page<0) $page=0;
		$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
		$max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
		$user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
		$screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
		//  caller user info
		unset($_REQUEST["user_id"]);
		unset($_GET["user_id"]);
		unset($_REQUEST["screen_name"]);
		unset($_GET["screen_name"]);
		$user_info = api_get_user($a);
		//$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
		$profile_url = $user_info["url"];
		// pagination
		$start = $page*$count;
		// filters
		if ($box=="sentbox") {
			$sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
		}
		elseif ($box=="conversation") {
			$sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] )  ."'";
		}
		elseif ($box=="all") {
			$sql_extra = "true";
		}
		elseif ($box=="inbox") {
			$sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
		}
		if ($max_id > 0)
			$sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
		if ($user_id !="") {
			$sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
		}
		elseif($screen_name !=""){
			$sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
		}
		$r = q("SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`id` DESC LIMIT %d,%d",
				intval(api_user()),
				intval($since_id),
				intval($start),	intval($count)
		);
		$ret = Array();
		foreach($r as $item) {
			if ($box == "inbox" || $item['from-url'] != $profile_url){
				$recipient = $user_info;
				$sender = api_get_user($a,normalise_link($item['contact-url']));
			}
			elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
				$recipient = api_get_user($a,normalise_link($item['contact-url']));
				$sender = $user_info;
			}
			$ret[]=api_format_messages($item, $recipient, $sender);
		}
		$data = array('$messages' => $ret);
		switch($type){
			case "atom":
			case "rss":
				$data = api_rss_extra($a, $data, $user_info);
		}
		return  api_apply_template("direct_messages", $type, $data);
	}
	function api_direct_messages_sentbox(&$a, $type){
		return api_direct_messages_box($a, $type, "sentbox");
	}
	function api_direct_messages_inbox(&$a, $type){
		return api_direct_messages_box($a, $type, "inbox");
	}
	function api_direct_messages_all(&$a, $type){
		return api_direct_messages_box($a, $type, "all");
	}
	function api_direct_messages_conversation(&$a, $type){
		return api_direct_messages_box($a, $type, "conversation");
	}
	api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
	api_register_func('api/direct_messages/all','api_direct_messages_all',true);
	api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
	api_register_func('api/direct_messages','api_direct_messages_inbox',true);
	function api_oauth_request_token(&$a, $type){
		try{
			$oauth = new FKOAuth1();
			$r = $oauth->fetch_request_token(OAuthRequest::from_request());
		}catch(Exception $e){
			echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
		}
		echo $r;
		killme();
	}
	function api_oauth_access_token(&$a, $type){
		try{
			$oauth = new FKOAuth1();
			$r = $oauth->fetch_access_token(OAuthRequest::from_request());
		}catch(Exception $e){
			echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
		}
		echo $r;
		killme();
	}
	api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
	api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
	function api_fr_photos_list(&$a,$type) {
		if (api_user()===false) return false;
		$r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
			intval(local_user())
		);
		if($r) {
			$ret = array();
			foreach($r as $rr)
				$ret[] = $rr['resource-id'];
			header("Content-type: application/json");
			echo json_encode($ret);
		}
		killme();
	}
	function api_fr_photo_detail(&$a,$type) {
		if (api_user()===false) return false;
		if(! $_REQUEST['photo_id']) return false;
		$scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
 		$r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
			intval(local_user()),
			dbesc($_REQUEST['photo_id']),
			intval($scale)
		);
		if($r) {
			header("Content-type: application/json");
			$r[0]['data'] = base64_encode($r[0]['data']);
			echo json_encode($r[0]);
		}
		killme();
	}
	api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
	api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
function api_share_as_retweet($a, $uid, &$item) {
	$body = trim($item["body"]);
	// Skip if it isn't a pure repeated messages
	// Does it start with a share?
	if (strpos($body, "[share") > 0)
		return(false);
	// Does it end with a share?
	if (strlen($body) > (strrpos($body, "[/share]") + 8))
		return(false);
	$attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
	// Skip if there is no shared message in there
	if ($body == $attributes)
		return(false);
	$author = "";
	preg_match("/author='(.*?)'/ism", $attributes, $matches);
	if ($matches[1] != "")
		$author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
	preg_match('/author="(.*?)"/ism', $attributes, $matches);
	if ($matches[1] != "")
		$author = $matches[1];
	$profile = "";
	preg_match("/profile='(.*?)'/ism", $attributes, $matches);
	if ($matches[1] != "")
		$profile = $matches[1];
	preg_match('/profile="(.*?)"/ism', $attributes, $matches);
	if ($matches[1] != "")
		$profile = $matches[1];
	$avatar = "";
	preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
	if ($matches[1] != "")
		$avatar = $matches[1];
	preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
	if ($matches[1] != "")
		$avatar = $matches[1];
	$shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
	if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
		return(false);
	$item["body"] = $shared_body;
	$item["author-name"] = $author;
	$item["author-link"] = $profile;
	$item["author-avatar"] = $avatar;
	return(true);
}
function api_get_nick($profile) {
/* To-Do:
 - remove trailing jung from profile url
 - pump.io check has to check the website
*/
	$nick = "";
	$friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
	if ($friendica != $profile)
		$nick = $friendica;
	if (!$nick == "") {
		$diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
		if ($diaspora != $profile)
			$nick = $diaspora;
	}
	if (!$nick == "") {
		$twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
		if ($twitter != $profile)
			$nick = $twitter;
	}
	if (!$nick == "") {
		$StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
		if ($StatusnetHost != $profile) {
			$StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
			if ($StatusnetUser != $profile) {
				$UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
				$user = json_decode($UserData);
				if ($user)
					$nick = $user->screen_name;
			}
		}
	}
	// To-Do: look at the page if its really a pumpio site
	//if (!$nick == "") {
	//	$pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
	//	if ($pumpio != $profile)
	//		$nick = $pumpio;
		//      
	//}
	if ($nick != "") {
		q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
			dbesc($nick), dbesc(normalise_link($profile)));
		return($nick);
	}
	return(false);
}
function api_clean_plain_items($Text) {
	$include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
	$Text = bb_CleanPictureLinks($Text);
	$URLSearchString = "^\[\]";
	$Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
	if ($include_entities == "true") {
		$Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
	}
	$Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
	return($Text);
}
function api_cleanup_share($shared) {
	if ($shared[2] != "type-link")
		return($shared[0]);
	if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
		return($shared[0]);
	$title = "";
	$link = "";
	if (isset($bookmark[2][0]))
		$title = $bookmark[2][0];
	if (isset($bookmark[1][0]))
		$link = $bookmark[1][0];
	if (strpos($shared[1],$title) !== false)
		$title = "";
	if (strpos($shared[1],$link) !== false)
		$link = "";
	$text = trim($shared[1]);
	//if (strlen($text) < strlen($title))
	if (($text == "") AND ($title != ""))
		$text .= "\n\n".trim($title);
	if ($link != "")
		$text .= "\n".trim($link);
	return(trim($text));
}
function api_best_nickname(&$contacts) {
	$best_contact = array();
	if (count($contact) == 0)
		return;
	foreach ($contacts AS $contact)
		if ($contact["network"] == "") {
			$contact["network"] = "dfrn";
			$best_contact = array($contact);
		}
	if (sizeof($best_contact) == 0)
		foreach ($contacts AS $contact)
			if ($contact["network"] == "dfrn")
				$best_contact = array($contact);
	if (sizeof($best_contact) == 0)
		foreach ($contacts AS $contact)
			if ($contact["network"] == "dspr")
				$best_contact = array($contact);
	if (sizeof($best_contact) == 0)
		foreach ($contacts AS $contact)
			if ($contact["network"] == "stat")
				$best_contact = array($contact);
	if (sizeof($best_contact) == 0)
		foreach ($contacts AS $contact)
			if ($contact["network"] == "pump")
				$best_contact = array($contact);
	if (sizeof($best_contact) == 0)
		foreach ($contacts AS $contact)
			if ($contact["network"] == "twit")
				$best_contact = array($contact);
	if (sizeof($best_contact) == 1)
		$contacts = $best_contact;
	else
		$contacts = array($contacts[0]);
}
/*
Not implemented by now:
statuses/retweets_of_me
friendships/create
friendships/destroy
friendships/exists
friendships/show
account/update_location
account/update_profile_background_image
account/update_profile_image
blocks/create
blocks/destroy
Not implemented in status.net:
statuses/retweeted_to_me
statuses/retweeted_by_me
direct_messages/destroy
account/end_session
account/update_delivery_device
notifications/follow
notifications/leave
blocks/exists
blocks/blocking
lists
*/