From 0c9f033505be5dbc2303d8758894e57c616c6534 Mon Sep 17 00:00:00 2001
From: Friendika <info@friendika.com>
Date: Sun, 31 Jul 2011 16:35:53 -0700
Subject: [PATCH] some api enhancements

---
 boot.php                   |  28 ++++++-
 include/api.php            | 154 ++++++++++++++++++++++++++++++-------
 include/conversation.php   |  29 +------
 include/items.php          |   2 -
 view/api_timeline_atom.tpl |  47 ++---------
 5 files changed, 162 insertions(+), 98 deletions(-)

diff --git a/boot.php b/boot.php
index cdde7652c6..025f7ef878 100644
--- a/boot.php
+++ b/boot.php
@@ -1,6 +1,6 @@
 <?php
 
-define ( 'FRIENDIKA_VERSION',      '2.2.1057' );
+define ( 'FRIENDIKA_VERSION',      '2.2.1058' );
 define ( 'DFRN_PROTOCOL_VERSION',  '2.21'    );
 define ( 'DB_UPDATE_VERSION',      1076      );
 
@@ -2985,3 +2985,29 @@ function pkcs5_unpad($text)
     if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
     return substr($text, 0, -1 * $pad);
 } 
+
+
+if(! function_exists('load_contact_links')) {
+function load_contact_links($uid) {
+
+	$a = get_app();
+
+	$ret = array();
+
+	if(! $uid || x($a->contacts,'empty'))
+		return;
+
+	$r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 ",
+			intval($uid)
+	);
+	if(count($r)) {
+		foreach($r as $rr){
+			$url = normalise_link($rr['url']);
+			$ret[$url] = $rr;
+		}
+	}
+	else 
+		$ret['empty'] = true;	
+	$a->contacts = $ret;
+	return;		
+}}
diff --git a/include/api.php b/include/api.php
index b8dbdd2d32..62dc785064 100644
--- a/include/api.php
+++ b/include/api.php
@@ -10,7 +10,6 @@
 	$API = Array();
 	 
 
-	
 	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" );
@@ -111,7 +110,10 @@
 				if ($info['auth']===true && local_user()===false) {
 						api_login($a);
 				}
-		
+
+				load_contact_links(local_user());
+
+				logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);		
 				$type="json";		
 				if (strpos($a->query_string, ".xml")>0) $type="xml";
 				if (strpos($a->query_string, ".json")>0) $type="json";
@@ -157,7 +159,9 @@
 		$arr['$rss'] = array(
 			'alternate' => $user_info['url'],
 			'self' => $a->get_baseurl(). "/". $a->query_string,
+			'base' => $a->get_baseurl(),
 			'updated' => api_date(null),
+			'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
 			'language' => $user_info['language'],
 			'logo'	=> $a->get_baseurl()."/images/friendika-32.png",
 		);
@@ -277,8 +281,18 @@
 	}
 
 	function api_item_get_user(&$a, $item) {
-		if(link_compare($item['url'],$item['author-link']))
+		// The author is our direct contact, in a conversation with us.
+		if(link_compare($item['url'],$item['author-link'])) {
 			return api_get_user($a,$item['cid']);
+		}
+		else {
+			// The author may be a contact of ours, but is replying to somebody else. 
+			// Figure out if we know him/her.
+			$normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
+            if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
+				return api_get_user($a,$a->contacts[$normalised]['id']);
+		}
+		// We don't know this person directly.
 		$ret = array(
 			'uid' => 0,
 			'id' => 0,
@@ -290,7 +304,7 @@
 			'contact_url' => 0,
 			'protected' => false,	#
 			'friends_count' => 0,
-			'created_at' => '0000-00-00 00:00:00',
+			'created_at' => '',
 			'utc_offset' => 0, #XXX: fix me
 			'time_zone' => '', //$uinfo[0]['timezone'],
 			'geo_enabled' => false,
@@ -332,9 +346,11 @@
 	 */
 	function api_apply_template($templatename, $type, $data){
 
+		$a = get_app();
+
 		switch($type){
-			case "rss":
 			case "atom":
+			case "rss":
 			case "xml":
 				$data = api_xmlify($data);
 				$tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
@@ -527,7 +543,7 @@
 		
 		$user_info = api_get_user($a);
 		// get last newtork messages
-		$sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` ) ";
+//		$sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` ) ";
 
 		$r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
 			`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
@@ -539,10 +555,108 @@
 			AND `contact`.`id` = `item`.`contact-id`
 			AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
 			$sql_extra
-			ORDER BY `item`.`created` DESC LIMIT %d ,%d ",
+			ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
 			intval($user_info['uid']),
 			0,20
 		);
+
+		$ret = api_format_items($r,$user_info);
+
+		
+		$data = array('$statuses' => $ret);
+		switch($type){
+			case "atom":
+			case "rss":
+				$data = api_rss_extra($a, $data, $user_info);
+		}
+				
+		return  api_apply_template("timeline", $type, $data);
+	}
+	api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
+	api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
+
+
+
+	function api_statuses_user_timeline(&$a, $type){
+		if (local_user()===false) return false;
+		
+		$user_info = api_get_user($a);
+		// get last newtork messages
+//		$sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` ) ";
+
+		$r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
+			`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
+			`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
+			`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
+			FROM `item`, `contact`
+			WHERE `item`.`uid` = %d
+			AND `item`.`visible` = 1 AND `item`.`deleted` = 0
+			AND `item`.`wall` = 1
+			AND `contact`.`id` = `item`.`contact-id`
+			AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
+			$sql_extra
+			ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
+			intval($user_info['uid']),
+			0,20
+		);
+
+		$ret = api_format_items($r,$user_info);
+
+		
+		$data = array('$statuses' => $ret);
+		switch($type){
+			case "atom":
+			case "rss":
+				$data = api_rss_extra($a, $data, $user_info);
+		}
+				
+		return  api_apply_template("timeline", $type, $data);
+	}
+
+	api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
+
+
+	function api_favorites(&$a, $type){
+		if (local_user()===false) return false;
+		
+		$user_info = api_get_user($a);
+		// get last newtork messages
+//		$sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` ) ";
+
+		$r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
+			`contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
+			`contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
+			`contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
+			FROM `item`, `contact`
+			WHERE `item`.`uid` = %d
+			AND `item`.`visible` = 1 AND `item`.`deleted` = 0
+			AND `item`.`starred` = 1
+			AND `contact`.`id` = `item`.`contact-id`
+			AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
+			$sql_extra
+			ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
+			intval($user_info['uid']),
+			0,20
+		);
+
+		$ret = api_format_items($r,$user_info);
+
+		
+		$data = array('$statuses' => $ret);
+		switch($type){
+			case "atom":
+			case "rss":
+				$data = api_rss_extra($a, $data, $user_info);
+		}
+				
+		return  api_apply_template("timeline", $type, $data);
+	}
+
+	api_register_func('api/favorites','api_favorites', true);
+
+	
+	function api_format_items($r,$user_info) {
+		$a = get_app();
 		$ret = Array();
 
 		foreach($r as $item) {
@@ -551,7 +665,7 @@
 				'created_at'=> api_date($item['created']),
 				'published' => datetime_convert('UTC','UTC',$item['created'],ATOM_TIME),
 				'updated'   => datetime_convert('UTC','UTC',$item['edited'],ATOM_TIME),
-				'id'		=> $item['id'],
+				'id'		=> $item['uri'],
 				'text'		=> strip_tags(bbcode($item['body'])),
 				'html'		=> bbcode($item['body']),
 				'source'    => (($item['app']) ? $item['app'] : 'web'),
@@ -568,28 +682,16 @@
 				'annotations'  => '',
 				'entities'  => '',
 				'user' =>  $status_user ,
-				'objecttype' => $item['object-type'],
-				'verb' => $item['verb'],
-				'self' => $a->get_baseurl()."/api/statuses/show/".$ite['id'].".".$type,
-				'edit' => $a->get_baseurl()."/api/statuses/show/".$ite['id'].".".$type,				
+				'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
+				'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
+				'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
+				'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,				
 			);
 			$ret[]=$status;
 		};
-		
-		$data = array('$statuses' => $ret);
-		switch($type){
-			case "atom":
-			case "rss":
-				$data = api_rss_extra($a, $data, $user_info);
-		}
-				
-		return  api_apply_template("timeline", $type, $data);
+		return $ret;
 	}
-	api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
-	api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
-	api_register_func('api/statuses/user_timeline','api_statuses_home_timeline', true);
-	# TODO: user_timeline should be profile view
-	
+
 
 	function api_account_rate_limit_status(&$a,$type) {
 
diff --git a/include/conversation.php b/include/conversation.php
index 50032cd367..6b1f649250 100644
--- a/include/conversation.php
+++ b/include/conversation.php
@@ -444,7 +444,7 @@ function conversation(&$a, $items, $mode, $update) {
 				$profile_link = '';
 
 			$normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
-			if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
+			if(($normalised != 'mailbox') && (x($a->contacts,$normalised)))
 				$profile_avatar = $a->contacts[$normalised]['thumb'];
 			else
 				$profile_avatar = (((strlen($item['author-avatar'])) && $diff_author) ? $item['author-avatar'] : $thumb);
@@ -533,33 +533,6 @@ function conversation(&$a, $items, $mode, $update) {
 	return $o;
 } 
 
-
-if(! function_exists('load_contact_links')) {
-function load_contact_links($uid) {
-
-	$a = get_app();
-
-	$ret = array();
-
-	if(! $uid || x($a->contacts,'empty'))
-		return;
-
-	$r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 ",
-			intval($uid)
-	);
-	if(count($r)) {
-		foreach($r as $rr){
-			$url = normalise_link($rr['url']);
-			$ret[$url] = $rr;
-		}
-	}
-	else 
-		$ret['empty'] = true;	
-	$a->contacts = $ret;
-	return;		
-}}
-
-
 function best_link_url($item,&$sparkle) {
 
 	$a = get_app();
diff --git a/include/items.php b/include/items.php
index 014d758721..6d69c6cc9e 100644
--- a/include/items.php
+++ b/include/items.php
@@ -6,7 +6,6 @@ require_once('include/salmon.php');
 
 function get_feed_for(&$a, $dfrn_id, $owner_nick, $last_update, $direction = 0) {
 
-
 	// default permissions - anonymous user
 
 	if(! strlen($owner_nick))
@@ -485,7 +484,6 @@ function get_atom_elements($feed,$item) {
 	if((x($res,'verb')) && ($res['verb'] === 'http://ostatus.org/schema/1.0/unfollow'))
 		$res['verb'] = ACTIVITY_UNFOLLOW;
 
-
 	$cats = $item->get_categories();
 	if($cats) {
 		$tag_arr = array();
diff --git a/view/api_timeline_atom.tpl b/view/api_timeline_atom.tpl
index bd674f3302..dcabba465a 100644
--- a/view/api_timeline_atom.tpl
+++ b/view/api_timeline_atom.tpl
@@ -1,10 +1,10 @@
 <feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:georss="http://www.georss.org/georss" xmlns:activity="http://activitystrea.ms/spec/1.0/" xmlns:media="http://purl.org/syndication/atommedia" xmlns:poco="http://portablecontacts.net/spec/1.0" xmlns:ostatus="http://ostatus.org/schema/1.0" xmlns:statusnet="http://status.net/schema/api/1/">
  <generator uri="http://status.net" version="0.9.7">StatusNet</generator>
- <id>tag:friendika:PublicTimeline</id>
- <title>Network on Friendika</title>
- <subtitle>Your network updates on Friendika</subtitle>
+ <id>$rss.self</id>
+ <title>Friendika</title>
+ <subtitle>Friendika API feed</subtitle>
  <logo>$rss.logo</logo>
- <updated>$rss.updated</updated>
+ <updated>$rss.atom_updated</updated>
  <link type="text/html" rel="alternate" href="$rss.alternate"/>
  <link type="application/atom+xml" rel="self" href="$rss.self"/>
  
@@ -61,20 +61,9 @@
 		<published>$status.published</published>
 		<updated>$status.updated</updated>
 
-		<!--
-		<source>
-		<id>http://identi.ca/api/statuses/user_timeline/397830.atom</id>
-		<title>Sin Mobopolitan</title>
-		<link rel="alternate" type="text/html" href="http://identi.ca/mobopolitan"/>
-		<link rel="self" type="application/atom+xml" href="http://identi.ca/api/statuses/user_timeline/397830.atom"/>
-		<link rel="license" href="http://creativecommons.org/licenses/by/3.0/"/>
-		<icon>http://avatar.identi.ca/397830-96-20110312195623.jpeg</icon>
-		<updated>2011-04-21T18:39:32+00:00</updated>
-		</source>
-		-->
 		<link rel="self" type="application/atom+xml" href="$status.self"/>
 		<link rel="edit" type="application/atom+xml" href="$status.edit"/>
-		<statusnet:notice_info local_id="$status.id" source="$status.source" favorite="false" repeated="false">
+		<statusnet:notice_info local_id="$status.id" source="$status.source" >
 		</statusnet:notice_info>
 
 		<author>
@@ -82,10 +71,8 @@
 			<uri>$status.user.url</uri>
 			<name>$status.user.name</name>
 			<link rel="alternate" type="text/html" href="$status.user.url"/>
-			<link rel="avatar" type="image/jpeg" media:width="106" media:height="106" href="$status.user.profile_image_url"/>
-			<link rel="avatar" type="image/jpeg" media:width="96" media:height="96" href="$status.user.profile_image_url"/>
 			<link rel="avatar" type="image/jpeg" media:width="48" media:height="48" href="$status.user.profile_image_url"/>
-			<link rel="avatar" type="image/jpeg" media:width="24" media:height="24" href="$status.user.profile_image_url"/>
+
 			<georss:point/>
 			<poco:preferredUsername>$status.user.screen_name</poco:preferredUsername>
 			<poco:displayName>$status.user.name</poco:displayName>
@@ -95,29 +82,7 @@
 				<poco:value>$status.user.url</poco:value>
 				<poco:primary>true</poco:primary>
 			</poco:urls>
-			<!-- <statusnet:profile_info local_id="123710" following="true" blocking="false"></statusnet:profile_info> -->			
 		</author>
-		<!--Deprecation warning: activity:actor is present only for backward compatibility. It will be removed in the next version of StatusNet.-->
-		<activity:actor>
-			<activity:object-type>http://activitystrea.ms/schema/1.0/person</activity:object-type>
-			<id>$status.user.contact_url</id>
-			<title>$status.user.name</title>
-			<link rel="alternate" type="text/html" href="$status.user.url"/>
-			<link rel="avatar" type="image/jpeg" media:width="106" media:height="106" href="$status.user.profile_image_url"/>
-			<link rel="avatar" type="image/jpeg" media:width="96" media:height="96" href="$status.user.profile_image_url"/>
-			<link rel="avatar" type="image/jpeg" media:width="48" media:height="48" href="$status.user.profile_image_url"/>
-			<link rel="avatar" type="image/jpeg" media:width="24" media:height="24" href="$status.user.profile_image_url"/>
-			<georss:point/>
-			<poco:preferredUsername>$status.user.screen_name</poco:preferredUsername>
-			<poco:displayName>$status.user.name</poco:displayName>
-			<poco:address />
-			<poco:urls>
-				<poco:type>homepage</poco:type>
-				<poco:value>$status.user.url</poco:value>
-				<poco:primary>true</poco:primary>
-			</poco:urls>
-			<!-- <statusnet:profile_info local_id="123710" following="true" blocking="false"></statusnet:profile_info> -->
-		</activity:actor>
 		<link rel="ostatus:conversation" href="$status.url"/> 
 
 	</entry>