". * Some clients doesn't send a source param, we support ones we know * (only Twidere, atm) * * @return string * Client source name, default to "api" if unset/unknown */ function api_source() { if (requestdata('source')) return (requestdata('source')); // Support for known clients that doesn't send a source name if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere")) return ("Twidere"); logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG); return ("api"); } /** * @brief Format date for API * * @param string $str Source date, as UTC * @return string Date in UTC formatted as "D M d H:i:s +0000 Y" */ function api_date($str){ //Wed May 23 06:01:13 +0000 2007 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" ); } /** * @brief Register API endpoint * * Register a function to be the endpont for defined API path. * * @param string $path API URL path, relative to $a->get_baseurl() * @param string $func Function name to call on path request * @param bool $auth API need logged user * @param string $method * HTTP method reqiured to call this endpoint. * One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST. * Default to API_METHOD_ANY */ function api_register_func($path, $func, $auth=false, $method=API_METHOD_ANY){ global $API; $API[$path] = array( 'func'=>$func, 'auth'=>$auth, 'method'=> $method ); // Workaround for hotot $path = str_replace("api/", "api/1.1/", $path); $API[$path] = array( 'func'=>$func, 'auth'=>$auth, 'method'=> $method ); } /** * @brief Login API user * * Log in user via OAuth1 or Simple HTTP Auth. * Simple Auth allow username in form of
user@server, ignoring server part * * @param App $a * @hook 'authenticate' * array $addon_auth * 'username' => username from login form * 'password' => password from login form * 'authenticated' => return status, * 'user_record' => return authenticated user record * @hook 'logged_in' * array $user logged user record */ 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($e);
		}
		// 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"');
			throw new UnauthorizedException("This API requires login");
		}
		$user = $_SERVER['PHP_AUTH_USER'];
		$password = $_SERVER['PHP_AUTH_PW'];
		$encrypted = hash('whirlpool',trim($password));
		// allow "user@server" login (but ignore 'server' part)
		$at=strstr($user, "@", true);
		if ( $at ) $user=$at;
		/**
		 *  next code from mod/auth.php. needs better solution
		 */
		$record = null;
		$addon_auth = array(
			'username' => trim($user),
			'password' => trim($password),
			'authenticated' => 0,
			'user_record' => null
		);
		/**
		 *
		 * A plugin indicates successful login by setting 'authenticated' to non-zero value and returning a user record
		 * Plugins should never set 'authenticated' except to indicate success - as hooks may be chained
		 * and later plugins should not interfere with an earlier one that succeeded.
		 *
		 */
		call_hooks('authenticate', $addon_auth);
		if(($addon_auth['authenticated']) && (count($addon_auth['user_record']))) {
			$record = $addon_auth['user_record'];
		}
		else {
			// 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];
		}
		if((! $record) || (! count($record))) {
			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');
			throw new UnauthorizedException("This API requires login");
		}
		authenticate_success($record); $_SESSION["allow_api"] = true;
		call_hooks('logged_in', $a->user);
	}
	/**
	 * @brief Check HTTP method of called API
	 *
	 * API endpoints can define which HTTP method to accept when called.
	 * This function check the current HTTP method agains endpoint
	 * registered method.
	 *
	 * @param string $method Required methods, uppercase, separated by comma
	 * @return bool
	 */
	 function api_check_method($method) {
		if ($method=="*") return True;
		return strpos($method, $_SERVER['REQUEST_METHOD']) !== false;
	 }
	/**
	 * @brief Main API entry point
	 *
	 * Authenticate user, call registered API function, set HTTP headers
	 *
	 * @param App $a
	 * @return string API call result
	 */
	function api_call(&$a){
		GLOBAL $API, $called_api;
		
		$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";
		try {
			foreach ($API as $p=>$info){
				if (strpos($a->query_string, $p)===0){
					if (!api_check_method($info['method'])){
						throw new MethodNotAllowedException();
					}
					$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));
					$stamp =  microtime(true);
					$r = call_user_func($info['func'], $a, $type);
					$duration = (float)(microtime(true)-$stamp);
					logger("API call duration: ".round($duration, 2)."\t".$a->query_string, LOGGER_DEBUG);
					if ($r===false) {
						// api function returned false withour throw an
						// exception. This should not happend, throw a 500
						throw new InternalServerErrorException();
					}
					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;
					}
				}
			}
			throw new NotImplementedException();
		} catch (HTTPException $e) {
			header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
			return api_error($a, $type, $e);
		}
	}
	/**
	 * @brief Format API error string
	 *
	 * @param Api $a
	 * @param string $type Return type (xml, json, rss, as)
	 * @param HTTPException $error Error object
	 * @return strin error message formatted as $type
	 */
	function api_error(&$a, $type, $e) {
		$error = ($e->getMessage()!==""?$e->getMessage():$e->httpdesc);
		# TODO:  https://dev.twitter.com/overview/api/response-codes
		$xmlstr = "{$error} {$e->httpcode} {$e->httpdesc}{$a->query_string} ") {
					$ret = api_array_to_xml($data); 
				} else {
					$tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
					if(! $tpl) {
						header ("Content-Type: text/xml");
						echo ''."\n".'not implemented 
", "", "
",
				"", "
", "", "
",
				"", "
", "", "
",
				"", "
", "", "
");
		$replace = array("
\n", "\n", "
\n",
				"\n", "
\n", "\n", "
\n",
				"\n", "
\n", "\n", "
\n",
				"\n", "
\n", "\n", "
\n");
		$statushtml = str_replace($search, $replace, $statushtml);
		if ($item['title'] != "")
			$statushtml = "".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;
		$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") {
			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)) {
				$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")) {
						$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;
	}
	/**
	 * @brief return likes, dislikes and attend status for item
	 *
	 * @param array $item
	 * @return array
	 * 			likes => int count
	 * 			dislikes => int count
	 */
	function api_format_items_likes(&$item) {
		$activities = array(
			'like' => array(),
			'dislike' => array(),
			'attendyes' => array(),
			'attendno' => array(),
			'attendmaybe' => array()
		);
		$items = q('SELECT * FROM item
					WHERE uid=%d AND `thr-parent`="%s" AND visible AND NOT deleted',
					intval($item['uid']),
					dbesc($item['uri']));
		foreach ($items as $i){
			builtin_activity_puller($i, $activities);
		}
		$res = array();
		$uri = $item['uri'];
		foreach($activities as $k => $v) {
			$res[$k] = (x($v,$uri)?$v[$uri]:0);
		}
		return $res;
	}
	/**
	 * @brief format items to be returned by api
	 *
	 * @param array $r array of items
	 * @param array $user_info
	 * @param bool $filter_user filter items by $user_info
	 */
	function api_format_items($r,$user_info, $filter_user = false) {
		$a = get_app();
		$ret = Array();
		foreach($r as $item) {
			api_share_as_retweet($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 `gcontact` 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'],
				'friendica_activities' => api_format_items_likes($item),
			);
			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'], $user_info['url']);
			else if (($item['item_network'] != "") AND (network_to_name($item['item_network'], $user_info['url']) != $status["source"]))
				$status["source"] = trim($status["source"].' ('.network_to_name($item['item_network'], $user_info['url']).')');
			// 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"]);
			if ($item["coord"] != "") {
				$coords = explode(' ',$item["coord"]);
				if (count($coords) == 2) {
					$status["geo"] = array('type' => 'Point',
							'coordinates' => array((float) $coords[0],
										(float) $coords[1]));
				}
			}
			$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) throw new ForbiddenException();
		$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
		$fake_statusnet_version = "0.9.7";
		if($type === 'xml') {
			header("Content-type: application/xml");
			echo '' . "\r\n" . ''.$fake_statusnet_version.' ' . "\r\n";
			killme();
		}
		elseif($type === 'json') {
			header("Content-type: application/json");
			echo '"'.$fake_statusnet_version.'"';
			killme();
		}
	}
	api_register_func('api/statusnet/version','api_statusnet_version',false);
	/**
	 * @todo use api_apply_template() to return data
	 */
	function api_ff_ids(&$a,$type,$qtype) {
		if(! api_user()) throw new ForbiddenException();
		$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 `gcontact`.`id` FROM `contact`, `gcontact` WHERE `contact`.`nurl` = `gcontact`.`nurl` AND `uid` = %d AND NOT `self` AND NOT `blocked` AND NOT `pending` $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) throw new ForbiddenException();
		if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
		$sender = api_get_user($a);
		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, API_METHOD_POST);
	function api_direct_messages_box(&$a, $type, $box) {
		if (api_user()===false) throw new ForbiddenException();
		// 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) throw new ForbiddenException();
		$r = q("select `resource-id`, max(scale) as scale, album, filename, type from photo
				where uid = %d and album != 'Contact Photos' group by `resource-id`",
			intval(local_user())
		);
		$typetoext = array(
		'image/jpeg' => 'jpg',
		'image/png' => 'png',
		'image/gif' => 'gif'
		);
		$data = array('photos'=>array());
		if($r) {
			foreach($r as $rr) {
				$photo = array();
				$photo['id'] = $rr['resource-id'];
				$photo['album'] = $rr['album'];
				$photo['filename'] = $rr['filename'];
				$photo['type'] = $rr['type'];
				$photo['thumb'] = $a->get_baseurl()."/photo/".$rr['resource-id']."-".$rr['scale'].".".$typetoext[$rr['type']];
				$data['photos'][] = $photo;
			}
		}
		return  api_apply_template("photos_list", $type, $data);
	}
	function api_fr_photo_detail(&$a,$type) {
		if (api_user()===false) throw new ForbiddenException();
		if(!x($_REQUEST,'photo_id')) throw new BadRequestException("No photo id.");
		$scale = (x($_REQUEST, 'scale') ? intval($_REQUEST['scale']) : false);
		$scale_sql = ($scale === false ? "" : sprintf("and scale=%d",intval($scale)));
		$data_sql = ($scale === false ? "" : "data, ");
		$r = q("select %s `resource-id`, `created`, `edited`, `title`, `desc`, `album`, `filename`,
						`type`, `height`, `width`, `datasize`, `profile`, min(`scale`) as minscale, max(`scale`) as maxscale
				from photo where `uid` = %d and `resource-id` = '%s' %s group by `resource-id`",
			$data_sql,
			intval(local_user()),
			dbesc($_REQUEST['photo_id']),
			$scale_sql
		);
		$typetoext = array(
		'image/jpeg' => 'jpg',
		'image/png' => 'png',
		'image/gif' => 'gif'
		);
		if ($r) {
			$data = array('photo' => $r[0]);
			if ($scale !== false) {
				$data['photo']['data'] = base64_encode($data['photo']['data']);
			} else {
				unset($data['photo']['datasize']); //needed only with scale param
			}
			$data['photo']['link'] = array();
			for($k=intval($data['photo']['minscale']); $k<=intval($data['photo']['maxscale']); $k++) {
				$data['photo']['link'][$k] = $a->get_baseurl()."/photo/".$data['photo']['resource-id']."-".$k.".".$typetoext[$data['photo']['type']];
			}
			$data['photo']['id'] = $data['photo']['resource-id'];
			unset($data['photo']['resource-id']);
			unset($data['photo']['minscale']);
			unset($data['photo']['maxscale']);
		} else {
			throw new NotFoundException();
		}
		return api_apply_template("photo_detail", $type, $data);
	}
	api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
	api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
	/**
	 * similar as /mod/redir.php
	 * redirect to 'url' after dfrn auth
	 *
	 * why this when there is mod/redir.php already?
	 * This use api_user() and api_login()
	 *
	 * params
	 * 		c_url: url of remote contact to auth to
	 * 		url: string, url to redirect after auth
	 */
	function api_friendica_remoteauth(&$a) {
		$url = ((x($_GET,'url')) ? $_GET['url'] : '');
		$c_url = ((x($_GET,'c_url')) ? $_GET['c_url'] : '');
		if ($url === '' || $c_url === '')
			throw new BadRequestException("Wrong parameters.");
		$c_url = normalise_link($c_url);
		// traditional DFRN
		$r = q("SELECT * FROM `contact` WHERE `id` = %d AND `nurl` = '%s' LIMIT 1",
			dbesc($c_url),
			intval(api_user())
		);
		if ((! count($r)) || ($r[0]['network'] !== NETWORK_DFRN))
			throw new BadRequestException("Unknown contact");
		$cid = $r[0]['id'];
		$dfrn_id = $orig_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
		if($r[0]['duplex'] && $r[0]['issued-id']) {
			$orig_id = $r[0]['issued-id'];
			$dfrn_id = '1:' . $orig_id;
		}
		if($r[0]['duplex'] && $r[0]['dfrn-id']) {
			$orig_id = $r[0]['dfrn-id'];
			$dfrn_id = '0:' . $orig_id;
		}
		$sec = random_string();
		q("INSERT INTO `profile_check` ( `uid`, `cid`, `dfrn_id`, `sec`, `expire`)
			VALUES( %d, %s, '%s', '%s', %d )",
			intval(api_user()),
			intval($cid),
			dbesc($dfrn_id),
			dbesc($sec),
			intval(time() + 45)
		);
		logger($r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
		$dest = (($url) ? '&destination_url=' . $url : '');
		goaway ($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
				. '&dfrn_version=' . DFRN_PROTOCOL_VERSION
				. '&type=profile&sec=' . $sec . $dest . $quiet );
	}
	api_register_func('api/friendica/remoteauth', 'api_friendica_remoteauth', true);
	function api_share_as_retweet(&$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];
		$link = "";
		preg_match("/link='(.*?)'/ism", $attributes, $matches);
		if ($matches[1] != "")
			$link = $matches[1];
		preg_match('/link="(.*?)"/ism', $attributes, $matches);
		if ($matches[1] != "")
			$link = $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;
		$item["plink"] = $link;
		return(true);
	}
	function api_get_nick($profile) {
		/* To-Do:
		 - remove trailing junk from profile url
		 - pump.io check has to check the website
		*/
		$nick = "";
		$r = q("SELECT `nick` FROM `gcontact` WHERE `nurl` = '%s'",
			dbesc(normalise_link($profile)));
		if ($r)
			$nick = $r[0]["nick"];
		if (!$nick == "") {
			$r = q("SELECT `nick` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s'",
				dbesc(normalise_link($profile)));
			if ($r)
				$nick = $r[0]["nick"];
		}
		if (!$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 != "")
			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);
		}
		// Simplify "attachment" element
		$Text = api_clean_attachments($Text);
		return($Text);
	}
	/**
	 * @brief Removes most sharing information for API text export
	 *
	 * @param string $body The original body
	 *
	 * @return string Cleaned body
	 */
	function api_clean_attachments($body) {
		$data = get_attachment_data($body);
		if (!$data)
			return $body;
		$body = "";
		if (isset($data["text"]))
			$body = $data["text"];
		if (($body == "") AND (isset($data["title"])))
			$body = $data["title"];
		if (isset($data["url"]))
			$body .= "\n".$data["url"];
		return $body;
	}
	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]);
	}
	// return all or a specified group of the user with the containing contacts
	function api_friendica_group_show(&$a, $type) {
		if (api_user()===false) throw new ForbiddenException();
		// params
		$user_info = api_get_user($a);
		$gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
		$uid = $user_info['uid'];
		// get data of the specified group id or all groups if not specified
		if ($gid != 0) {
			$r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d AND `id` = %d",
				intval($uid),
				intval($gid));
			// error message if specified gid is not in database
			if (count($r) == 0)
				throw new BadRequestException("gid not available");
		}
		else
			$r = q("SELECT * FROM `group` WHERE `deleted` = 0 AND `uid` = %d",
				intval($uid));
		// loop through all groups and retrieve all members for adding data in the user array
		foreach ($r as $rr) {
			$members = group_get_members($rr['id']);
			$users = array();
			foreach ($members as $member) {
				$user = api_get_user($a, $member['nurl']);
				$users[] = $user;
			}
			$grps[] = array('name' => $rr['name'], 'gid' => $rr['id'], 'user' => $users);
		}
		return api_apply_template("group_show", $type, array('$groups' => $grps));
	}
	api_register_func('api/friendica/group_show', 'api_friendica_group_show', true);
	// delete the specified group of the user
	function api_friendica_group_delete(&$a, $type) {
		if (api_user()===false) throw new ForbiddenException();
		// params
		$user_info = api_get_user($a);
		$gid = (x($_REQUEST,'gid') ? $_REQUEST['gid'] : 0);
		$name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
		$uid = $user_info['uid'];
		// error if no gid specified
		if ($gid == 0 || $name == "")
			throw new BadRequestException('gid or name not specified');
		// get data of the specified group id
		$r = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d",
			intval($uid),
			intval($gid));
		// error message if specified gid is not in database
		if (count($r) == 0)
			throw new BadRequestException('gid not available');
		// get data of the specified group id and group name
		$rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `id` = %d AND `name` = '%s'",
			intval($uid),
			intval($gid),
			dbesc($name));
		// error message if specified gid is not in database
		if (count($rname) == 0)
			throw new BadRequestException('wrong group name');
		// delete group
		$ret = group_rmv($uid, $name);
		if ($ret) {
			// return success
			$success = array('success' => $ret, 'gid' => $gid, 'name' => $name, 'status' => 'deleted', 'wrong users' => array());
			return api_apply_template("group_delete", $type, array('$result' => $success));
		}
		else
			throw new BadRequestException('other API error');
	}
	api_register_func('api/friendica/group_delete', 'api_friendica_group_delete', true, API_METHOD_DELETE);
	// create the specified group with the posted array of contacts
	function api_friendica_group_create(&$a, $type) {
		if (api_user()===false) throw new ForbiddenException();
		// params
		$user_info = api_get_user($a);
		$name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
		$uid = $user_info['uid'];
		$json = json_decode($_POST['json'], true);
		$users = $json['user'];
		// error if no name specified
		if ($name == "")
			throw new BadRequestException('group name not specified');
		// get data of the specified group name
		$rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 0",
			intval($uid),
			dbesc($name));
		// error message if specified group name already exists
		if (count($rname) != 0)
			throw new BadRequestException('group name already exists');
		// check if specified group name is a deleted group
		$rname = q("SELECT * FROM `group` WHERE `uid` = %d AND `name` = '%s' AND `deleted` = 1",
			intval($uid),
			dbesc($name));
		// error message if specified group name already exists
		if (count($rname) != 0)
			$reactivate_group = true;
		// create group
		$ret = group_add($uid, $name);
		if ($ret)
			$gid = group_byname($uid, $name);
		else
			throw new BadRequestException('other API error');
		// add members
		$erroraddinguser = false;
		$errorusers = array();
		foreach ($users as $user) {
			$cid = $user['cid'];
			// check if user really exists as contact
			$contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
				intval($cid),
				intval($uid));
			if (count($contact))
				$result = group_add_member($uid, $name, $cid, $gid);
			else {
				$erroraddinguser = true;
				$errorusers[] = $cid;
			}
		}
		// return success message incl. missing users in array
		$status = ($erroraddinguser ? "missing user" : ($reactivate_group ? "reactivated" : "ok"));
		$success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
		return api_apply_template("group_create", $type, array('result' => $success));
	}
	api_register_func('api/friendica/group_create', 'api_friendica_group_create', true, API_METHOD_POST);
	// update the specified group with the posted array of contacts
	function api_friendica_group_update(&$a, $type) {
		if (api_user()===false) throw new ForbiddenException();
		// params
		$user_info = api_get_user($a);
		$uid = $user_info['uid'];
		$gid = (x($_REQUEST, 'gid') ? $_REQUEST['gid'] : 0);
		$name = (x($_REQUEST, 'name') ? $_REQUEST['name'] : "");
		$json = json_decode($_POST['json'], true);
		$users = $json['user'];
		// error if no name specified
		if ($name == "")
			throw new BadRequestException('group name not specified');
		// error if no gid specified
		if ($gid == "")
			throw new BadRequestException('gid not specified');
		// remove members
		$members = group_get_members($gid);
		foreach ($members as $member) {
			$cid = $member['id'];
			foreach ($users as $user) {
				$found = ($user['cid'] == $cid ? true : false);
			}
			if (!$found) {
				$ret = group_rmv_member($uid, $name, $cid);
			}
		}
		// add members
		$erroraddinguser = false;
		$errorusers = array();
		foreach ($users as $user) {
			$cid = $user['cid'];
			// check if user really exists as contact
			$contact = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d",
				intval($cid),
				intval($uid));
			if (count($contact))
				$result = group_add_member($uid, $name, $cid, $gid);
			else {
				$erroraddinguser = true;
				$errorusers[] = $cid;
			}
		}
		// return success message incl. missing users in array
		$status = ($erroraddinguser ? "missing user" : "ok");
		$success = array('success' => true, 'gid' => $gid, 'name' => $name, 'status' => $status, 'wrong users' => $errorusers);
		return api_apply_template("group_update", $type, array('result' => $success));
	}
	api_register_func('api/friendica/group_update', 'api_friendica_group_update', true, API_METHOD_POST);
	function api_friendica_activity(&$a, $type) {
		if (api_user()===false) throw new ForbiddenException();
		$verb = strtolower($a->argv[3]);
		$verb = preg_replace("|\..*$|", "", $verb);
		$id = (x($_REQUEST, 'id') ? $_REQUEST['id'] : 0);
		$res = do_like($id, $verb);
		if ($res) {
			if ($type == 'xml')
				$ok = "true";
			else
				$ok = "ok";
			return api_apply_template('test', $type, array('ok' => $ok));
		} else {
			throw new BadRequestException('Error adding activity');
		}
	}
	api_register_func('api/friendica/activity/like', 'api_friendica_activity', true, API_METHOD_POST);
	api_register_func('api/friendica/activity/dislike', 'api_friendica_activity', true, API_METHOD_POST);
	api_register_func('api/friendica/activity/attendyes', 'api_friendica_activity', true, API_METHOD_POST);
	api_register_func('api/friendica/activity/attendno', 'api_friendica_activity', true, API_METHOD_POST);
	api_register_func('api/friendica/activity/attendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
	api_register_func('api/friendica/activity/unlike', 'api_friendica_activity', true, API_METHOD_POST);
	api_register_func('api/friendica/activity/undislike', 'api_friendica_activity', true, API_METHOD_POST);
	api_register_func('api/friendica/activity/unattendyes', 'api_friendica_activity', true, API_METHOD_POST);
	api_register_func('api/friendica/activity/unattendno', 'api_friendica_activity', true, API_METHOD_POST);
	api_register_func('api/friendica/activity/unattendmaybe', 'api_friendica_activity', true, API_METHOD_POST);
	/**
	 * @brief Returns notifications
	 *
	 * @param App $a
	 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
	 * @return string
	*/
	function api_friendica_notification(&$a, $type) {
		if (api_user()===false) throw new ForbiddenException();
		if ($a->argc!==3) throw new BadRequestException("Invalid argument count");
		$nm = new NotificationsManager();
		
		$notes = $nm->getAll(array(), "+seen -date", 50);
		return api_apply_template("", $type, array('$notes' => $notes));
	}
	
	/**
	 * @brief Set notification as seen and returns associated item (if possible)
	 *
	 * POST request with 'id' param as notification id
	 * 
	 * @param App $a
	 * @param string $type Known types are 'atom', 'rss', 'xml' and 'json'
	 * @return string
	 */
	function api_friendica_notification_seen(&$a, $type){
		if (api_user()===false) throw new ForbiddenException();
		if ($a->argc!==4) throw new BadRequestException("Invalid argument count");
		
		$id = (x($_REQUEST, 'id') ? intval($_REQUEST['id']) : 0);
		
		$nm = new NotificationsManager();		
		$note = $nm->getByID($id);
		if (is_null($note)) throw new BadRequestException("Invalid argument");
		
		$nm->setSeen($note);
		if ($note['otype']=='item') {
			// would be really better with an ItemsManager and $im->getByID() :-P
			$r = q("SELECT * FROM `item` WHERE `id`=%d AND `uid`=%d",
				intval($note['iid']),
				intval(local_user())
			);
			if ($r!==false) {
				// we found the item, return it to the user
				$user_info = api_get_user($a);
				$ret = api_format_items($r,$user_info);
				$data = array('$statuses' => $ret);
				return api_apply_template("timeline", $type, $data);
			}
			// the item can't be found, but we set the note as seen, so we count this as a success
		} 
		return api_apply_template('', $type, array('status' => "success"));
	}
	
	api_register_func('api/friendica/notification/seen', 'api_friendica_notification_seen', true, API_METHOD_POST);
	api_register_func('api/friendica/notification', 'api_friendica_notification', true, API_METHOD_GET);
	
/*
To.Do:
    [pagename] => api/1.1/statuses/lookup.json
    [id] => 605138389168451584
    [include_cards] => true
    [cards_platform] => Android-12
    [include_entities] => true
    [include_my_retweet] => 1
    [include_rts] => 1
    [include_reply_count] => true
    [include_descendent_reply_count] => true
(?)
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
*/