]> git.mxchange.org Git - friendica.git/blob - include/ostatus.php
Salmon: Don't store contact data before the message was authenticated.
[friendica.git] / include / ostatus.php
1 <?php
2 require_once("include/Contact.php");
3 require_once("include/threads.php");
4 require_once("include/html2bbcode.php");
5 require_once("include/items.php");
6 require_once("mod/share.php");
7 require_once("include/enotify.php");
8 require_once("include/socgraph.php");
9 require_once("include/Photo.php");
10
11 define('OSTATUS_DEFAULT_POLL_INTERVAL', 30); // given in minutes
12 define('OSTATUS_DEFAULT_POLL_TIMEFRAME', 1440); // given in minutes
13 define('OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS', 14400); // given in minutes
14
15 function ostatus_fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
16
17         $author = array();
18         $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
19         $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
20
21         // Preserve the value
22         $authorlink = $author["author-link"];
23
24         $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
25         if (is_object($alternate))
26                 foreach($alternate AS $attributes)
27                         if ($attributes->name == "href")
28                                 $author["author-link"] = $attributes->textContent;
29
30         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
31                 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
32                 dbesc(normalise_link($authorlink)), dbesc(NETWORK_STATUSNET));
33         if ($r) {
34                 $contact = $r[0];
35                 $author["contact-id"] = $r[0]["id"];
36         } else
37                 $author["contact-id"] = $contact["id"];
38
39         $avatarlist = array();
40         $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
41         foreach($avatars AS $avatar) {
42                 $href = "";
43                 $width = 0;
44                 foreach($avatar->attributes AS $attributes) {
45                         if ($attributes->name == "href")
46                                 $href = $attributes->textContent;
47                         if ($attributes->name == "width")
48                                 $width = $attributes->textContent;
49                 }
50                 if (($width > 0) AND ($href != ""))
51                         $avatarlist[$width] = $href;
52         }
53         if (count($avatarlist) > 0) {
54                 krsort($avatarlist);
55                 $author["author-avatar"] = current($avatarlist);
56         }
57
58         $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
59         if ($displayname != "")
60                 $author["author-name"] = $displayname;
61
62         $author["owner-name"] = $author["author-name"];
63         $author["owner-link"] = $author["author-link"];
64         $author["owner-avatar"] = $author["author-avatar"];
65
66         if ($r AND !$onlyfetch) {
67                 // Update contact data
68                 $update_contact = ($r[0]['name-date'] < datetime_convert('','','now -12 hours'));
69                 if ($update_contact) {
70                         logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
71
72                         $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
73                         if ($value != "")
74                                 $contact["name"] = $value;
75
76                         $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
77                         if ($value != "")
78                                 $contact["nick"] = $value;
79
80                         $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
81                         if ($value != "")
82                                 $contact["about"] = $value;
83
84                         $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
85                         if ($value != "")
86                                 $contact["location"] = $value;
87
88                         q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
89                                 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
90                                 dbesc(datetime_convert()), intval($contact["id"]));
91
92                         poco_check($contact["url"], $contact["name"], $contact["network"], $author["author-avatar"], $contact["about"], $contact["location"],
93                                         "", "", "", datetime_convert(), 2, $contact["id"], $contact["uid"]);
94                 }
95
96                 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
97
98                 if ($update_photo AND isset($author["author-avatar"])) {
99                         logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
100
101                         $photos = import_profile_photo($author["author-avatar"], $importer["uid"], $contact["id"]);
102
103                         q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' WHERE `id` = %d",
104                                 dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]),
105                                 dbesc(datetime_convert()), intval($contact["id"]));
106                 }
107         }
108
109         return($author);
110 }
111
112 function ostatus_salmon_author($xml, $importer) {
113         $a = get_app();
114
115         if ($xml == "")
116                 return;
117
118         $doc = new DOMDocument();
119         @$doc->loadXML($xml);
120
121         $xpath = new DomXPath($doc);
122         $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
123         $xpath->registerNamespace('thr', "http://purl.org/syndication/thread/1.0");
124         $xpath->registerNamespace('georss', "http://www.georss.org/georss");
125         $xpath->registerNamespace('activity', "http://activitystrea.ms/spec/1.0/");
126         $xpath->registerNamespace('media', "http://purl.org/syndication/atommedia");
127         $xpath->registerNamespace('poco', "http://portablecontacts.net/spec/1.0");
128         $xpath->registerNamespace('ostatus', "http://ostatus.org/schema/1.0");
129         $xpath->registerNamespace('statusnet', "http://status.net/schema/api/1/");
130
131         $entries = $xpath->query('/atom:entry');
132
133         foreach ($entries AS $entry) {
134                 // fetch the author
135                 $author = ostatus_fetchauthor($xpath, $entry, $importer, $contact, true);
136                 return $author;
137         }
138 }
139
140 function ostatus_import($xml,$importer,&$contact, &$hub) {
141
142         $a = get_app();
143
144         logger("Import OStatus message", LOGGER_DEBUG);
145
146         if ($xml == "")
147                 return;
148
149         $doc = new DOMDocument();
150         @$doc->loadXML($xml);
151
152         $xpath = new DomXPath($doc);
153         $xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");
154         $xpath->registerNamespace('thr', "http://purl.org/syndication/thread/1.0");
155         $xpath->registerNamespace('georss', "http://www.georss.org/georss");
156         $xpath->registerNamespace('activity', "http://activitystrea.ms/spec/1.0/");
157         $xpath->registerNamespace('media', "http://purl.org/syndication/atommedia");
158         $xpath->registerNamespace('poco', "http://portablecontacts.net/spec/1.0");
159         $xpath->registerNamespace('ostatus', "http://ostatus.org/schema/1.0");
160         $xpath->registerNamespace('statusnet', "http://status.net/schema/api/1/");
161
162         $gub = "";
163         $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
164         if (is_object($hub_attributes))
165                 foreach($hub_attributes AS $hub_attribute)
166                         if ($hub_attribute->name == "href") {
167                                 $hub = $hub_attribute->textContent;
168                                 logger("Found hub ".$hub, LOGGER_DEBUG);
169                         }
170
171         $header = array();
172         $header["uid"] = $importer["uid"];
173         $header["network"] = NETWORK_OSTATUS;
174         $header["type"] = "remote";
175         $header["wall"] = 0;
176         $header["origin"] = 0;
177         $header["gravity"] = GRAVITY_PARENT;
178
179         // it could either be a received post or a post we fetched by ourselves
180         // depending on that, the first node is different
181         $first_child = $doc->firstChild->tagName;
182
183         if ($first_child == "feed")
184                 $entries = $xpath->query('/atom:feed/atom:entry');
185         else
186                 $entries = $xpath->query('/atom:entry');
187
188         $conversation = "";
189         $conversationlist = array();
190         $item_id = 0;
191
192         // Reverse the order of the entries
193         $entrylist = array();
194
195         foreach ($entries AS $entry)
196                 $entrylist[] = $entry;
197
198         foreach (array_reverse($entrylist) AS $entry) {
199
200                 $mention = false;
201
202                 // fetch the author
203                 if ($first_child == "feed")
204                         $author = ostatus_fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
205                 else
206                         $author = ostatus_fetchauthor($xpath, $entry, $importer, $contact, false);
207
208                 $item = array_merge($header, $author);
209
210                 // Now get the item
211                 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
212
213                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
214                         intval($importer["uid"]), dbesc($item["uri"]));
215                 if ($r) {
216                         logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
217                         continue;
218                 }
219
220                 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
221                 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
222
223                 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
224                         $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
225                         $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
226                 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION)
227                         $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
228
229                 $item["object"] = $xml;
230                 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
231
232                 // To-Do:
233                 // Delete a message
234                 if ($item["verb"] == "qvitter-delete-notice") {
235                         // ignore "Delete" messages (by now)
236                         continue;
237                 }
238
239                 if ($item["verb"] == ACTIVITY_JOIN) {
240                         // ignore "Join" messages
241                         continue;
242                 }
243
244                 if ($item["verb"] == ACTIVITY_FOLLOW) {
245                         // ignore "Follow" messages
246                         // new_follower($importer,$contact,$datarray,$item);
247                         continue;
248                 }
249
250                 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
251                         // ignore "Unfollow" messages
252                         // lose_follower($importer,$contact,$datarray,$item);
253                         continue;
254                 }
255
256                 if ($item["verb"] == ACTIVITY_FAVORITE) {
257                         // ignore "Favorite" messages
258                         continue;
259                 }
260
261                 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
262                 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
263                 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
264
265                 $related = "";
266
267                 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
268                 if (is_object($inreplyto->item(0))) {
269                         foreach($inreplyto->item(0)->attributes AS $attributes) {
270                                 if ($attributes->name == "ref")
271                                         $item["parent-uri"] = $attributes->textContent;
272                                 if ($attributes->name == "href")
273                                         $related = $attributes->textContent;
274                         }
275                 }
276
277                 $georsspoint = $xpath->query('georss:point', $entry);
278                 if ($georsspoint)
279                         $item["coord"] = $georsspoint->item(0)->nodeValue;
280
281                 // To-Do
282                 // $item["location"] =
283
284                 $categories = $xpath->query('atom:category', $entry);
285                 if ($categories) {
286                         foreach ($categories AS $category) {
287                                 foreach($category->attributes AS $attributes)
288                                         if ($attributes->name == "term") {
289                                                 $term = $attributes->textContent;
290                                                 if(strlen($item["tag"]))
291                                                         $item["tag"] .= ',';
292                                                 $item["tag"] .= "#[url=".$a->get_baseurl()."/search?tag=".$term."]".$term."[/url]";
293                                         }
294                         }
295                 }
296
297                 $self = "";
298                 $enclosure = "";
299
300                 $links = $xpath->query('atom:link', $entry);
301                 if ($links) {
302                         $rel = "";
303                         $href = "";
304                         $type = "";
305                         $length = "0";
306                         $title = "";
307                         foreach ($links AS $link) {
308                                 foreach($link->attributes AS $attributes) {
309                                         if ($attributes->name == "href")
310                                                 $href = $attributes->textContent;
311                                         if ($attributes->name == "rel")
312                                                 $rel = $attributes->textContent;
313                                         if ($attributes->name == "type")
314                                                 $type = $attributes->textContent;
315                                         if ($attributes->name == "length")
316                                                 $length = $attributes->textContent;
317                                         if ($attributes->name == "title")
318                                                 $title = $attributes->textContent;
319                                 }
320                                 if (($rel != "") AND ($href != ""))
321                                         switch($rel) {
322                                                 case "alternate":
323                                                         $item["plink"] = $href;
324                                                         if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
325                                                                 ($item["object-type"] == ACTIVITY_OBJ_EVENT))
326                                                                 $item["body"] .= add_page_info($href);
327                                                         break;
328                                                 case "ostatus:conversation":
329                                                         $conversation = $href;
330                                                         break;
331                                                 case "enclosure":
332                                                         $enclosure = $href;
333                                                         if(strlen($item["attach"]))
334                                                                 $item["attach"] .= ',';
335
336                                                         $item["attach"] .= '[attach]href="'.$href.'" length="'.$length.'" type="'.$type.'" title="'.$title.'"[/attach]';
337                                                         break;
338                                                 case "related":
339                                                         if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
340                                                                 if (!isset($item["parent-uri"]))
341                                                                         $item["parent-uri"] = $href;
342
343                                                                 if ($related == "")
344                                                                         $related = $href;
345                                                         } else
346                                                                 $item["body"] .= add_page_info($href);
347                                                         break;
348                                                 case "self":
349                                                         $self = $href;
350                                                         break;
351                                                 case "mentioned":
352                                                         // Notification check
353                                                         if ($importer["nurl"] == normalise_link($href))
354                                                                 $mention = true;
355                                                         break;
356                                         }
357                         }
358                 }
359
360                 $local_id = "";
361                 $repeat_of = "";
362
363                 $notice_info = $xpath->query('statusnet:notice_info', $entry);
364                 if ($notice_info AND ($notice_info->length > 0)) {
365                         foreach($notice_info->item(0)->attributes AS $attributes) {
366                                 if ($attributes->name == "source")
367                                         $item["app"] = strip_tags($attributes->textContent);
368                                 if ($attributes->name == "local_id")
369                                         $local_id = $attributes->textContent;
370                                 if ($attributes->name == "repeat_of")
371                                         $repeat_of = $attributes->textContent;
372                         }
373                 }
374
375                 // Is it a repeated post?
376                 if ($repeat_of != "") {
377                         $activityobjects = $xpath->query('activity:object', $entry)->item(0);
378
379                         if (is_object($activityobjects)) {
380
381                                 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
382                                 if (!isset($orig_uri))
383                                         $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
384
385                                 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
386                                 if ($orig_links AND ($orig_links->length > 0))
387                                         foreach($orig_links->item(0)->attributes AS $attributes)
388                                                 if ($attributes->name == "href")
389                                                         $orig_link = $attributes->textContent;
390
391                                 if (!isset($orig_link))
392                                         $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
393
394                                 if (!isset($orig_link))
395                                         $orig_link =  ostatus_convert_href($orig_uri);
396
397                                 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
398                                 if (!isset($orig_body))
399                                         $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
400
401                                 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
402
403                                 $orig_contact = $contact;
404                                 $orig_author = ostatus_fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
405
406                                 //if (!intval(get_config('system','wall-to-wall_share'))) {
407                                 //      $prefix = share_header($orig_author['author-name'], $orig_author['author-link'], $orig_author['author-avatar'], "", $orig_created, $orig_link);
408                                 //      $item["body"] = $prefix.add_page_info_to_body(html2bbcode($orig_body))."[/share]";
409                                 //} else {
410                                         $item["author-name"] = $orig_author["author-name"];
411                                         $item["author-link"] = $orig_author["author-link"];
412                                         $item["author-avatar"] = $orig_author["author-avatar"];
413                                         $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
414                                         $item["created"] = $orig_created;
415
416                                         $item["uri"] = $orig_uri;
417                                         $item["plink"] = $orig_link;
418                                 //}
419
420                                 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
421
422                                 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
423                                 if (!isset($item["object-type"]))
424                                         $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
425                         }
426                 }
427
428                 //if ($enclosure != "")
429                 //      $item["body"] .= add_page_info($enclosure);
430
431                 if (isset($item["parent-uri"])) {
432                         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
433                                 intval($importer["uid"]), dbesc($item["parent-uri"]));
434
435                         if (!$r AND ($related != "")) {
436                                 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
437
438                                 if ($reply_path != $related) {
439                                         logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
440                                         $reply_xml = fetch_url($reply_path);
441
442                                         $reply_contact = $contact;
443                                         ostatus_import($reply_xml,$importer,$reply_contact, $reply_hub);
444
445                                         // After the import try to fetch the parent item again
446                                         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
447                                                 intval($importer["uid"]), dbesc($item["parent-uri"]));
448                                 }
449                         }
450                         if ($r) {
451                                 $item["type"] = 'remote-comment';
452                                 $item["gravity"] = GRAVITY_COMMENT;
453                         }
454                 } else
455                         $item["parent-uri"] = $item["uri"];
456
457                 $item_id = ostatus_completion($conversation, $importer["uid"], $item);
458
459                 if (!$item_id) {
460                         logger("Error storing item", LOGGER_DEBUG);
461                         continue;
462                 }
463
464                 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
465                 $item["id"] = $item_id;
466
467                 if ($mention) {
468                         $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($item['uid']));
469                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($item_id));
470
471                         notification(array(
472                                 'type'         => NOTIFY_TAGSELF,
473                                 'notify_flags' => $u[0]["notify-flags"],
474                                 'language'     => $u[0]["language"],
475                                 'to_name'      => $u[0]["username"],
476                                 'to_email'     => $u[0]["email"],
477                                 'uid'          => $item["uid"],
478                                 'item'         => $item,
479                                 'link'         => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item_id)),
480                                 'source_name'  => $item["author-name"],
481                                 'source_link'  => $item["author-link"],
482                                 'source_photo' => $item["author-avatar"],
483                                 'verb'         => ACTIVITY_TAG,
484                                 'otype'        => 'item',
485                                 'parent'       => $r[0]["parent"]
486                         ));
487                 }
488         }
489 }
490
491 function ostatus_convert_href($href) {
492         $elements = explode(":",$href);
493
494         if ((count($elements) <= 2) OR ($elements[0] != "tag"))
495                 return $href;
496
497         $server = explode(",", $elements[1]);
498         $conversation = explode("=", $elements[2]);
499
500         if ((count($elements) == 4) AND ($elements[2] == "post"))
501                 return "http://".$server[0]."/notice/".$elements[3];
502
503         if ((count($conversation) != 2) OR ($conversation[1] ==""))
504                 return $href;
505
506         if ($elements[3] == "objectType=thread")
507                 return "http://".$server[0]."/conversation/".$conversation[1];
508         else
509                 return "http://".$server[0]."/notice/".$conversation[1];
510
511         return $href;
512 }
513
514 function check_conversations($mentions = false, $override = false) {
515         $last = get_config('system','ostatus_last_poll');
516
517         $poll_interval = intval(get_config('system','ostatus_poll_interval'));
518         if(! $poll_interval)
519                 $poll_interval = OSTATUS_DEFAULT_POLL_INTERVAL;
520
521         // Don't poll if the interval is set negative
522         if (($poll_interval < 0) AND !$override)
523                 return;
524
525         if (!$mentions) {
526                 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
527                 if (!$poll_timeframe)
528                         $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME;
529         } else {
530                 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
531                 if (!$poll_timeframe)
532                         $poll_timeframe = OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
533         }
534
535
536         if ($last AND !$override) {
537                 $next = $last + ($poll_interval * 60);
538                 if ($next > time()) {
539                         logger('poll interval not reached');
540                         return;
541                 }
542         }
543
544         logger('cron_start');
545
546         $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
547
548         if ($mentions)
549                 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
550                                         STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
551                                         WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
552                                         GROUP BY `term`.`url`, `term`.`uid` ORDER BY `term`.`term` DESC", dbesc($start));
553         else
554                 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
555                                         WHERE `type` = 7 AND `term` > '%s'
556                                         GROUP BY `url`, `uid` ORDER BY `term` DESC", dbesc($start));
557
558         foreach ($conversations AS $conversation) {
559                 ostatus_completion($conversation['url'], $conversation['uid']);
560         }
561
562         logger('cron_end');
563
564         set_config('system','ostatus_last_poll', time());
565 }
566
567 function ostatus_completion($conversation_url, $uid, $item = array()) {
568
569         $a = get_app();
570
571         $item_stored = -1;
572
573         $conversation_url = ostatus_convert_href($conversation_url);
574
575         // If the thread shouldn't be completed then store the item and go away
576         if ((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) {
577                 //$arr["app"] .= " (OStatus-NoCompletion)";
578                 $item_stored = item_store($item, true);
579                 return($item_stored);
580         }
581
582         // Get the parent
583         $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
584                         (SELECT `parent` FROM `item` WHERE `id` IN
585                                 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
586                         intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
587
588         if ($parents)
589                 $parent = $parents[0];
590         elseif (count($item) > 0) {
591                 $parent = $item;
592                 $parent["type"] = "remote";
593                 $parent["verb"] = ACTIVITY_POST;
594                 $parent["visible"] = 1;
595         } else {
596                 // Preset the parent
597                 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
598                 if (!$r)
599                         return(-2);
600
601                 $parent = array();
602                 $parent["id"] = 0;
603                 $parent["parent"] = 0;
604                 $parent["uri"] = "";
605                 $parent["contact-id"] = $r[0]["id"];
606                 $parent["type"] = "remote";
607                 $parent["verb"] = ACTIVITY_POST;
608                 $parent["visible"] = 1;
609         }
610
611         $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
612         $pageno = 1;
613         $items = array();
614
615         logger('fetching conversation url '.$conv.' for user '.$uid);
616
617         do {
618                 $conv_arr = z_fetch_url($conv."?page=".$pageno);
619
620                 // If it is a non-ssl site and there is an error, then try ssl or vice versa
621                 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
622                         $conv = str_replace("http://", "https://", $conv);
623                         $conv_as = fetch_url($conv."?page=".$pageno);
624                 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
625                         $conv = str_replace("https://", "http://", $conv);
626                         $conv_as = fetch_url($conv."?page=".$pageno);
627                 } else
628                         $conv_as = $conv_arr["body"];
629
630                 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
631                 $conv_as = json_decode($conv_as);
632
633                 if (@is_array($conv_as->items))
634                         $items = array_merge($items, $conv_as->items);
635                 else
636                         break;
637
638                 $pageno++;
639
640         } while (true);
641
642         logger('fetching conversation done. Found '.count($items).' items');
643
644         if (!sizeof($items)) {
645                 if (count($item) > 0) {
646                         //$arr["app"] .= " (OStatus-NoConvFetched)";
647                         $item_stored = item_store($item, true);
648
649                         if ($item_stored) {
650                                 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
651                                 ostatus_store_conversation($item_id, $conversation_url);
652                         }
653
654                         return($item_stored);
655                 } else
656                         return(-3);
657         }
658
659         $items = array_reverse($items);
660
661         $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
662         $importer = $r[0];
663
664         foreach ($items as $single_conv) {
665
666                 // Test - remove before flight
667                 //$tempfile = tempnam(get_temppath(), "conversation");
668                 //file_put_contents($tempfile, json_encode($single_conv));
669
670                 $mention = false;
671
672                 if (isset($single_conv->object->id))
673                         $single_conv->id = $single_conv->object->id;
674
675                 $plink = ostatus_convert_href($single_conv->id);
676                 if (isset($single_conv->object->url))
677                         $plink = ostatus_convert_href($single_conv->object->url);
678
679                 if (@!$single_conv->id)
680                         continue;
681
682                 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
683
684                 if ($first_id == "") {
685                         $first_id = $single_conv->id;
686
687                         // The first post of the conversation isn't our first post. There are three options:
688                         // 1. Our conversation hasn't the "real" thread starter
689                         // 2. This first post is a post inside our thread
690                         // 3. This first post is a post inside another thread
691                         if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
692                                 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
693                                                         (SELECT `parent` FROM `item`
694                                                                 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
695                                         intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
696                                 if ($new_parents) {
697                                         if ($new_parents[0]["parent"] == $parent["parent"]) {
698                                                 // Option 2: This post is already present inside our thread - but not as thread starter
699                                                 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
700                                                 $first_id = $parent["uri"];
701                                         } else {
702                                                 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
703                                                 // For now just take the new parent.
704                                                 $parent = $new_parents[0];
705                                                 $first_id = $parent["uri"];
706                                                 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
707                                         }
708                                 } else {
709                                         // Option 1: We hadn't got the real thread starter
710                                         // We have to clean up our existing messages.
711                                         $parent["id"] = 0;
712                                         $parent["uri"] = $first_id;
713                                         logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
714                                 }
715                         } elseif ($parent["uri"] == "") {
716                                 $parent["id"] = 0;
717                                 $parent["uri"] = $first_id;
718                         }
719                 }
720
721                 $parent_uri = $parent["uri"];
722
723                 // "context" only seems to exist on older servers
724                 if (isset($single_conv->context->inReplyTo->id)) {
725                         $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
726                                                 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
727                         if ($parent_exists)
728                                 $parent_uri = $single_conv->context->inReplyTo->id;
729                 }
730
731                 // This is the current way
732                 if (isset($single_conv->object->inReplyTo->id)) {
733                         $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
734                                                 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
735                         if ($parent_exists)
736                                 $parent_uri = $single_conv->object->inReplyTo->id;
737                 }
738
739                 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
740                                                 intval($uid), dbesc($single_conv->id),
741                                                 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
742                 if ($message_exists) {
743                         logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
744
745                         if ($parent["id"] != 0) {
746                                 $existing_message = $message_exists[0];
747
748                                 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
749                                 // To-Do: we have to change the shadow copies as well. This way here is really ugly.
750                                 if ($existing_message["parent"] != $parent["id"]) {
751                                         logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
752
753                                         // Update the parent id of the selected item
754                                         $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
755                                                 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
756
757                                         // Update the parent uri in the thread - but only if it points to itself
758                                         $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
759                                                 dbesc($parent_uri), intval($existing_message["id"]));
760
761                                         // try to change all items of the same parent
762                                         $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
763                                                 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
764
765                                         // Update the parent uri in the thread - but only if it points to itself
766                                         $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
767                                                 dbesc($parent["uri"]), intval($existing_message["parent"]));
768
769                                         // Now delete the thread
770                                         delete_thread($existing_message["parent"]);
771                                 }
772                         }
773
774                         // The item we are having on the system is the one that we wanted to store via the item array
775                         if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
776                                 $item = array();
777                                 $item_stored = 0;
778                         }
779
780                         continue;
781                 }
782
783                 if (is_array($single_conv->to))
784                         foreach($single_conv->to AS $to)
785                                 if ($importer["nurl"] == normalise_link($to->id))
786                                         $mention = true;
787
788                 $actor = $single_conv->actor->id;
789                 if (isset($single_conv->actor->url))
790                         $actor = $single_conv->actor->url;
791
792                 $contact = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
793                                 $uid, normalise_link($actor), NETWORK_STATUSNET);
794
795                 if (count($contact)) {
796                         logger("Found contact for url ".$actor, LOGGER_DEBUG);
797                         $contact_id = $contact[0]["id"];
798                 } else {
799                         logger("No contact found for url ".$actor, LOGGER_DEBUG);
800
801                         // Adding a global contact
802                         // To-Do: Use this data for the post
803                         $global_contact_id = get_contact($actor, 0);
804
805                         logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
806
807                         $contact_id = $parent["contact-id"];
808                 }
809
810                 $arr = array();
811                 $arr["network"] = NETWORK_OSTATUS;
812                 $arr["uri"] = $single_conv->id;
813                 $arr["plink"] = $plink;
814                 $arr["uid"] = $uid;
815                 $arr["contact-id"] = $contact_id;
816                 $arr["parent-uri"] = $parent_uri;
817                 $arr["created"] = $single_conv->published;
818                 $arr["edited"] = $single_conv->published;
819                 $arr["owner-name"] = $single_conv->actor->displayName;
820                 if ($arr["owner-name"] == '')
821                         $arr["owner-name"] = $single_conv->actor->contact->displayName;
822                 if ($arr["owner-name"] == '')
823                         $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
824
825                 $arr["owner-link"] = $actor;
826                 $arr["owner-avatar"] = $single_conv->actor->image->url;
827                 $arr["author-name"] = $arr["owner-name"];
828                 $arr["author-link"] = $actor;
829                 $arr["author-avatar"] = $single_conv->actor->image->url;
830                 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
831
832                 if (isset($single_conv->status_net->notice_info->source))
833                         $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
834                 elseif (isset($single_conv->statusnet->notice_info->source))
835                         $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
836                 elseif (isset($single_conv->statusnet_notice_info->source))
837                         $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
838                 elseif (isset($single_conv->provider->displayName))
839                         $arr["app"] = $single_conv->provider->displayName;
840                 else
841                         $arr["app"] = "OStatus";
842
843                 //$arr["app"] .= " (Conversation)";
844
845                 $arr["object"] = json_encode($single_conv);
846                 $arr["verb"] = $parent["verb"];
847                 $arr["visible"] = $parent["visible"];
848                 $arr["location"] = $single_conv->location->displayName;
849                 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
850
851                 // Is it a reshared item?
852                 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
853                         if (is_array($single_conv->object))
854                                 $single_conv->object = $single_conv->object[0];
855
856                         logger("Found reshared item ".$single_conv->object->id);
857
858                         // $single_conv->object->context->conversation;
859
860                         if (isset($single_conv->object->object->id))
861                                 $arr["uri"] = $single_conv->object->object->id;
862                         else
863                                 $arr["uri"] = $single_conv->object->id;
864
865                         if (isset($single_conv->object->object->url))
866                                 $plink = ostatus_convert_href($single_conv->object->object->url);
867                         else
868                                 $plink = ostatus_convert_href($single_conv->object->url);
869
870                         if (isset($single_conv->object->object->content))
871                                 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
872                         else
873                                 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
874
875                         $arr["plink"] = $plink;
876
877                         $arr["created"] = $single_conv->object->published;
878                         $arr["edited"] = $single_conv->object->published;
879
880                         $arr["author-name"] = $single_conv->object->actor->displayName;
881                         if ($arr["owner-name"] == '')
882                                 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
883
884                         $arr["author-link"] = $single_conv->object->actor->url;
885                         $arr["author-avatar"] = $single_conv->object->actor->image->url;
886
887                         $arr["app"] = $single_conv->object->provider->displayName."#";
888                         //$arr["verb"] = $single_conv->object->verb;
889
890                         $arr["location"] = $single_conv->object->location->displayName;
891                         $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
892                 }
893
894                 if ($arr["location"] == "")
895                         unset($arr["location"]);
896
897                 if ($arr["coord"] == "")
898                         unset($arr["coord"]);
899
900                 // Copy fields from given item array
901                 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] ==  $single_conv->id))) {
902                         $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
903                                                 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
904                                                 "title", "attach", "app", "type", "location", "contact-id", "uri");
905                         foreach ($copy_fields AS $field)
906                                 if (isset($item[$field]))
907                                         $arr[$field] = $item[$field];
908
909                         //$arr["app"] .= " (OStatus)";
910                 }
911
912                 $newitem = item_store($arr);
913                 if (!$newitem) {
914                         logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
915                         continue;
916                 }
917
918                 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
919                         $item = array();
920                         $item_stored = $newitem;
921                 }
922
923                 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
924
925                 // Add the conversation entry (but don't fetch the whole conversation)
926                 ostatus_store_conversation($newitem, $conversation_url);
927
928                 if ($mention) {
929                         $u = q("SELECT `notify-flags`, `language`, `username`, `email` FROM user WHERE uid = %d LIMIT 1", intval($uid));
930                         $r = q("SELECT `parent` FROM `item` WHERE `id` = %d", intval($newitem));
931
932                         notification(array(
933                                 'type'         => NOTIFY_TAGSELF,
934                                 'notify_flags' => $u[0]["notify-flags"],
935                                 'language'     => $u[0]["language"],
936                                 'to_name'      => $u[0]["username"],
937                                 'to_email'     => $u[0]["email"],
938                                 'uid'          => $uid,
939                                 'item'         => $arr,
940                                 'link'         => $a->get_baseurl().'/display/'.urlencode(get_item_guid($newitem)),
941                                 'source_name'  => $arr["author-name"],
942                                 'source_link'  => $arr["author-link"],
943                                 'source_photo' => $arr["author-avatar"],
944                                 'verb'         => ACTIVITY_TAG,
945                                 'otype'        => 'item',
946                                 'parent'       => $r[0]["parent"]
947                         ));
948                 }
949
950                 // If the newly created item is the top item then change the parent settings of the thread
951                 // This shouldn't happen anymore. This is supposed to be absolote.
952                 if ($arr["uri"] == $first_id) {
953                         logger('setting new parent to id '.$newitem);
954                         $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
955                                 intval($uid), intval($newitem));
956                         if ($new_parents)
957                                 $parent = $new_parents[0];
958                 }
959         }
960
961         if (($item_stored < 0) AND (count($item) > 0)) {
962                 //$arr["app"] .= " (OStatus-NoConvFound)";
963                 $item_stored = item_store($item, true);
964                 if ($item_stored) {
965                         logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
966                         ostatus_store_conversation($item_stored, $conversation_url);
967                 }
968         }
969
970         return($item_stored);
971 }
972
973 function ostatus_store_conversation($itemid, $conversation_url) {
974         global $a;
975
976         $conversation_url = ostatus_convert_href($conversation_url);
977
978         $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
979         if (!$messages)
980                 return;
981         $message = $messages[0];
982
983         // Store conversation url if not done before
984         $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
985                 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
986
987         if (!$conversation) {
988                 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
989                         intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
990                         dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
991                 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
992         }
993 }
994 ?>