]> git.mxchange.org Git - friendica.git/blob - include/diaspora2.php
Likes would now work with unlikes and with likes on comments.
[friendica.git] / include / diaspora2.php
1 <?php
2 /**
3  * @file include/diaspora.php
4  * @brief The implementation of the diaspora protocol
5  */
6
7 require_once("include/items.php");
8 require_once("include/bb2diaspora.php");
9 require_once("include/Scrape.php");
10 require_once("include/Contact.php");
11 require_once("include/Photo.php");
12 require_once("include/socgraph.php");
13 require_once("include/group.php");
14 require_once("include/api.php");
15
16 class xml {
17         function from_array($array, &$xml) {
18
19                 if (!is_object($xml)) {
20                         foreach($array as $key => $value) {
21                                 $root = new SimpleXMLElement('<'.$key.'/>');
22                                 array_to_xml($value, $root);
23
24                                 $dom = dom_import_simplexml($root)->ownerDocument;
25                                 $dom->formatOutput = true;
26                                 return $dom->saveXML();
27                         }
28                 }
29
30                 foreach($array as $key => $value) {
31                         if (!is_array($value) AND !is_numeric($key))
32                                 $xml->addChild($key, $value);
33                         elseif (is_array($value))
34                                 array_to_xml($value, $xml->addChild($key));
35                 }
36         }
37
38         function copy(&$source, &$target, $elementname) {
39                 if (count($source->children()) == 0)
40                         $target->addChild($elementname, $source);
41                 else {
42                         $child = $target->addChild($elementname);
43                         foreach ($source->children() AS $childfield => $childentry)
44                                 self::copy($childentry, $child, $childfield);
45                 }
46         }
47 }
48 /**
49  * @brief This class contain functions to create and send Diaspora XML files
50  *
51  */
52 class diaspora {
53
54         public static function dispatch_public($msg) {
55
56                 $enabled = intval(get_config("system", "diaspora_enabled"));
57                 if (!$enabled) {
58                         logger("diaspora is disabled");
59                         return false;
60                 }
61
62                 // Use a dummy importer to import the data for the public copy
63                 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
64                 $item_id = self::dispatch($importer,$msg);
65
66                 // Now distribute it to the followers
67                 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
68                         (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
69                         AND NOT `account_expired` AND NOT `account_removed`",
70                         dbesc(NETWORK_DIASPORA),
71                         dbesc($msg["author"])
72                 );
73                 if(count($r)) {
74                         foreach($r as $rr) {
75                                 logger("delivering to: ".$rr["username"]);
76                                 self::dispatch($rr,$msg);
77                         }
78                 } else
79                         logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
80
81                 return $item_id;
82         }
83
84         public static function dispatch($importer, $msg) {
85
86                 // The sender is the handle of the contact that sent the message.
87                 // This will often be different with relayed messages (for example "like" and "comment")
88                 $sender = $msg["author"];
89
90                 if (!diaspora::valid_posting($msg, $fields)) {
91                         logger("Invalid posting");
92                         return false;
93                 }
94
95                 $type = $fields->getName();
96
97                 switch ($type) {
98                         case "account_deletion":
99                                 return true;
100                                 //return self::import_account_deletion($importer, $fields);
101
102                         case "comment":
103                                 return true;
104                                 //return self::import_comment($importer, $sender, $fields);
105
106                         case "conversation":
107                                 return true;
108                                 //return self::import_conversation($importer, $fields);
109
110                         case "like":
111                                 return true;
112                                 //return self::import_like($importer, $sender, $fields);
113
114                         case "message":
115                                 return true;
116                                 //return self::import_message($importer, $fields);
117
118                         case "participation": // Not implemented
119                                 return self::import_participation($importer, $fields);
120
121                         case "photo":
122                                 return self::import_photo($importer, $fields);
123
124                         case "poll_participation": // Not implemented
125                                 return self::import_poll_participation($importer, $fields);
126
127                         case "profile":
128                                 return true;
129                                 //return self::import_profile($importer, $fields);
130
131                         case "request":
132                                 return self::import_request($importer, $fields);
133
134                         case "reshare":
135                                 return true;
136                                 //return self::import_reshare($importer, $fields);
137
138                         case "retraction":
139                                 return self::import_retraction($importer, $fields);
140
141                         case "status_message":
142                                 //return true;
143                                 return self::import_status_message($importer, $fields);
144
145                         default:
146                                 logger("Unknown message type ".$type);
147                                 return false;
148                 }
149
150                 return true;
151         }
152
153         /**
154          * @brief Checks if a posting is valid and fetches the data fields.
155          *
156          * This function does not only check the signature.
157          * It also does the conversion between the old and the new diaspora format.
158          *
159          * @param array $msg Array with the XML, the sender handle and the sender signature
160          * @param object $fields SimpleXML object that contains the posting when it is valid
161          *
162          * @return bool Is the posting valid?
163          */
164         private function valid_posting($msg, &$fields) {
165
166                 $data = parse_xml_string($msg["message"], false);
167
168                 if (!is_object($data))
169                         return false;
170
171                 $first_child = $data->getName();
172
173                 // Is this the new or the old version?
174                 if ($data->getName() == "XML") {
175                         $oldXML = true;
176                         foreach ($data->post->children() as $child)
177                                 $element = $child;
178                 } else {
179                         $oldXML = false;
180                         $element = $data;
181                 }
182
183                 $type = $element->getName();
184
185                 // All retractions are handled identically from now on.
186                 // In the new version there will only be "retraction".
187                 if (in_array($type, array("signed_retraction", "relayable_retraction")))
188                         $type = "retraction";
189
190                 $fields = new SimpleXMLElement("<".$type."/>");
191
192                 $signed_data = "";
193
194                 foreach ($element->children() AS $fieldname => $entry) {
195                         if ($oldXML) {
196                                 // Translation for the old XML structure
197                                 if ($fieldname == "diaspora_handle")
198                                         $fieldname = "author";
199
200                                 if ($fieldname == "participant_handles")
201                                         $fieldname = "participants";
202
203                                 if (in_array($type, array("like", "participation"))) {
204                                         if ($fieldname == "target_type")
205                                                 $fieldname = "parent_type";
206                                 }
207
208                                 if ($fieldname == "sender_handle")
209                                         $fieldname = "author";
210
211                                 if ($fieldname == "recipient_handle")
212                                         $fieldname = "recipient";
213
214                                 if ($fieldname == "root_diaspora_id")
215                                         $fieldname = "root_author";
216
217                                 if ($type == "retraction") {
218                                         if ($fieldname == "post_guid")
219                                                 $fieldname = "target_guid";
220
221                                         if ($fieldname == "type")
222                                                 $fieldname = "target_type";
223                                 }
224                         }
225
226                         if ($fieldname == "author_signature")
227                                 $author_signature = base64_decode($entry);
228                         elseif ($fieldname == "parent_author_signature")
229                                 $parent_author_signature = base64_decode($entry);
230                         elseif ($fieldname != "target_author_signature") {
231                                 if ($signed_data != "") {
232                                         $signed_data .= ";";
233                                         $signed_data_parent .= ";";
234                                 }
235
236                                 $signed_data .= $entry;
237                         }
238                         if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")))
239                                 xml::copy($entry, $fields, $fieldname);
240                 }
241
242                 // This is something that shouldn't happen at all.
243                 if (in_array($type, array("status_message", "reshare", "profile")))
244                         if ($msg["author"] != $fields->author) {
245                                 logger("Message handle is not the same as envelope sender. Quitting this message.");
246                                 return false;
247                         }
248
249                 // Only some message types have signatures. So we quit here for the other types.
250                 if (!in_array($type, array("comment", "message", "like")))
251                         return true;
252
253                 // No author_signature? This is a must, so we quit.
254                 if (!isset($author_signature))
255                         return false;
256
257                 if (isset($parent_author_signature)) {
258                         $key = self::get_key($msg["author"]);
259
260                         if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
261                                 return false;
262                 }
263
264                 $key = self::get_key($fields->author);
265
266                 return rsa_verify($signed_data, $author_signature, $key, "sha256");
267         }
268
269         private function get_key($handle) {
270                 logger("Fetching diaspora key for: ".$handle);
271
272                 $r = self::get_person_by_handle($handle);
273                 if($r)
274                         return $r["pubkey"];
275
276                 return "";
277         }
278
279         private function get_person_by_handle($handle) {
280
281                 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
282                         dbesc(NETWORK_DIASPORA),
283                         dbesc($handle)
284                 );
285                 if (count($r)) {
286                         $person = $r[0];
287                         logger("In cache ".print_r($r,true), LOGGER_DEBUG);
288
289                         // update record occasionally so it doesn't get stale
290                         $d = strtotime($person["updated"]." +00:00");
291                         if ($d < strtotime("now - 14 days"))
292                                 $update = true;
293                 }
294
295                 if (!$person OR $update) {
296                         logger("create or refresh", LOGGER_DEBUG);
297                         $r = probe_url($handle, PROBE_DIASPORA);
298
299                         // Note that Friendica contacts will return a "Diaspora person"
300                         // if Diaspora connectivity is enabled on their server
301                         if (count($r) AND ($r["network"] === NETWORK_DIASPORA)) {
302                                 self::add_fcontact($r, $update);
303                                 $person = $r;
304                         }
305                 }
306                 return $person;
307         }
308
309         private function add_fcontact($arr, $update = false) {
310                 /// @todo Remove this function from include/network.php
311
312                 if($update) {
313                         $r = q("UPDATE `fcontact` SET
314                                         `name` = '%s',
315                                         `photo` = '%s',
316                                         `request` = '%s',
317                                         `nick` = '%s',
318                                         `addr` = '%s',
319                                         `batch` = '%s',
320                                         `notify` = '%s',
321                                         `poll` = '%s',
322                                         `confirm` = '%s',
323                                         `alias` = '%s',
324                                         `pubkey` = '%s',
325                                         `updated` = '%s'
326                                 WHERE `url` = '%s' AND `network` = '%s'",
327                                         dbesc($arr["name"]),
328                                         dbesc($arr["photo"]),
329                                         dbesc($arr["request"]),
330                                         dbesc($arr["nick"]),
331                                         dbesc($arr["addr"]),
332                                         dbesc($arr["batch"]),
333                                         dbesc($arr["notify"]),
334                                         dbesc($arr["poll"]),
335                                         dbesc($arr["confirm"]),
336                                         dbesc($arr["alias"]),
337                                         dbesc($arr["pubkey"]),
338                                         dbesc(datetime_convert()),
339                                         dbesc($arr["url"]),
340                                         dbesc($arr["network"])
341                                 );
342                 } else {
343                         $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
344                                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
345                                 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
346                                         dbesc($arr["url"]),
347                                         dbesc($arr["name"]),
348                                         dbesc($arr["photo"]),
349                                         dbesc($arr["request"]),
350                                         dbesc($arr["nick"]),
351                                         dbesc($arr["addr"]),
352                                         dbesc($arr["batch"]),
353                                         dbesc($arr["notify"]),
354                                         dbesc($arr["poll"]),
355                                         dbesc($arr["confirm"]),
356                                         dbesc($arr["network"]),
357                                         dbesc($arr["alias"]),
358                                         dbesc($arr["pubkey"]),
359                                         dbesc(datetime_convert())
360                                 );
361                 }
362
363                 return $r;
364         }
365
366         private function get_contact_by_handle($uid, $handle) {
367                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
368                         intval($uid),
369                         dbesc($handle)
370                 );
371
372                 if ($r AND count($r))
373                         return $r[0];
374
375                 $handle_parts = explode("@", $handle);
376                 $nurl_sql = '%%://' . $handle_parts[1] . '%%/profile/' . $handle_parts[0];
377                 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
378                         dbesc(NETWORK_DFRN),
379                         intval($uid),
380                         dbesc($nurl_sql)
381                 );
382                 if($r AND count($r))
383                         return $r[0];
384
385                 return false;
386         }
387
388         private function post_allow($importer, $contact, $is_comment = false) {
389
390                 // perhaps we were already sharing with this person. Now they're sharing with us.
391                 // That makes us friends.
392                 // Normally this should have handled by getting a request - but this could get lost
393                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
394                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
395                                 intval(CONTACT_IS_FRIEND),
396                                 intval($contact["id"]),
397                                 intval($importer["uid"])
398                         );
399                         $contact["rel"] = CONTACT_IS_FRIEND;
400                         logger("defining user ".$contact["nick"]." as friend");
401                 }
402
403                 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
404                         return false;
405                 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
406                         return true;
407                 if($contact["rel"] == CONTACT_IS_FOLLOWER)
408                         if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
409                                 return true;
410
411                 // Messages for the global users are always accepted
412                 if ($importer["uid"] == 0)
413                         return true;
414
415                 return false;
416         }
417
418         private function get_allowed_contact_by_handle($importer, $handle, $is_comment = false) {
419                 $contact = self::get_contact_by_handle($importer["uid"], $handle);
420                 if (!$contact) {
421                         logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
422                         return false;
423                 }
424
425                 if (!self::post_allow($importer, $contact, false)) {
426                         logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
427                         return false;
428                 }
429                 return $contact;
430         }
431
432         private function message_exists($uid, $guid) {
433                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
434                         intval($uid),
435                         dbesc($guid)
436                 );
437
438                 if(count($r)) {
439                         logger("message ".$guid." already exists for user ".$uid);
440                         return false;
441                 }
442
443                 return true;
444         }
445
446         private function fetch_guid($item) {
447                 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
448                         function ($match) use ($item){
449                                 return(self::fetch_guid_sub($match, $item));
450                         },$item["body"]);
451         }
452
453         private function fetch_guid_sub($match, $item) {
454                 if (!self::store_by_guid($match[1], $item["author-link"]))
455                         self::store_by_guid($match[1], $item["owner-link"]);
456         }
457
458         private function store_by_guid($guid, $server, $uid = 0) {
459                 $serverparts = parse_url($server);
460                 $server = $serverparts["scheme"]."://".$serverparts["host"];
461
462                 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
463
464                 $msg = self::fetch_message($guid, $server);
465
466                 if (!$msg)
467                         return false;
468
469                 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
470
471                 // Now call the dispatcher
472                 return self::dispatch_public($msg);
473         }
474
475         private function fetch_message($guid, $server, $level = 0) {
476
477                 if ($level > 5)
478                         return false;
479
480                 // This will not work if the server is not a Diaspora server
481                 $source_url = $server."/p/".$guid.".xml";
482                 $x = fetch_url($source_url);
483                 if(!$x)
484                         return false;
485
486                 /// @todo - should maybe solved by the dispatcher
487                 $source_xml = parse_xml_string($x, false);
488
489                 if (!is_object($source_xml))
490                         return false;
491
492                 if ($source_xml->post->reshare) {
493                         // Reshare of a reshare - old Diaspora version
494                         return self::fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
495                 } elseif ($source_xml->getName() == "reshare") {
496                         // Reshare of a reshare - new Diaspora version
497                         return self::fetch_message($source_xml->root_guid, $server, ++$level);
498                 }
499
500                 // Fetch the author - for the old and the new Diaspora version
501                 if ($source_xml->post->status_message->diaspora_handle)
502                         $author = (string)$source_xml->post->status_message->diaspora_handle;
503                 elseif ($source_xml->author)
504                         $author = (string)$source_xml->author;
505
506                 if (!$author)
507                         return false;
508
509                 $msg = array("message" => $x, "author" => $author);
510
511                 // We don't really need this, but until the work is unfinished we better will keep this
512                 $msg["key"] = self::get_key($msg["author"]);
513
514                 return $msg;
515         }
516
517         private function fetch_parent_item($uid, $guid, $author, $contact) {
518                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
519                                 `author-name`, `author-link`, `author-avatar`,
520                                 `owner-name`, `owner-link`, `owner-avatar`
521                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
522                         intval($uid), dbesc($guid));
523
524                 if(!count($r)) {
525                         $result = self::store_by_guid($guid, $contact["url"], $uid);
526
527                         if (!$result) {
528                                 $person = self::get_person_by_handle($author);
529                                 $result = self::store_by_guid($guid, $person["url"], $uid);
530                         }
531
532                         if ($result) {
533                                 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
534
535                                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
536                                                 `author-name`, `author-link`, `author-avatar`,
537                                                 `owner-name`, `owner-link`, `owner-avatar`
538                                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
539                                         intval($uid), dbesc($guid));
540                         }
541                 }
542
543                 if (!count($r)) {
544                         logger("parent item not found: parent: ".$guid." item: ".$guid);
545                         return false;
546                 } else
547                         return $r[0];
548         }
549
550         private function get_author_contact_by_url($contact, $person, $uid) {
551
552                 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
553                         dbesc(normalise_link($person["url"])), intval($uid));
554                 if ($r) {
555                         $cid = $r[0]["id"];
556                         $network = $r[0]["network"];
557                 } else {
558                         $cid = $contact["id"];
559                         $network = NETWORK_DIASPORA;
560                 }
561
562                 return (array("cid" => $cid, "network" => $network));
563         }
564
565         public static function is_redmatrix($url) {
566                 return(strstr($url, "/channel/"));
567         }
568
569         private function plink($addr, $guid) {
570                 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
571
572                 // Fallback
573                 if (!$r)
574                         return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
575
576                 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
577                 // So we try another way as well.
578                 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
579                 if ($s)
580                         $r[0]["network"] = $s[0]["network"];
581
582                 if ($r[0]["network"] == NETWORK_DFRN)
583                         return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
584
585                 if (self::is_redmatrix($r[0]["url"]))
586                         return $r[0]["url"]."/?f=&mid=".$guid;
587
588                 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
589         }
590
591         private function import_account_deletion($importer, $data) {
592                 $author = notags(unxmlify($data->author));
593
594                 $contact = self::get_contact_by_handle($importer["uid"], $author);
595                 if (!$contact) {
596                         logger("cannot find contact for author: ".$author);
597                         return false;
598                 }
599
600                 // We now remove the contact
601                 contact_remove($contact["id"]);
602                 return true;
603         }
604
605         private function import_comment($importer, $sender, $data) {
606                 $guid = notags(unxmlify($data->guid));
607                 $parent_guid = notags(unxmlify($data->parent_guid));
608                 $text = unxmlify($data->text);
609                 $author = notags(unxmlify($data->author));
610
611                 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
612                 if (!$contact)
613                         return false;
614
615                 if (self::message_exists($importer["uid"], $guid))
616                         return false;
617
618                 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
619                 if (!$parent_item)
620                         return false;
621
622                 $person = self::get_person_by_handle($author);
623                 if (!is_array($person)) {
624                         logger("unable to find author details");
625                         return false;
626                 }
627
628                 // Fetch the contact id - if we know this contact
629                 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
630
631                 $datarray = array();
632
633                 $datarray["uid"] = $importer["uid"];
634                 $datarray["contact-id"] = $author_contact["cid"];
635                 $datarray["network"]  = $author_contact["network"];
636
637                 $datarray["author-name"] = $person["name"];
638                 $datarray["author-link"] = $person["url"];
639                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
640
641                 $datarray["owner-name"] = $contact["name"];
642                 $datarray["owner-link"] = $contact["url"];
643                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
644
645                 $datarray["guid"] = $guid;
646                 $datarray["uri"] = $author.":".$guid;
647
648                 $datarray["type"] = "remote-comment";
649                 $datarray["verb"] = ACTIVITY_POST;
650                 $datarray["gravity"] = GRAVITY_COMMENT;
651                 $datarray["parent-uri"] = $parent_item["uri"];
652
653                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
654                 $datarray["object"] = json_encode($data);
655
656                 $datarray["body"] = diaspora2bb($text);
657
658                 self::fetch_guid($datarray);
659
660                 $message_id = item_store($datarray);
661                 // print_r($datarray);
662
663                 // If we are the origin of the parent we store the original data and notify our followers
664                 if($message_id AND $parent_item["origin"]) {
665
666                         // Formerly we stored the signed text, the signature and the author in different fields.
667                         // The new Diaspora protocol can have variable fields. We now store the data in correct order in a single field.
668                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
669                                 intval($message_id),
670                                 dbesc(json_encode($data))
671                         );
672
673                         // notify others
674                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
675                 }
676
677                 return $message_id;
678         }
679
680         private function import_conversation($importer, $data) {
681                 print_r($data);
682                 die();
683 /*
684         $guid = notags(unxmlify($xml->guid));
685         $subject = notags(unxmlify($xml->subject));
686         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
687         $participant_handles = notags(unxmlify($xml->participant_handles));
688         $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
689
690         $parent_uri = $diaspora_handle . ':' . $guid;
691
692         $messages = $xml->message;
693
694         if(! count($messages)) {
695                 logger('empty conversation');
696                 return;
697         }
698
699                 $contact = self::get_allowed_contact_by_handle($importer, $sender, true)
700                 if (!$contact)
701                         return false;
702
703         $conversation = null;
704
705         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
706                 intval($importer['uid']),
707                 dbesc($guid)
708         );
709         if(count($c))
710                 $conversation = $c[0];
711         else {
712                 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
713                         intval($importer['uid']),
714                         dbesc($guid),
715                         dbesc($diaspora_handle),
716                         dbesc(datetime_convert('UTC','UTC',$created_at)),
717                         dbesc(datetime_convert()),
718                         dbesc($subject),
719                         dbesc($participant_handles)
720                 );
721                 if($r)
722                         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
723                 intval($importer['uid']),
724             dbesc($guid)
725         );
726             if(count($c))
727             $conversation = $c[0];
728         }
729         if(! $conversation) {
730                 logger('diaspora_conversation: unable to create conversation.');
731                 return;
732         }
733
734         foreach($messages as $mesg) {
735
736                 $reply = 0;
737
738                 $msg_guid = notags(unxmlify($mesg->guid));
739                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
740                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
741                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
742                 $msg_text = unxmlify($mesg->text);
743                 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
744                 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
745                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
746                 if($msg_conversation_guid != $guid) {
747                         logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
748                         continue;
749                 }
750
751                 $body = diaspora2bb($msg_text);
752                 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
753
754                 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
755
756                 $author_signature = base64_decode($msg_author_signature);
757
758                 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
759                         $person = $contact;
760                         $key = $msg['key'];
761                 }
762                 else {
763                         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
764
765                         if(is_array($person) && x($person,'pubkey'))
766                                 $key = $person['pubkey'];
767                         else {
768                                 logger('diaspora_conversation: unable to find author details');
769                                 continue;
770                         }
771                 }
772
773                 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
774                         logger('diaspora_conversation: verification failed.');
775                         continue;
776                 }
777
778                 if($msg_parent_author_signature) {
779                         $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
780
781                         $parent_author_signature = base64_decode($msg_parent_author_signature);
782
783                         $key = $msg['key'];
784
785                         if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
786                                 logger('diaspora_conversation: owner verification failed.');
787                                 continue;
788                         }
789                 }
790
791                 $r = q("select id from mail where `uri` = '%s' limit 1",
792                         dbesc($message_id)
793                 );
794                 if(count($r)) {
795                         logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
796                         continue;
797                 }
798
799                 q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
800                         intval($importer['uid']),
801                         dbesc($msg_guid),
802                         intval($conversation['id']),
803                         dbesc($person['name']),
804                         dbesc($person['photo']),
805                         dbesc($person['url']),
806                         intval($contact['id']),
807                         dbesc($subject),
808                         dbesc($body),
809                         0,
810                         0,
811                         dbesc($message_id),
812                         dbesc($parent_uri),
813                         dbesc($msg_created_at)
814                 );
815
816                 q("update conv set updated = '%s' where id = %d",
817                         dbesc(datetime_convert()),
818                         intval($conversation['id'])
819                 );
820
821                 notification(array(
822                         'type' => NOTIFY_MAIL,
823                         'notify_flags' => $importer['notify-flags'],
824                         'language' => $importer['language'],
825                         'to_name' => $importer['username'],
826                         'to_email' => $importer['email'],
827                         'uid' =>$importer['uid'],
828                         'item' => array('subject' => $subject, 'body' => $body),
829                         'source_name' => $person['name'],
830                         'source_link' => $person['url'],
831                         'source_photo' => $person['thumb'],
832                         'verb' => ACTIVITY_POST,
833                         'otype' => 'mail'
834                 ));
835         }
836 */
837                 return true;
838         }
839
840         private function construct_like_body($contact, $parent_item, $guid) {
841                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
842
843                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
844                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
845                 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
846
847                 return sprintf($bodyverb, $ulink, $alink, $plink);
848         }
849
850         private function construct_like_object($importer, $parent_item) {
851                 $objtype = ACTIVITY_OBJ_NOTE;
852                 $link = xmlify('<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />'."\n") ;
853                 $parent_body = $parent_item["body"];
854
855                 $obj = <<< EOT
856
857                 <object>
858                         <type>$objtype</type>
859                         <local>1</local>
860                         <id>{$parent_item["uri"]}</id>
861                         <link>$link</link>
862                         <title></title>
863                         <content>$parent_body</content>
864                 </object>
865 EOT;
866
867                 return $obj;
868         }
869
870         private function import_like($importer, $sender, $data) {
871                 $positive = notags(unxmlify($data->positive));
872                 $guid = notags(unxmlify($data->guid));
873                 $parent_type = notags(unxmlify($data->parent_type));
874                 $parent_guid = notags(unxmlify($data->parent_guid));
875                 $author = notags(unxmlify($data->author));
876
877                 // likes on comments aren't supported by Diaspora - only on posts
878                 // But maybe this will be supported in the future, so we will accept it.
879                 if (!in_array($parent_type, array("Post", "Comment")))
880                         return false;
881
882                 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
883                 if (!$contact)
884                         return false;
885
886                 if (self::message_exists($importer["uid"], $guid))
887                         return false;
888
889                 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
890                 if (!$parent_item)
891                         return false;
892
893                 $person = self::get_person_by_handle($author);
894                 if (!is_array($person)) {
895                         logger("unable to find author details");
896                         return false;
897                 }
898
899                 // Fetch the contact id - if we know this contact
900                 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
901
902                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
903                 // We would accept this anyhow.
904                 if ($positive === "true")
905                         $verb = ACTIVITY_LIKE;
906                 else
907                         $verb = ACTIVITY_DISLIKE;
908
909                 $datarray = array();
910
911                 $datarray["uid"] = $importer["uid"];
912                 $datarray["contact-id"] = $author_contact["cid"];
913                 $datarray["network"]  = $author_contact["network"];
914
915                 $datarray["author-name"] = $person["name"];
916                 $datarray["author-link"] = $person["url"];
917                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
918
919                 $datarray["owner-name"] = $contact["name"];
920                 $datarray["owner-link"] = $contact["url"];
921                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
922
923                 $datarray["guid"] = $guid;
924                 $datarray["uri"] = $author.":".$guid;
925
926                 $datarray["type"] = "activity";
927                 $datarray["verb"] = $verb;
928                 $datarray["gravity"] = GRAVITY_LIKE;
929                 $datarray["parent-uri"] = $parent_item["uri"];
930
931                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
932                 $datarray["object"] = self::construct_like_object($importer, $parent_item);
933
934                 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
935
936                 $message_id = item_store($datarray);
937                 //print_r($datarray);
938
939                 // If we are the origin of the parent we store the original data and notify our followers
940                 if($message_id AND $parent_item["origin"]) {
941
942                         // Formerly we stored the signed text, the signature and the author in different fields.
943                         // The new Diaspora protocol can have variable fields. We now store the data in correct order in a single field.
944                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
945                                 intval($message_id),
946                                 dbesc(json_encode($data))
947                         );
948
949                         // notify others
950                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
951                 }
952
953                 return $message_id;
954         }
955
956         private function import_message($importer, $data) {
957                 $guid = notags(unxmlify($data->guid));
958                 $parent_guid = notags(unxmlify($data->parent_guid));
959                 $text = unxmlify($data->text);
960                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
961                 $author = notags(unxmlify($data->author));
962                 $conversation_guid = notags(unxmlify($data->conversation_guid));
963
964                 $parent_uri = $author.":".$parent_guid;
965
966                 $contact = self::get_allowed_contact_by_handle($importer, $author, true);
967                 if (!$contact)
968                         return false;
969
970                 $conversation = null;
971
972                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
973                         intval($importer["uid"]),
974                         dbesc($conversation_guid)
975                 );
976                 if(count($c))
977                         $conversation = $c[0];
978                 else {
979                         logger("conversation not available.");
980                         return false;
981                 }
982
983                 $reply = 0;
984
985                 $body = diaspora2bb($text);
986                 $message_id = $author.":".$guid;
987
988                 $person = self::get_person_by_handle($author);
989                 if (!$person) {
990                         logger("unable to find author details");
991                         return false;
992                 }
993
994                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
995                         dbesc($message_id),
996                         intval($importer["uid"])
997                 );
998                 if(count($r)) {
999                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1000                         return false;
1001                 }
1002
1003                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1004                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1005                         intval($importer["uid"]),
1006                         dbesc($guid),
1007                         intval($conversation["id"]),
1008                         dbesc($person["name"]),
1009                         dbesc($person["photo"]),
1010                         dbesc($person["url"]),
1011                         intval($contact["id"]),
1012                         dbesc($conversation["subject"]),
1013                         dbesc($body),
1014                         0,
1015                         1,
1016                         dbesc($message_id),
1017                         dbesc($parent_uri),
1018                         dbesc($created_at)
1019                 );
1020
1021                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1022                         dbesc(datetime_convert()),
1023                         intval($conversation["id"])
1024                 );
1025
1026                 return true;
1027         }
1028
1029         private function import_participation($importer, $data) {
1030                 // I'm not sure if we can fully support this message type
1031                 return true;
1032         }
1033
1034         private function import_photo($importer, $data) {
1035                 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1036                 return true;
1037         }
1038
1039         private function import_poll_participation($importer, $data) {
1040                 // We don't support polls by now
1041                 return true;
1042         }
1043
1044         private function import_profile($importer, $data) {
1045                 $author = notags(unxmlify($data->author));
1046
1047                 $contact = self::get_contact_by_handle($importer["uid"], $author);
1048                 if (!$contact)
1049                         return;
1050
1051                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1052                 $image_url = unxmlify($data->image_url);
1053                 $birthday = unxmlify($data->birthday);
1054                 $location = diaspora2bb(unxmlify($data->location));
1055                 $about = diaspora2bb(unxmlify($data->bio));
1056                 $gender = unxmlify($data->gender);
1057                 $searchable = (unxmlify($data->searchable) == "true");
1058                 $nsfw = (unxmlify($data->nsfw) == "true");
1059                 $tags = unxmlify($data->tag_string);
1060
1061                 $tags = explode("#", $tags);
1062
1063                 $keywords = array();
1064                 foreach ($tags as $tag) {
1065                         $tag = trim(strtolower($tag));
1066                         if ($tag != "")
1067                                 $keywords[] = $tag;
1068                 }
1069
1070                 $keywords = implode(", ", $keywords);
1071
1072                 $handle_parts = explode("@", $author);
1073                 $nick = $handle_parts[0];
1074
1075                 if($name === "")
1076                         $name = $handle_parts[0];
1077
1078                 if( preg_match("|^https?://|", $image_url) === 0)
1079                         $image_url = "http://".$handle_parts[1].$image_url;
1080
1081                 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1082
1083                 // Generic birthday. We don't know the timezone. The year is irrelevant.
1084
1085                 $birthday = str_replace("1000", "1901", $birthday);
1086
1087                 if ($birthday != "")
1088                         $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1089
1090                 // this is to prevent multiple birthday notifications in a single year
1091                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1092
1093                 if(substr($birthday,5) === substr($contact["bd"],5))
1094                         $birthday = $contact["bd"];
1095
1096                 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1097                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1098                         dbesc($name),
1099                         dbesc($nick),
1100                         dbesc($author),
1101                         dbesc(datetime_convert()),
1102                         dbesc($birthday),
1103                         dbesc($location),
1104                         dbesc($about),
1105                         dbesc($keywords),
1106                         dbesc($gender),
1107                         intval($contact["id"]),
1108                         intval($importer["uid"])
1109                 );
1110
1111                 if ($searchable) {
1112                         poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1113                                 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1114                 }
1115
1116                 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1117                                         "photo" => $image_url, "name" => $name, "location" => $location,
1118                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
1119                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1120                                         "hide" => !$searchable, "nsfw" => $nsfw);
1121
1122                 update_gcontact($gcontact);
1123
1124                 return true;
1125         }
1126
1127         private function import_request($importer, $data) {
1128 print_r($data);
1129 /*
1130         $author = unxmlify($xml->author);
1131         $recipient = unxmlify($xml->recipient);
1132
1133         if (!$author || !$recipient)
1134                 return;
1135
1136         $contact = self::get_contact_by_handle($importer["uid"],$author);
1137
1138         if($contact) {
1139
1140                 // perhaps we were already sharing with this person. Now they're sharing with us.
1141                 // That makes us friends.
1142
1143                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1144                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1145                                 intval(CONTACT_IS_FRIEND),
1146                                 intval($contact["id"]),
1147                                 intval($importer["uid"])
1148                         );
1149                 }
1150                 // send notification
1151
1152                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1153                         intval($importer["uid"])
1154                 );
1155
1156                 if((count($r)) && (!$r[0]["hide-friends"]) && (!$contact["hidden"]) && intval(get_pconfig($importer["uid"],'system','post_newfriend'))) {
1157
1158                         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1159                                 intval($importer["uid"])
1160                         );
1161
1162                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1163
1164                         if(count($self) && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1165
1166                                 $arr = array();
1167                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri(App::get_hostname(), $importer["uid"]);
1168                                 $arr["uid"] = $importer["uid"];
1169                                 $arr["contact-id"] = $self[0]["id"];
1170                                 $arr["wall"] = 1;
1171                                 $arr["type"] = 'wall';
1172                                 $arr["gravity"] = 0;
1173                                 $arr["origin"] = 1;
1174                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1175                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1176                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1177                                 $arr["verb"] = ACTIVITY_FRIEND;
1178                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1179
1180                                 $A = '[url=' . $self[0]["url"] . "]' . $self[0]["name"] . '[/url]';
1181                                 $B = '[url=' . $contact["url"] . "]' . $contact["name"] . '[/url]';
1182                                 $BPhoto = '[url=' . $contact["url"] . "]' . '[img]' . $contact["thumb"] . '[/img][/url]';
1183                                 $arr["body"] =  sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
1184
1185                                 $arr["object"] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact["name"] . '</title>'
1186                                         . '<id>' . $contact["url"] . '/' . $contact["name"] . '</id>';
1187                                 $arr["object"] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact["url"] . '" />' . "\n")
1188 ;
1189                                 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact["thumb"] . '" />' . "\n");
1190                                 $arr["object"] .= '</link></object>' . "\n";
1191                                 $arr["last-child"] = 1;
1192
1193                                 $arr["allow_cid"] = $user[0]["allow_cid"];
1194                                 $arr["allow_gid"] = $user[0]["allow_gid"];
1195                                 $arr["deny_cid"]  = $user[0]["deny_cid"];
1196                                 $arr["deny_gid"]  = $user[0]["deny_gid"];
1197
1198                                 $i = item_store($arr);
1199                                 if($i)
1200                                 proc_run('php',"include/notifier.php","activity","$i");
1201
1202                         }
1203
1204                 }
1205
1206                 return;
1207         }
1208
1209         $ret = self::get_person_by_handle($author);
1210
1211
1212         if((! count($ret)) || ($ret["network"] != NETWORK_DIASPORA)) {
1213                 logger('diaspora_request: Cannot resolve diaspora handle ' . $author . ' for ' . $recipient);
1214                 return;
1215         }
1216
1217         $batch = (($ret["batch"]) ? $ret["batch"] : implode('/', array_slice(explode('/',$ret["url"]),0,3)) . '/receive/public');
1218
1219
1220
1221         $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1222                 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
1223                 intval($importer["uid"]),
1224                 dbesc($ret["network"]),
1225                 dbesc($ret["addr"]),
1226                 datetime_convert(),
1227                 dbesc($ret["url"]),
1228                 dbesc(normalise_link($ret["url"])),
1229                 dbesc($batch),
1230                 dbesc($ret["name"]),
1231                 dbesc($ret["nick"]),
1232                 dbesc($ret["photo"]),
1233                 dbesc($ret["pubkey"]),
1234                 dbesc($ret["notify"]),
1235                 dbesc($ret["poll"]),
1236                 1,
1237                 2
1238         );
1239
1240         // find the contact record we just created
1241
1242         $contact_record = diaspora_get_contact_by_handle($importer["uid"],$author);
1243
1244         if(! $contact_record) {
1245                 logger('diaspora_request: unable to locate newly created contact record.');
1246                 return;
1247         }
1248
1249         $g = q("select def_gid from user where uid = %d limit 1",
1250                 intval($importer["uid"])
1251         );
1252         if($g && intval($g[0]["def_gid"])) {
1253                 group_add_member($importer["uid"],'',$contact_record["id"],$g[0]["def_gid"]);
1254         }
1255
1256         if($importer["page-flags"] == PAGE_NORMAL) {
1257
1258                 $hash = random_string() . (string) time();   // Generate a confirm_key
1259
1260                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
1261                         VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
1262                         intval($importer["uid"]),
1263                         intval($contact_record["id"]),
1264                         0,
1265                         0,
1266                         dbesc( t('Sharing notification from Diaspora network')),
1267                         dbesc($hash),
1268                         dbesc(datetime_convert())
1269                 );
1270         }
1271         else {
1272
1273                 // automatic friend approval
1274
1275                 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1276
1277                 // technically they are sharing with us (CONTACT_IS_SHARING),
1278                 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1279                 // we are going to change the relationship and make them a follower.
1280
1281                 if($importer["page-flags"] == PAGE_FREELOVE)
1282                         $new_relation = CONTACT_IS_FRIEND;
1283                 else
1284                         $new_relation = CONTACT_IS_FOLLOWER;
1285
1286                 $r = q("UPDATE `contact` SET `rel` = %d,
1287                         `name-date` = '%s',
1288                         `uri-date` = '%s',
1289                         `blocked` = 0,
1290                         `pending` = 0,
1291                         `writable` = 1
1292                         WHERE `id` = %d
1293                         ",
1294                         intval($new_relation),
1295                         dbesc(datetime_convert()),
1296                         dbesc(datetime_convert()),
1297                         intval($contact_record["id"])
1298                 );
1299
1300                 $u = q("select * from user where uid = %d limit 1",intval($importer["uid"]));
1301                 if($u)
1302                         $ret = diaspora_share($u[0],$contact_record);
1303         }
1304 */
1305                 return true;
1306         }
1307
1308         private function get_original_item($guid, $orig_author, $author) {
1309
1310                 // Do we already have this item?
1311                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1312                                 `author-name`, `author-link`, `author-avatar`
1313                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1314                         dbesc($guid));
1315
1316                 if(count($r)) {
1317                         logger("reshared message ".$guid." already exists on system.");
1318
1319                         // Maybe it is already a reshared item?
1320                         // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1321                         if (api_share_as_retweet($r[0]))
1322                                 $r = array();
1323                         else
1324                                 return $r[0];
1325                 }
1326
1327                 if (!count($r)) {
1328                         $server = 'https://'.substr($orig_author,strpos($orig_author,'@')+1);
1329                         logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1330                         $item_id = self::store_by_guid($guid, $server);
1331
1332                         if (!$item_id) {
1333                                 $server = 'https://'.substr($author,strpos($author,'@')+1);
1334                                 logger("2nd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1335                                 $item = self::store_by_guid($guid, $server);
1336                         }
1337                         if (!$item_id) {
1338                                 $server = 'http://'.substr($orig_author,strpos($orig_author,'@')+1);
1339                                 logger("3rd try: reshared message ".$guid." will be fetched from original server: ".$server);
1340                                 $item = self::store_by_guid($guid, $server);
1341                         }
1342                         if (!$item_id) {
1343                                 $server = 'http://'.substr($author,strpos($author,'@')+1);
1344                                 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1345                                 $item = self::store_by_guid($guid, $server);
1346                         }
1347
1348                         if ($item_id) {
1349                                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1350                                                 `author-name`, `author-link`, `author-avatar`
1351                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1352                                         intval($item_id));
1353
1354                                 if ($r)
1355                                         return $r[0];
1356
1357                         }
1358                 }
1359                 return false;
1360         }
1361
1362         private function import_reshare($importer, $data) {
1363                 $root_author = notags(unxmlify($data->root_author));
1364                 $root_guid = notags(unxmlify($data->root_guid));
1365                 $guid = notags(unxmlify($data->guid));
1366                 $author = notags(unxmlify($data->author));
1367                 $public = notags(unxmlify($data->public));
1368                 $created_at = notags(unxmlify($data->created_at));
1369
1370                 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1371                 if (!$contact)
1372                         return false;
1373
1374 //              if (self::message_exists($importer["uid"], $guid))
1375 //                      return false;
1376
1377                 $original_item = self::get_original_item($root_guid, $root_author, $author);
1378                 if (!$original_item)
1379                         return false;
1380
1381                 $datarray = array();
1382
1383                 $datarray["uid"] = $importer["uid"];
1384                 $datarray["contact-id"] = $contact["id"];
1385                 $datarray["network"]  = NETWORK_DIASPORA;
1386
1387                 $datarray["author-name"] = $contact["name"];
1388                 $datarray["author-link"] = $contact["url"];
1389                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1390
1391                 $datarray["owner-name"] = $datarray["author-name"];
1392                 $datarray["owner-link"] = $datarray["author-link"];
1393                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1394
1395                 $datarray["guid"] = $guid;
1396                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1397
1398                 $datarray["verb"] = ACTIVITY_POST;
1399                 $datarray["gravity"] = GRAVITY_PARENT;
1400
1401                 $datarray["object"] = json_encode($data);
1402
1403                 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1404                                         $original_item["guid"], $original_item["created"], $original_item["uri"]);
1405                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1406
1407                 $datarray["tag"] = $original_item["tag"];
1408                 $datarray["app"]  = $original_item["app"];
1409
1410                 $datarray["plink"] = self::plink($author, $guid);
1411                 $datarray["private"] = (($public == "false") ? 1 : 0);
1412                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1413
1414                 $datarray["object-type"] = $original_item["object-type"];
1415
1416                 self::fetch_guid($datarray);
1417                 //$message_id = item_store($datarray);
1418                 print_r($datarray);
1419
1420                 return $message_id;
1421         }
1422
1423         private function import_retraction($importer, $data) {
1424                 return true;
1425         }
1426
1427         private function import_status_message($importer, $data) {
1428
1429                 $raw_message = unxmlify($data->raw_message);
1430                 $guid = notags(unxmlify($data->guid));
1431                 $author = notags(unxmlify($data->author));
1432                 $public = notags(unxmlify($data->public));
1433                 $created_at = notags(unxmlify($data->created_at));
1434                 $provider_display_name = notags(unxmlify($data->provider_display_name));
1435
1436                 /// @todo enable support for polls
1437                 if ($data->poll) {
1438                         foreach ($data->poll AS $poll)
1439                                 print_r($poll);
1440                         die("poll!\n");
1441                 }
1442                 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1443                 if (!$contact)
1444                         return false;
1445
1446                 //if (self::message_exists($importer["uid"], $guid))
1447                 //      return false;
1448
1449                 $address = array();
1450                 if ($data->location)
1451                         foreach ($data->location->children() AS $fieldname => $data)
1452                                 $address[$fieldname] = notags(unxmlify($data));
1453
1454                 $body = diaspora2bb($raw_message);
1455
1456                 if ($data->photo)
1457                         foreach ($data->photo AS $photo)
1458                                 $body = "[img]".$photo->remote_photo_path.$photo->remote_photo_name."[/img]\n".$body;
1459
1460                 $datarray = array();
1461
1462                 if($data->photo->remote_photo_path AND $data->photo->remote_photo_name)
1463                         $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1464                 else {
1465                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1466                         // Add OEmbed and other information to the body
1467                         if (!self::is_redmatrix($contact["url"]))
1468                                 $body = add_page_info_to_body($body, false, true);
1469                 }
1470
1471                 $str_tags = "";
1472
1473                 $cnt = preg_match_all("/@\[url=(.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1474                 if($cnt) {
1475                         foreach($matches as $mtch) {
1476                                 if(strlen($str_tags))
1477                                         $str_tags .= ",";
1478                                 $str_tags .= "@[url=".$mtch[1]."[/url]";
1479                         }
1480                 }
1481
1482                 $datarray["uid"] = $importer["uid"];
1483                 $datarray["contact-id"] = $contact["id"];
1484                 $datarray["network"] = NETWORK_DIASPORA;
1485
1486                 $datarray["author-name"] = $contact["name"];
1487                 $datarray["author-link"] = $contact["url"];
1488                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1489
1490                 $datarray["owner-name"] = $datarray["author-name"];
1491                 $datarray["owner-link"] = $datarray["author-link"];
1492                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1493
1494                 $datarray["guid"] = $guid;
1495                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1496
1497                 $datarray["verb"] = ACTIVITY_POST;
1498                 $datarray["gravity"] = GRAVITY_PARENT;
1499
1500                 $datarray["object"] = json_encode($data);
1501
1502                 $datarray["body"] = $body;
1503
1504                 $datarray["tag"] = $str_tags;
1505                 if ($provider_display_name != "")
1506                         $datarray["app"] = $provider_display_name;
1507
1508                 $datarray["plink"] = self::plink($author, $guid);
1509                 $datarray["private"] = (($public == "false") ? 1 : 0);
1510                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1511
1512                 if (isset($address["address"]))
1513                         $datarray["location"] = $address["address"];
1514
1515                 if (isset($address["lat"]) AND isset($address["lng"]))
1516                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
1517
1518                 self::fetch_guid($datarray);
1519                 //$message_id = item_store($datarray);
1520                 print_r($datarray);
1521
1522                 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
1523
1524                 return $message_id;
1525         }
1526 }
1527 ?>