]> git.mxchange.org Git - friendica.git/blob - include/diaspora2.php
4c9d79912e341a125821b6f401173b0cfc9ab500
[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/xml.php");
15 require_once("include/datetime.php");
16
17 /**
18  * @brief This class contain functions to create and send Diaspora XML files
19  *
20  */
21 class diaspora {
22
23         public static function fetch_relay() {
24
25                 $serverdata = get_config("system", "relay_server");
26                 if ($serverdata == "")
27                         return array();
28
29                 $relay = array();
30
31                 $servers = explode(",", $serverdata);
32
33                 foreach($servers AS $server) {
34                         $server = trim($server);
35                         $batch = $server."/receive/public";
36
37                         $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
38
39                         if (!$relais) {
40                                 $addr = "relay@".str_replace("http://", "", normalise_link($server));
41
42                                 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
43                                         VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
44                                         datetime_convert(),
45                                         dbesc($addr),
46                                         dbesc($addr),
47                                         dbesc($server),
48                                         dbesc(normalise_link($server)),
49                                         dbesc($batch),
50                                         dbesc(NETWORK_DIASPORA),
51                                         intval(CONTACT_IS_FOLLOWER),
52                                         dbesc(datetime_convert()),
53                                         dbesc(datetime_convert()),
54                                         dbesc(datetime_convert())
55                                 );
56
57                                 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
58                                 if ($relais)
59                                         $relay[] = $relais[0];
60                         } else
61                                 $relay[] = $relais[0];
62                 }
63
64                 return $relay;
65         }
66
67         /**
68          * @brief Dispatches public messages and find the fitting receivers
69          *
70          * @param array $msg The post that will be dispatched
71          *
72          * @return bool Was the message accepted?
73          */
74         public static function dispatch_public($msg) {
75
76                 $enabled = intval(get_config("system", "diaspora_enabled"));
77                 if (!$enabled) {
78                         logger("diaspora is disabled");
79                         return false;
80                 }
81
82                 // Use a dummy importer to import the data for the public copy
83                 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
84                 $item_id = self::dispatch($importer,$msg);
85
86                 // Now distribute it to the followers
87                 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
88                         (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
89                         AND NOT `account_expired` AND NOT `account_removed`",
90                         dbesc(NETWORK_DIASPORA),
91                         dbesc($msg["author"])
92                 );
93                 if($r) {
94                         foreach($r as $rr) {
95                                 logger("delivering to: ".$rr["username"]);
96                                 self::dispatch($rr,$msg);
97                         }
98                 } else
99                         logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
100
101                 return $item_id;
102         }
103
104         /**
105          * @brief Dispatches the different message types to the different functions
106          *
107          * @param array $importer Array of the importer user
108          * @param array $msg The post that will be dispatched
109          *
110          * @return bool Was the message accepted?
111          */
112         public static function dispatch($importer, $msg) {
113
114                 // The sender is the handle of the contact that sent the message.
115                 // This will often be different with relayed messages (for example "like" and "comment")
116                 $sender = $msg["author"];
117
118                 if (!diaspora::valid_posting($msg, $fields)) {
119                         logger("Invalid posting");
120                         return false;
121                 }
122
123                 $type = $fields->getName();
124
125                 switch ($type) {
126                         case "account_deletion": // Done
127                                 //return true;
128                                 return self::receive_account_deletion($importer, $fields);
129
130                         case "comment": // Done
131                                 //return true;
132                                 return self::receive_comment($importer, $sender, $fields);
133
134                         case "conversation": // Done
135                                 //return true;
136                                 return self::receive_conversation($importer, $msg, $fields);
137
138                         case "like": // Done
139                                 //return true;
140                                 return self::receive_like($importer, $sender, $fields);
141
142                         case "message": // Done
143                                 //return true;
144                                 return self::receive_message($importer, $fields);
145
146                         case "participation": // Not implemented
147                                 return self::receive_participation($importer, $fields);
148
149                         case "photo": // Not needed
150                                 return self::receive_photo($importer, $fields);
151
152                         case "poll_participation": // Not implemented
153                                 return self::receive_poll_participation($importer, $fields);
154
155                         case "profile": // Done
156                                 //return true;
157                                 return self::receive_profile($importer, $fields);
158
159                         case "request":
160                                 //return true;
161                                 return self::receive_request($importer, $fields);
162
163                         case "reshare": // Done
164                                 //return true;
165                                 return self::receive_reshare($importer, $fields);
166
167                         case "retraction": // Done
168                                 //return true;
169                                 return self::receive_retraction($importer, $sender, $fields);
170
171                         case "status_message": // Done
172                                 //return true;
173                                 return self::receive_status_message($importer, $fields);
174
175                         default:
176                                 logger("Unknown message type ".$type);
177                                 return false;
178                 }
179
180                 return true;
181         }
182
183         /**
184          * @brief Checks if a posting is valid and fetches the data fields.
185          *
186          * This function does not only check the signature.
187          * It also does the conversion between the old and the new diaspora format.
188          *
189          * @param array $msg Array with the XML, the sender handle and the sender signature
190          * @param object $fields SimpleXML object that contains the posting when it is valid
191          *
192          * @return bool Is the posting valid?
193          */
194         private function valid_posting($msg, &$fields) {
195
196                 $data = parse_xml_string($msg["message"], false);
197
198                 if (!is_object($data))
199                         return false;
200
201                 $first_child = $data->getName();
202
203                 // Is this the new or the old version?
204                 if ($data->getName() == "XML") {
205                         $oldXML = true;
206                         foreach ($data->post->children() as $child)
207                                 $element = $child;
208                 } else {
209                         $oldXML = false;
210                         $element = $data;
211                 }
212
213                 $type = $element->getName();
214                 $orig_type = $type;
215
216                 // All retractions are handled identically from now on.
217                 // In the new version there will only be "retraction".
218                 if (in_array($type, array("signed_retraction", "relayable_retraction")))
219                         $type = "retraction";
220
221                 $fields = new SimpleXMLElement("<".$type."/>");
222
223                 $signed_data = "";
224
225                 foreach ($element->children() AS $fieldname => $entry) {
226                         if ($oldXML) {
227                                 // Translation for the old XML structure
228                                 if ($fieldname == "diaspora_handle")
229                                         $fieldname = "author";
230
231                                 if ($fieldname == "participant_handles")
232                                         $fieldname = "participants";
233
234                                 if (in_array($type, array("like", "participation"))) {
235                                         if ($fieldname == "target_type")
236                                                 $fieldname = "parent_type";
237                                 }
238
239                                 if ($fieldname == "sender_handle")
240                                         $fieldname = "author";
241
242                                 if ($fieldname == "recipient_handle")
243                                         $fieldname = "recipient";
244
245                                 if ($fieldname == "root_diaspora_id")
246                                         $fieldname = "root_author";
247
248                                 if ($type == "retraction") {
249                                         if ($fieldname == "post_guid")
250                                                 $fieldname = "target_guid";
251
252                                         if ($fieldname == "type")
253                                                 $fieldname = "target_type";
254                                 }
255                         }
256
257                         if ($fieldname == "author_signature")
258                                 $author_signature = base64_decode($entry);
259                         elseif ($fieldname == "parent_author_signature")
260                                 $parent_author_signature = base64_decode($entry);
261                         elseif ($fieldname != "target_author_signature") {
262                                 if ($signed_data != "") {
263                                         $signed_data .= ";";
264                                         $signed_data_parent .= ";";
265                                 }
266
267                                 $signed_data .= $entry;
268                         }
269                         if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
270                                 ($orig_type == "relayable_retraction"))
271                                 xml::copy($entry, $fields, $fieldname);
272                 }
273
274                 // This is something that shouldn't happen at all.
275                 if (in_array($type, array("status_message", "reshare", "profile")))
276                         if ($msg["author"] != $fields->author) {
277                                 logger("Message handle is not the same as envelope sender. Quitting this message.");
278                                 return false;
279                         }
280
281                 // Only some message types have signatures. So we quit here for the other types.
282                 if (!in_array($type, array("comment", "message", "like")))
283                         return true;
284
285                 // No author_signature? This is a must, so we quit.
286                 if (!isset($author_signature))
287                         return false;
288
289                 if (isset($parent_author_signature)) {
290                         $key = self::get_key($msg["author"]);
291
292                         if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
293                                 return false;
294                 }
295
296                 $key = self::get_key($fields->author);
297
298                 return rsa_verify($signed_data, $author_signature, $key, "sha256");
299         }
300
301         /**
302          * @brief Fetches the public key for a given handle
303          *
304          * @param string $handle The handle
305          *
306          * @return string The public key
307          */
308         private function get_key($handle) {
309                 logger("Fetching diaspora key for: ".$handle);
310
311                 $r = self::get_person_by_handle($handle);
312                 if($r)
313                         return $r["pubkey"];
314
315                 return "";
316         }
317
318         /**
319          * @brief Fetches data for a given handle
320          *
321          * @param string $handle The handle
322          *
323          * @return array the queried data
324          */
325         private function get_person_by_handle($handle) {
326
327                 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
328                         dbesc(NETWORK_DIASPORA),
329                         dbesc($handle)
330                 );
331                 if ($r) {
332                         $person = $r[0];
333                         logger("In cache ".print_r($r,true), LOGGER_DEBUG);
334
335                         // update record occasionally so it doesn't get stale
336                         $d = strtotime($person["updated"]." +00:00");
337                         if ($d < strtotime("now - 14 days"))
338                                 $update = true;
339                 }
340
341                 if (!$person OR $update) {
342                         logger("create or refresh", LOGGER_DEBUG);
343                         $r = probe_url($handle, PROBE_DIASPORA);
344
345                         // Note that Friendica contacts will return a "Diaspora person"
346                         // if Diaspora connectivity is enabled on their server
347                         if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
348                                 self::add_fcontact($r, $update);
349                                 $person = $r;
350                         }
351                 }
352                 return $person;
353         }
354
355         /**
356          * @brief Updates the fcontact table
357          *
358          * @param array $arr The fcontact data
359          * @param bool $update Update or insert?
360          *
361          * @return string The id of the fcontact entry
362          */
363         private function add_fcontact($arr, $update = false) {
364                 /// @todo Remove this function from include/network.php
365
366                 if($update) {
367                         $r = q("UPDATE `fcontact` SET
368                                         `name` = '%s',
369                                         `photo` = '%s',
370                                         `request` = '%s',
371                                         `nick` = '%s',
372                                         `addr` = '%s',
373                                         `batch` = '%s',
374                                         `notify` = '%s',
375                                         `poll` = '%s',
376                                         `confirm` = '%s',
377                                         `alias` = '%s',
378                                         `pubkey` = '%s',
379                                         `updated` = '%s'
380                                 WHERE `url` = '%s' AND `network` = '%s'",
381                                         dbesc($arr["name"]),
382                                         dbesc($arr["photo"]),
383                                         dbesc($arr["request"]),
384                                         dbesc($arr["nick"]),
385                                         dbesc($arr["addr"]),
386                                         dbesc($arr["batch"]),
387                                         dbesc($arr["notify"]),
388                                         dbesc($arr["poll"]),
389                                         dbesc($arr["confirm"]),
390                                         dbesc($arr["alias"]),
391                                         dbesc($arr["pubkey"]),
392                                         dbesc(datetime_convert()),
393                                         dbesc($arr["url"]),
394                                         dbesc($arr["network"])
395                                 );
396                 } else {
397                         $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
398                                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
399                                 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
400                                         dbesc($arr["url"]),
401                                         dbesc($arr["name"]),
402                                         dbesc($arr["photo"]),
403                                         dbesc($arr["request"]),
404                                         dbesc($arr["nick"]),
405                                         dbesc($arr["addr"]),
406                                         dbesc($arr["batch"]),
407                                         dbesc($arr["notify"]),
408                                         dbesc($arr["poll"]),
409                                         dbesc($arr["confirm"]),
410                                         dbesc($arr["network"]),
411                                         dbesc($arr["alias"]),
412                                         dbesc($arr["pubkey"]),
413                                         dbesc(datetime_convert())
414                                 );
415                 }
416
417                 return $r;
418         }
419
420         private function get_contact_by_handle($uid, $handle) {
421                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
422                         intval($uid),
423                         dbesc($handle)
424                 );
425
426                 if ($r)
427                         return $r[0];
428
429                 $handle_parts = explode("@", $handle);
430                 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
431                 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
432                         dbesc(NETWORK_DFRN),
433                         intval($uid),
434                         dbesc($nurl_sql)
435                 );
436                 if($r)
437                         return $r[0];
438
439                 return false;
440         }
441
442         private function post_allow($importer, $contact, $is_comment = false) {
443
444                 // perhaps we were already sharing with this person. Now they're sharing with us.
445                 // That makes us friends.
446                 // Normally this should have handled by getting a request - but this could get lost
447                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
448                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
449                                 intval(CONTACT_IS_FRIEND),
450                                 intval($contact["id"]),
451                                 intval($importer["uid"])
452                         );
453                         $contact["rel"] = CONTACT_IS_FRIEND;
454                         logger("defining user ".$contact["nick"]." as friend");
455                 }
456
457                 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
458                         return false;
459                 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
460                         return true;
461                 if($contact["rel"] == CONTACT_IS_FOLLOWER)
462                         if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
463                                 return true;
464
465                 // Messages for the global users are always accepted
466                 if ($importer["uid"] == 0)
467                         return true;
468
469                 return false;
470         }
471
472         private function get_allowed_contact_by_handle($importer, $handle, $is_comment = false) {
473                 $contact = self::get_contact_by_handle($importer["uid"], $handle);
474                 if (!$contact) {
475                         logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
476                         return false;
477                 }
478
479                 if (!self::post_allow($importer, $contact, false)) {
480                         logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
481                         return false;
482                 }
483                 return $contact;
484         }
485
486         private function message_exists($uid, $guid) {
487                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
488                         intval($uid),
489                         dbesc($guid)
490                 );
491
492                 if($r) {
493                         logger("message ".$guid." already exists for user ".$uid);
494                         return false;
495                 }
496
497                 return true;
498         }
499
500         private function fetch_guid($item) {
501                 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
502                         function ($match) use ($item){
503                                 return(self::fetch_guid_sub($match, $item));
504                         },$item["body"]);
505         }
506
507         private function fetch_guid_sub($match, $item) {
508                 if (!self::store_by_guid($match[1], $item["author-link"]))
509                         self::store_by_guid($match[1], $item["owner-link"]);
510         }
511
512         private function store_by_guid($guid, $server, $uid = 0) {
513                 $serverparts = parse_url($server);
514                 $server = $serverparts["scheme"]."://".$serverparts["host"];
515
516                 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
517
518                 $msg = self::fetch_message($guid, $server);
519
520                 if (!$msg)
521                         return false;
522
523                 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
524
525                 // Now call the dispatcher
526                 return self::dispatch_public($msg);
527         }
528
529         private function fetch_message($guid, $server, $level = 0) {
530
531                 if ($level > 5)
532                         return false;
533
534                 // This will work for Diaspora and newer Friendica servers
535                 $source_url = $server."/p/".$guid.".xml";
536                 $x = fetch_url($source_url);
537                 if(!$x)
538                         return false;
539
540                 $source_xml = parse_xml_string($x, false);
541
542                 if (!is_object($source_xml))
543                         return false;
544
545                 if ($source_xml->post->reshare) {
546                         // Reshare of a reshare - old Diaspora version
547                         return self::fetch_message($source_xml->post->reshare->root_guid, $server, ++$level);
548                 } elseif ($source_xml->getName() == "reshare") {
549                         // Reshare of a reshare - new Diaspora version
550                         return self::fetch_message($source_xml->root_guid, $server, ++$level);
551                 }
552
553                 // Fetch the author - for the old and the new Diaspora version
554                 if ($source_xml->post->status_message->diaspora_handle)
555                         $author = (string)$source_xml->post->status_message->diaspora_handle;
556                 elseif ($source_xml->author)
557                         $author = (string)$source_xml->author;
558
559                 if (!$author)
560                         return false;
561
562                 $msg = array("message" => $x, "author" => $author);
563
564                 $msg["key"] = self::get_key($msg["author"]);
565
566                 return $msg;
567         }
568
569         private function fetch_parent_item($uid, $guid, $author, $contact) {
570                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
571                                 `author-name`, `author-link`, `author-avatar`,
572                                 `owner-name`, `owner-link`, `owner-avatar`
573                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
574                         intval($uid), dbesc($guid));
575
576                 if(!$r) {
577                         $result = self::store_by_guid($guid, $contact["url"], $uid);
578
579                         if (!$result) {
580                                 $person = self::get_person_by_handle($author);
581                                 $result = self::store_by_guid($guid, $person["url"], $uid);
582                         }
583
584                         if ($result) {
585                                 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
586
587                                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
588                                                 `author-name`, `author-link`, `author-avatar`,
589                                                 `owner-name`, `owner-link`, `owner-avatar`
590                                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
591                                         intval($uid), dbesc($guid));
592                         }
593                 }
594
595                 if (!$r) {
596                         logger("parent item not found: parent: ".$guid." item: ".$guid);
597                         return false;
598                 } else
599                         return $r[0];
600         }
601
602         private function get_author_contact_by_url($contact, $person, $uid) {
603
604                 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
605                         dbesc(normalise_link($person["url"])), intval($uid));
606                 if ($r) {
607                         $cid = $r[0]["id"];
608                         $network = $r[0]["network"];
609                 } else {
610                         $cid = $contact["id"];
611                         $network = NETWORK_DIASPORA;
612                 }
613
614                 return (array("cid" => $cid, "network" => $network));
615         }
616
617         public static function is_redmatrix($url) {
618                 return(strstr($url, "/channel/"));
619         }
620
621         private function plink($addr, $guid) {
622                 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
623
624                 // Fallback
625                 if (!$r)
626                         return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
627
628                 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
629                 // So we try another way as well.
630                 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
631                 if ($s)
632                         $r[0]["network"] = $s[0]["network"];
633
634                 if ($r[0]["network"] == NETWORK_DFRN)
635                         return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
636
637                 if (self::is_redmatrix($r[0]["url"]))
638                         return $r[0]["url"]."/?f=&mid=".$guid;
639
640                 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
641         }
642
643         private function receive_account_deletion($importer, $data) {
644                 $author = notags(unxmlify($data->author));
645
646                 $contact = self::get_contact_by_handle($importer["uid"], $author);
647                 if (!$contact) {
648                         logger("cannot find contact for author: ".$author);
649                         return false;
650                 }
651
652                 // We now remove the contact
653                 contact_remove($contact["id"]);
654                 return true;
655         }
656
657         private function receive_comment($importer, $sender, $data) {
658                 $guid = notags(unxmlify($data->guid));
659                 $parent_guid = notags(unxmlify($data->parent_guid));
660                 $text = unxmlify($data->text);
661                 $author = notags(unxmlify($data->author));
662
663                 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
664                 if (!$contact)
665                         return false;
666
667                 if (self::message_exists($importer["uid"], $guid))
668                         return false;
669
670                 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
671                 if (!$parent_item)
672                         return false;
673
674                 $person = self::get_person_by_handle($author);
675                 if (!is_array($person)) {
676                         logger("unable to find author details");
677                         return false;
678                 }
679
680                 // Fetch the contact id - if we know this contact
681                 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
682
683                 $datarray = array();
684
685                 $datarray["uid"] = $importer["uid"];
686                 $datarray["contact-id"] = $author_contact["cid"];
687                 $datarray["network"]  = $author_contact["network"];
688
689                 $datarray["author-name"] = $person["name"];
690                 $datarray["author-link"] = $person["url"];
691                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
692
693                 $datarray["owner-name"] = $contact["name"];
694                 $datarray["owner-link"] = $contact["url"];
695                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
696
697                 $datarray["guid"] = $guid;
698                 $datarray["uri"] = $author.":".$guid;
699
700                 $datarray["type"] = "remote-comment";
701                 $datarray["verb"] = ACTIVITY_POST;
702                 $datarray["gravity"] = GRAVITY_COMMENT;
703                 $datarray["parent-uri"] = $parent_item["uri"];
704
705                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
706                 $datarray["object"] = json_encode($data);
707
708                 $datarray["body"] = diaspora2bb($text);
709
710                 self::fetch_guid($datarray);
711
712                 $message_id = item_store($datarray);
713                 // print_r($datarray);
714
715                 // If we are the origin of the parent we store the original data and notify our followers
716                 if($message_id AND $parent_item["origin"]) {
717
718                         // Formerly we stored the signed text, the signature and the author in different fields.
719                         // We now store the raw data so that we are more flexible.
720                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
721                                 intval($message_id),
722                                 dbesc(json_encode($data))
723                         );
724
725                         // notify others
726                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
727                 }
728
729                 return $message_id;
730         }
731
732         private function receive_conversation_message($importer, $contact, $data, $msg, $mesg) {
733                 $guid = notags(unxmlify($data->guid));
734                 $subject = notags(unxmlify($data->subject));
735                 $author = notags(unxmlify($data->author));
736
737                 $reply = 0;
738
739                 $msg_guid = notags(unxmlify($mesg->guid));
740                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
741                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
742                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
743                 $msg_text = unxmlify($mesg->text);
744                 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
745
746                 // "diaspora_handle" is the element name from the old version
747                 // "author" is the element name from the new version
748                 if ($mesg->author)
749                         $msg_author = notags(unxmlify($mesg->author));
750                 elseif ($mesg->diaspora_handle)
751                         $msg_author = notags(unxmlify($mesg->diaspora_handle));
752                 else
753                         return false;
754
755                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
756
757                 if($msg_conversation_guid != $guid) {
758                         logger("message conversation guid does not belong to the current conversation.");
759                         return false;
760                 }
761
762                 $body = diaspora2bb($msg_text);
763                 $message_uri = $msg_author.":".$msg_guid;
764
765                 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
766
767                 $author_signature = base64_decode($msg_author_signature);
768
769                 if(strcasecmp($msg_author,$msg["author"]) == 0) {
770                         $person = $contact;
771                         $key = $msg["key"];
772                 } else {
773                         $person = self::get_person_by_handle($msg_author);
774
775                         if (is_array($person) && x($person, "pubkey"))
776                                 $key = $person["pubkey"];
777                         else {
778                                 logger("unable to find author details");
779                                         return false;
780                         }
781                 }
782
783                 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
784                         logger("verification failed.");
785                         return false;
786                 }
787
788                 if($msg_parent_author_signature) {
789                         $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
790
791                         $parent_author_signature = base64_decode($msg_parent_author_signature);
792
793                         $key = $msg["key"];
794
795                         if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
796                                 logger("owner verification failed.");
797                                 return false;
798                         }
799                 }
800
801                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
802                         dbesc($message_uri)
803                 );
804                 if($r) {
805                         logger("duplicate message already delivered.", LOGGER_DEBUG);
806                         return false;
807                 }
808
809                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
810                         VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
811                         intval($importer["uid"]),
812                         dbesc($msg_guid),
813                         intval($conversation["id"]),
814                         dbesc($person["name"]),
815                         dbesc($person["photo"]),
816                         dbesc($person["url"]),
817                         intval($contact["id"]),
818                         dbesc($subject),
819                         dbesc($body),
820                         0,
821                         0,
822                         dbesc($message_uri),
823                         dbesc($author.":".$guid),
824                         dbesc($msg_created_at)
825                 );
826
827                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
828                         dbesc(datetime_convert()),
829                         intval($conversation["id"])
830                 );
831
832                 notification(array(
833                         "type" => NOTIFY_MAIL,
834                         "notify_flags" => $importer["notify-flags"],
835                         "language" => $importer["language"],
836                         "to_name" => $importer["username"],
837                         "to_email" => $importer["email"],
838                         "uid" =>$importer["uid"],
839                         "item" => array("subject" => $subject, "body" => $body),
840                         "source_name" => $person["name"],
841                         "source_link" => $person["url"],
842                         "source_photo" => $person["thumb"],
843                         "verb" => ACTIVITY_POST,
844                         "otype" => "mail"
845                 ));
846         }
847
848         private function receive_conversation($importer, $msg, $data) {
849                 $guid = notags(unxmlify($data->guid));
850                 $subject = notags(unxmlify($data->subject));
851                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
852                 $author = notags(unxmlify($data->author));
853                 $participants = notags(unxmlify($data->participants));
854
855                 $messages = $data->message;
856
857                 if (!count($messages)) {
858                         logger("empty conversation");
859                         return false;
860                 }
861
862                 $contact = self::get_allowed_contact_by_handle($importer, $msg["author"], true);
863                 if (!$contact)
864                         return false;
865
866                 $conversation = null;
867
868                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
869                         intval($importer["uid"]),
870                         dbesc($guid)
871                 );
872                 if($c)
873                         $conversation = $c[0];
874                 else {
875                         $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
876                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
877                                 intval($importer["uid"]),
878                                 dbesc($guid),
879                                 dbesc($author),
880                                 dbesc(datetime_convert("UTC", "UTC", $created_at)),
881                                 dbesc(datetime_convert()),
882                                 dbesc($subject),
883                                 dbesc($participants)
884                         );
885                         if($r)
886                                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
887                                         intval($importer["uid"]),
888                                         dbesc($guid)
889                                 );
890
891                         if($c)
892                                 $conversation = $c[0];
893                 }
894                 if (!$conversation) {
895                         logger("unable to create conversation.");
896                         return;
897                 }
898
899                 foreach($messages as $mesg)
900                         self::receive_conversation_message($importer, $contact, $data, $msg, $mesg);
901
902                 return true;
903         }
904
905         private function construct_like_body($contact, $parent_item, $guid) {
906                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
907
908                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
909                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
910                 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
911
912                 return sprintf($bodyverb, $ulink, $alink, $plink);
913         }
914
915         private function construct_like_object($importer, $parent_item) {
916                 $objtype = ACTIVITY_OBJ_NOTE;
917                 $link = xmlify('<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />'."\n") ;
918                 $parent_body = $parent_item["body"];
919
920                 $obj = <<< EOT
921
922                 <object>
923                         <type>$objtype</type>
924                         <local>1</local>
925                         <id>{$parent_item["uri"]}</id>
926                         <link>$link</link>
927                         <title></title>
928                         <content>$parent_body</content>
929                 </object>
930 EOT;
931
932                 return $obj;
933         }
934
935         private function receive_like($importer, $sender, $data) {
936                 $positive = notags(unxmlify($data->positive));
937                 $guid = notags(unxmlify($data->guid));
938                 $parent_type = notags(unxmlify($data->parent_type));
939                 $parent_guid = notags(unxmlify($data->parent_guid));
940                 $author = notags(unxmlify($data->author));
941
942                 // likes on comments aren't supported by Diaspora - only on posts
943                 // But maybe this will be supported in the future, so we will accept it.
944                 if (!in_array($parent_type, array("Post", "Comment")))
945                         return false;
946
947                 $contact = self::get_allowed_contact_by_handle($importer, $sender, true);
948                 if (!$contact)
949                         return false;
950
951                 if (self::message_exists($importer["uid"], $guid))
952                         return false;
953
954                 $parent_item = self::fetch_parent_item($importer["uid"], $parent_guid, $author, $contact);
955                 if (!$parent_item)
956                         return false;
957
958                 $person = self::get_person_by_handle($author);
959                 if (!is_array($person)) {
960                         logger("unable to find author details");
961                         return false;
962                 }
963
964                 // Fetch the contact id - if we know this contact
965                 $author_contact = self::get_author_contact_by_url($contact, $person, $importer["uid"]);
966
967                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
968                 // We would accept this anyhow.
969                 if ($positive === "true")
970                         $verb = ACTIVITY_LIKE;
971                 else
972                         $verb = ACTIVITY_DISLIKE;
973
974                 $datarray = array();
975
976                 $datarray["uid"] = $importer["uid"];
977                 $datarray["contact-id"] = $author_contact["cid"];
978                 $datarray["network"]  = $author_contact["network"];
979
980                 $datarray["author-name"] = $person["name"];
981                 $datarray["author-link"] = $person["url"];
982                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
983
984                 $datarray["owner-name"] = $contact["name"];
985                 $datarray["owner-link"] = $contact["url"];
986                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
987
988                 $datarray["guid"] = $guid;
989                 $datarray["uri"] = $author.":".$guid;
990
991                 $datarray["type"] = "activity";
992                 $datarray["verb"] = $verb;
993                 $datarray["gravity"] = GRAVITY_LIKE;
994                 $datarray["parent-uri"] = $parent_item["uri"];
995
996                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
997                 $datarray["object"] = self::construct_like_object($importer, $parent_item);
998
999                 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1000
1001                 $message_id = item_store($datarray);
1002                 // print_r($datarray);
1003
1004                 // If we are the origin of the parent we store the original data and notify our followers
1005                 if($message_id AND $parent_item["origin"]) {
1006
1007                         // Formerly we stored the signed text, the signature and the author in different fields.
1008                         // We now store the raw data so that we are more flexible.
1009                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1010                                 intval($message_id),
1011                                 dbesc(json_encode($data))
1012                         );
1013
1014                         // notify others
1015                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
1016                 }
1017
1018                 return $message_id;
1019         }
1020
1021         private function receive_message($importer, $data) {
1022                 $guid = notags(unxmlify($data->guid));
1023                 $parent_guid = notags(unxmlify($data->parent_guid));
1024                 $text = unxmlify($data->text);
1025                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1026                 $author = notags(unxmlify($data->author));
1027                 $conversation_guid = notags(unxmlify($data->conversation_guid));
1028
1029                 $contact = self::get_allowed_contact_by_handle($importer, $author, true);
1030                 if (!$contact)
1031                         return false;
1032
1033                 $conversation = null;
1034
1035                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1036                         intval($importer["uid"]),
1037                         dbesc($conversation_guid)
1038                 );
1039                 if($c)
1040                         $conversation = $c[0];
1041                 else {
1042                         logger("conversation not available.");
1043                         return false;
1044                 }
1045
1046                 $reply = 0;
1047
1048                 $body = diaspora2bb($text);
1049                 $message_uri = $author.":".$guid;
1050
1051                 $person = self::get_person_by_handle($author);
1052                 if (!$person) {
1053                         logger("unable to find author details");
1054                         return false;
1055                 }
1056
1057                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1058                         dbesc($message_uri),
1059                         intval($importer["uid"])
1060                 );
1061                 if($r) {
1062                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1063                         return false;
1064                 }
1065
1066                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1067                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1068                         intval($importer["uid"]),
1069                         dbesc($guid),
1070                         intval($conversation["id"]),
1071                         dbesc($person["name"]),
1072                         dbesc($person["photo"]),
1073                         dbesc($person["url"]),
1074                         intval($contact["id"]),
1075                         dbesc($conversation["subject"]),
1076                         dbesc($body),
1077                         0,
1078                         1,
1079                         dbesc($message_uri),
1080                         dbesc($author.":".$parent_guid),
1081                         dbesc($created_at)
1082                 );
1083
1084                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1085                         dbesc(datetime_convert()),
1086                         intval($conversation["id"])
1087                 );
1088
1089                 return true;
1090         }
1091
1092         private function receive_participation($importer, $data) {
1093                 // I'm not sure if we can fully support this message type
1094                 return true;
1095         }
1096
1097         private function receive_photo($importer, $data) {
1098                 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1099                 return true;
1100         }
1101
1102         private function receive_poll_participation($importer, $data) {
1103                 // We don't support polls by now
1104                 return true;
1105         }
1106
1107         private function receive_profile($importer, $data) {
1108                 $author = notags(unxmlify($data->author));
1109
1110                 $contact = self::get_contact_by_handle($importer["uid"], $author);
1111                 if (!$contact)
1112                         return;
1113
1114                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1115                 $image_url = unxmlify($data->image_url);
1116                 $birthday = unxmlify($data->birthday);
1117                 $location = diaspora2bb(unxmlify($data->location));
1118                 $about = diaspora2bb(unxmlify($data->bio));
1119                 $gender = unxmlify($data->gender);
1120                 $searchable = (unxmlify($data->searchable) == "true");
1121                 $nsfw = (unxmlify($data->nsfw) == "true");
1122                 $tags = unxmlify($data->tag_string);
1123
1124                 $tags = explode("#", $tags);
1125
1126                 $keywords = array();
1127                 foreach ($tags as $tag) {
1128                         $tag = trim(strtolower($tag));
1129                         if ($tag != "")
1130                                 $keywords[] = $tag;
1131                 }
1132
1133                 $keywords = implode(", ", $keywords);
1134
1135                 $handle_parts = explode("@", $author);
1136                 $nick = $handle_parts[0];
1137
1138                 if($name === "")
1139                         $name = $handle_parts[0];
1140
1141                 if( preg_match("|^https?://|", $image_url) === 0)
1142                         $image_url = "http://".$handle_parts[1].$image_url;
1143
1144                 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1145
1146                 // Generic birthday. We don't know the timezone. The year is irrelevant.
1147
1148                 $birthday = str_replace("1000", "1901", $birthday);
1149
1150                 if ($birthday != "")
1151                         $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1152
1153                 // this is to prevent multiple birthday notifications in a single year
1154                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1155
1156                 if(substr($birthday,5) === substr($contact["bd"],5))
1157                         $birthday = $contact["bd"];
1158
1159                 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1160                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1161                         dbesc($name),
1162                         dbesc($nick),
1163                         dbesc($author),
1164                         dbesc(datetime_convert()),
1165                         dbesc($birthday),
1166                         dbesc($location),
1167                         dbesc($about),
1168                         dbesc($keywords),
1169                         dbesc($gender),
1170                         intval($contact["id"]),
1171                         intval($importer["uid"])
1172                 );
1173
1174                 if ($searchable) {
1175                         poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1176                                 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1177                 }
1178
1179                 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1180                                         "photo" => $image_url, "name" => $name, "location" => $location,
1181                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
1182                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1183                                         "hide" => !$searchable, "nsfw" => $nsfw);
1184
1185                 update_gcontact($gcontact);
1186
1187                 return true;
1188         }
1189
1190         private function receive_request_make_friend($importer, $contact) {
1191
1192                 $a = get_app();
1193
1194                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1195                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1196                                 intval(CONTACT_IS_FRIEND),
1197                                 intval($contact["id"]),
1198                                 intval($importer["uid"])
1199                         );
1200                 }
1201                 // send notification
1202
1203                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1204                         intval($importer["uid"])
1205                 );
1206
1207                 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1208
1209                         $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1210                                 intval($importer["uid"])
1211                         );
1212
1213                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1214
1215                         if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1216
1217                                 $arr = array();
1218                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1219                                 $arr["uid"] = $importer["uid"];
1220                                 $arr["contact-id"] = $self[0]["id"];
1221                                 $arr["wall"] = 1;
1222                                 $arr["type"] = 'wall';
1223                                 $arr["gravity"] = 0;
1224                                 $arr["origin"] = 1;
1225                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1226                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1227                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1228                                 $arr["verb"] = ACTIVITY_FRIEND;
1229                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1230
1231                                 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1232                                 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1233                                 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1234                                 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1235
1236                                 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1237                                         ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1238                                 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1239                                 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1240                                 $arr["object"] .= "</link></object>\n";
1241                                 $arr["last-child"] = 1;
1242
1243                                 $arr["allow_cid"] = $user[0]["allow_cid"];
1244                                 $arr["allow_gid"] = $user[0]["allow_gid"];
1245                                 $arr["deny_cid"]  = $user[0]["deny_cid"];
1246                                 $arr["deny_gid"]  = $user[0]["deny_gid"];
1247
1248                                 $i = item_store($arr);
1249                                 if($i)
1250                                         proc_run("php", "include/notifier.php", "activity", $i);
1251
1252                         }
1253
1254                 }
1255         }
1256
1257         private function receive_request($importer, $data) {
1258                 $author = unxmlify($data->author);
1259                 $recipient = unxmlify($data->recipient);
1260
1261                 if (!$author || !$recipient)
1262                         return;
1263
1264                 $contact = self::get_contact_by_handle($importer["uid"],$author);
1265
1266                 if($contact) {
1267
1268                         // perhaps we were already sharing with this person. Now they're sharing with us.
1269                         // That makes us friends.
1270
1271                         self::receive_request_make_friend($importer, $contact);
1272                         return true;
1273                 }
1274
1275                 $ret = self::get_person_by_handle($author);
1276
1277                 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1278                         logger("Cannot resolve diaspora handle ".$author ." for ".$recipient);
1279                         return false;
1280                 }
1281
1282                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1283
1284                 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1285                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1286                         intval($importer["uid"]),
1287                         dbesc($ret["network"]),
1288                         dbesc($ret["addr"]),
1289                         datetime_convert(),
1290                         dbesc($ret["url"]),
1291                         dbesc(normalise_link($ret["url"])),
1292                         dbesc($batch),
1293                         dbesc($ret["name"]),
1294                         dbesc($ret["nick"]),
1295                         dbesc($ret["photo"]),
1296                         dbesc($ret["pubkey"]),
1297                         dbesc($ret["notify"]),
1298                         dbesc($ret["poll"]),
1299                         1,
1300                         2
1301                 );
1302
1303                 // find the contact record we just created
1304
1305                 $contact_record = self::get_contact_by_handle($importer["uid"],$author);
1306
1307                 if (!$contact_record) {
1308                         logger("unable to locate newly created contact record.");
1309                         return;
1310                 }
1311
1312                 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1313                         intval($importer["uid"])
1314                 );
1315
1316                 if($g && intval($g[0]["def_gid"]))
1317                         group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1318
1319                 if($importer["page-flags"] == PAGE_NORMAL) {
1320
1321                         $hash = random_string().(string)time();   // Generate a confirm_key
1322
1323                         $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1324                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1325                                 intval($importer["uid"]),
1326                                 intval($contact_record["id"]),
1327                                 0,
1328                                 0,
1329                                 dbesc(t("Sharing notification from Diaspora network")),
1330                                 dbesc($hash),
1331                                 dbesc(datetime_convert())
1332                         );
1333                 } else {
1334
1335                         // automatic friend approval
1336
1337                         update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1338
1339                         // technically they are sharing with us (CONTACT_IS_SHARING),
1340                         // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1341                         // we are going to change the relationship and make them a follower.
1342
1343                         if($importer["page-flags"] == PAGE_FREELOVE)
1344                                 $new_relation = CONTACT_IS_FRIEND;
1345                         else
1346                                 $new_relation = CONTACT_IS_FOLLOWER;
1347
1348                         $r = q("UPDATE `contact` SET `rel` = %d,
1349                                 `name-date` = '%s',
1350                                 `uri-date` = '%s',
1351                                 `blocked` = 0,
1352                                 `pending` = 0,
1353                                 `writable` = 1
1354                                 WHERE `id` = %d
1355                                 ",
1356                                 intval($new_relation),
1357                                 dbesc(datetime_convert()),
1358                                 dbesc(datetime_convert()),
1359                                 intval($contact_record["id"])
1360                         );
1361
1362                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1363                         if($u)
1364                                 $ret = diaspora_share($u[0], $contact_record);
1365                 }
1366
1367                 return true;
1368         }
1369
1370         private function get_original_item($guid, $orig_author, $author) {
1371
1372                 // Do we already have this item?
1373                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1374                                 `author-name`, `author-link`, `author-avatar`
1375                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1376                         dbesc($guid));
1377
1378                 if($r) {
1379                         logger("reshared message ".$guid." already exists on system.");
1380
1381                         // Maybe it is already a reshared item?
1382                         // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1383                         if (self::is_reshare($r[0]["body"]))
1384                                 $r = array();
1385                         else
1386                                 return $r[0];
1387                 }
1388
1389                 if (!$r) {
1390                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1391                         logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1392                         $item_id = self::store_by_guid($guid, $server);
1393
1394                         if (!$item_id) {
1395                                 $server = "https://".substr($author, strpos($author, "@") + 1);
1396                                 logger("2nd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1397                                 $item = self::store_by_guid($guid, $server);
1398                         }
1399                         if (!$item_id) {
1400                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1401                                 logger("3rd try: reshared message ".$guid." will be fetched from original server: ".$server);
1402                                 $item = self::store_by_guid($guid, $server);
1403                         }
1404                         if (!$item_id) {
1405                                 $server = "http://".substr($author, strpos($author, "@") + 1);
1406                                 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1407                                 $item = self::store_by_guid($guid, $server);
1408                         }
1409
1410                         if ($item_id) {
1411                                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1412                                                 `author-name`, `author-link`, `author-avatar`
1413                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1414                                         intval($item_id));
1415
1416                                 if ($r)
1417                                         return $r[0];
1418
1419                         }
1420                 }
1421                 return false;
1422         }
1423
1424         private function receive_reshare($importer, $data) {
1425                 $root_author = notags(unxmlify($data->root_author));
1426                 $root_guid = notags(unxmlify($data->root_guid));
1427                 $guid = notags(unxmlify($data->guid));
1428                 $author = notags(unxmlify($data->author));
1429                 $public = notags(unxmlify($data->public));
1430                 $created_at = notags(unxmlify($data->created_at));
1431
1432                 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1433                 if (!$contact)
1434                         return false;
1435
1436                 if (self::message_exists($importer["uid"], $guid))
1437                         return false;
1438
1439                 $original_item = self::get_original_item($root_guid, $root_author, $author);
1440                 if (!$original_item)
1441                         return false;
1442
1443                 $datarray = array();
1444
1445                 $datarray["uid"] = $importer["uid"];
1446                 $datarray["contact-id"] = $contact["id"];
1447                 $datarray["network"]  = NETWORK_DIASPORA;
1448
1449                 $datarray["author-name"] = $contact["name"];
1450                 $datarray["author-link"] = $contact["url"];
1451                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1452
1453                 $datarray["owner-name"] = $datarray["author-name"];
1454                 $datarray["owner-link"] = $datarray["author-link"];
1455                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1456
1457                 $datarray["guid"] = $guid;
1458                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1459
1460                 $datarray["verb"] = ACTIVITY_POST;
1461                 $datarray["gravity"] = GRAVITY_PARENT;
1462
1463                 $datarray["object"] = json_encode($data);
1464
1465                 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1466                                         $original_item["guid"], $original_item["created"], $original_item["uri"]);
1467                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1468
1469                 $datarray["tag"] = $original_item["tag"];
1470                 $datarray["app"]  = $original_item["app"];
1471
1472                 $datarray["plink"] = self::plink($author, $guid);
1473                 $datarray["private"] = (($public == "false") ? 1 : 0);
1474                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1475
1476                 $datarray["object-type"] = $original_item["object-type"];
1477
1478                 self::fetch_guid($datarray);
1479                 $message_id = item_store($datarray);
1480                 // print_r($datarray);
1481
1482                 return $message_id;
1483         }
1484
1485         private function item_retraction($importer, $contact, $data) {
1486                 $target_type = notags(unxmlify($data->target_type));
1487                 $target_guid = notags(unxmlify($data->target_guid));
1488                 $author = notags(unxmlify($data->author));
1489
1490                 $person = self::get_person_by_handle($author);
1491                 if (!is_array($person)) {
1492                         logger("unable to find author detail for ".$author);
1493                         return false;
1494                 }
1495
1496                 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1497                         dbesc($target_guid),
1498                         intval($importer["uid"])
1499                 );
1500                 if (!$r)
1501                         return false;
1502
1503                 // Only delete it if the author really fits
1504                 if (!link_compare($r[0]["author-link"],$person["url"]))
1505                         return false;
1506
1507                 // Check if the sender is the thread owner
1508                 $p = q("SELECT `author-link`, `origin` FROM `item` WHERE `id` = %d",
1509                         intval($r[0]["parent"]));
1510
1511                 // Only delete it if the parent author really fits
1512                 if (!link_compare($p[0]["author-link"], $contact["url"]))
1513                         return false;
1514
1515                 // Currently we don't have a central deletion function that we could use in this case. The function "item_drop" doesn't work for that case
1516                 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1517                         dbesc(datetime_convert()),
1518                         dbesc(datetime_convert()),
1519                         intval($r[0]["id"])
1520                 );
1521                 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1522
1523                 // Now check if the retraction needs to be relayed by us
1524                 if($p[0]["origin"]) {
1525
1526                         // Formerly we stored the signed text, the signature and the author in different fields.
1527                         // We now store the raw data so that we are more flexible.
1528                         q("INSERT INTO `sign` (`retract_iid`,`signed_text`) VALUES (%d,'%s')",
1529                                 intval($r[0]["id"]),
1530                                 dbesc(json_encode($data))
1531                         );
1532
1533                         // notify others
1534                         proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1535                 }
1536         }
1537
1538         private function receive_retraction($importer, $sender, $data) {
1539                 $target_type = notags(unxmlify($data->target_type));
1540
1541                 $contact = self::get_contact_by_handle($importer["uid"], $sender);
1542                 if (!$contact) {
1543                         logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1544                         return false;
1545                 }
1546
1547                 switch ($target_type) {
1548                         case "Comment":
1549                         case "Like":
1550                         case "Post": // "Post" will be supported in a future version
1551                         case "Reshare":
1552                         case "StatusMessage":
1553                                 return self::item_retraction($importer, $contact, $data);;
1554
1555                         case "Person": /// @todo an "unshare" shouldn't remove the contact
1556                                 contact_remove($contact["id"]);
1557                                 return true;
1558
1559                         default:
1560                                 logger("Unknown target type ".$target_type);
1561                                 return false;
1562                 }
1563                 return true;
1564         }
1565
1566         private function receive_status_message($importer, $data) {
1567
1568                 $raw_message = unxmlify($data->raw_message);
1569                 $guid = notags(unxmlify($data->guid));
1570                 $author = notags(unxmlify($data->author));
1571                 $public = notags(unxmlify($data->public));
1572                 $created_at = notags(unxmlify($data->created_at));
1573                 $provider_display_name = notags(unxmlify($data->provider_display_name));
1574
1575                 /// @todo enable support for polls
1576                 //if ($data->poll) {
1577                 //      foreach ($data->poll AS $poll)
1578                 //              print_r($poll);
1579                 //      die("poll!\n");
1580                 //}
1581                 $contact = self::get_allowed_contact_by_handle($importer, $author, false);
1582                 if (!$contact)
1583                         return false;
1584
1585                 if (self::message_exists($importer["uid"], $guid))
1586                         return false;
1587
1588                 $address = array();
1589                 if ($data->location)
1590                         foreach ($data->location->children() AS $fieldname => $data)
1591                                 $address[$fieldname] = notags(unxmlify($data));
1592
1593                 $body = diaspora2bb($raw_message);
1594
1595                 $datarray = array();
1596
1597                 if ($data->photo) {
1598                         foreach ($data->photo AS $photo)
1599                                 $body = "[img]".$photo->remote_photo_path.$photo->remote_photo_name."[/img]\n".$body;
1600
1601                         $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1602                 } else {
1603                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1604
1605                         // Add OEmbed and other information to the body
1606                         if (!self::is_redmatrix($contact["url"]))
1607                                 $body = add_page_info_to_body($body, false, true);
1608                 }
1609
1610                 $datarray["uid"] = $importer["uid"];
1611                 $datarray["contact-id"] = $contact["id"];
1612                 $datarray["network"] = NETWORK_DIASPORA;
1613
1614                 $datarray["author-name"] = $contact["name"];
1615                 $datarray["author-link"] = $contact["url"];
1616                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1617
1618                 $datarray["owner-name"] = $datarray["author-name"];
1619                 $datarray["owner-link"] = $datarray["author-link"];
1620                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1621
1622                 $datarray["guid"] = $guid;
1623                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1624
1625                 $datarray["verb"] = ACTIVITY_POST;
1626                 $datarray["gravity"] = GRAVITY_PARENT;
1627
1628                 $datarray["object"] = json_encode($data);
1629
1630                 $datarray["body"] = $body;
1631
1632                 if ($provider_display_name != "")
1633                         $datarray["app"] = $provider_display_name;
1634
1635                 $datarray["plink"] = self::plink($author, $guid);
1636                 $datarray["private"] = (($public == "false") ? 1 : 0);
1637                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1638
1639                 if (isset($address["address"]))
1640                         $datarray["location"] = $address["address"];
1641
1642                 if (isset($address["lat"]) AND isset($address["lng"]))
1643                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
1644
1645                 self::fetch_guid($datarray);
1646                 $message_id = item_store($datarray);
1647                 // print_r($datarray);
1648
1649                 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
1650
1651                 return $message_id;
1652         }
1653
1654         /*******************************************************************************************
1655          * Here come all the functions that are needed to transmit data with the Diaspora protocol *
1656          *******************************************************************************************/
1657
1658         private function get_my_handle($me) {
1659                 if ($contact["addr"] != "")
1660                         return $contact["addr"];
1661
1662                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
1663                 // So - just in case - we build the the address here.
1664                 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
1665         }
1666
1667         private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
1668
1669                 logger("Message: ".$msg, LOGGER_DATA);
1670
1671                 $handle = self::get_my_handle($user);
1672
1673                 $b64url_data = base64url_encode($msg);
1674
1675                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1676
1677                 $type = "application/xml";
1678                 $encoding = "base64url";
1679                 $alg = "RSA-SHA256";
1680
1681                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1682
1683                 $signature = rsa_sign($signable_data,$prvkey);
1684                 $sig = base64url_encode($signature);
1685
1686 $magic_env = <<< EOT
1687 <?xml version='1.0' encoding='UTF-8'?>
1688 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
1689   <header>
1690     <author_id>$handle</author_id>
1691   </header>
1692   <me:env>
1693     <me:encoding>base64url</me:encoding>
1694     <me:alg>RSA-SHA256</me:alg>
1695     <me:data type="application/xml">$data</me:data>
1696     <me:sig>$sig</me:sig>
1697   </me:env>
1698 </diaspora>
1699 EOT;
1700
1701                 logger("magic_env: ".$magic_env, LOGGER_DATA);
1702                 return $magic_env;
1703         }
1704
1705         private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
1706
1707                 logger("Message: ".$msg, LOGGER_DATA);
1708
1709                 // without a public key nothing will work
1710
1711                 if (!$pubkey) {
1712                         logger("pubkey missing: contact id: ".$contact["id"]);
1713                         return false;
1714                 }
1715
1716                 $inner_aes_key = random_string(32);
1717                 $b_inner_aes_key = base64_encode($inner_aes_key);
1718                 $inner_iv = random_string(16);
1719                 $b_inner_iv = base64_encode($inner_iv);
1720
1721                 $outer_aes_key = random_string(32);
1722                 $b_outer_aes_key = base64_encode($outer_aes_key);
1723                 $outer_iv = random_string(16);
1724                 $b_outer_iv = base64_encode($outer_iv);
1725
1726                 $handle = self::get_my_handle($user);
1727
1728                 $padded_data = pkcs5_pad($msg,16);
1729                 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
1730
1731                 $b64_data = base64_encode($inner_encrypted);
1732
1733
1734                 $b64url_data = base64url_encode($b64_data);
1735                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1736
1737                 $type = "application/xml";
1738                 $encoding = "base64url";
1739                 $alg = "RSA-SHA256";
1740
1741                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1742
1743                 $signature = rsa_sign($signable_data,$prvkey);
1744                 $sig = base64url_encode($signature);
1745
1746 $decrypted_header = <<< EOT
1747 <decrypted_header>
1748   <iv>$b_inner_iv</iv>
1749   <aes_key>$b_inner_aes_key</aes_key>
1750   <author_id>$handle</author_id>
1751 </decrypted_header>
1752 EOT;
1753
1754                 $decrypted_header = pkcs5_pad($decrypted_header,16);
1755
1756                 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
1757
1758                 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
1759
1760                 $encrypted_outer_key_bundle = "";
1761                 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
1762
1763                 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
1764
1765                 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
1766
1767                 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
1768                                                                 "ciphertext" => base64_encode($ciphertext)));
1769                 $cipher_json = base64_encode($encrypted_header_json_object);
1770
1771                 $encrypted_header = "<encrypted_header>".$cipher_json."</encrypted_header>";
1772
1773 $magic_env = <<< EOT
1774 <?xml version='1.0' encoding='UTF-8'?>
1775 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
1776   $encrypted_header
1777   <me:env>
1778     <me:encoding>base64url</me:encoding>
1779     <me:alg>RSA-SHA256</me:alg>
1780     <me:data type="application/xml">$data</me:data>
1781     <me:sig>$sig</me:sig>
1782   </me:env>
1783 </diaspora>
1784 EOT;
1785
1786                 logger("magic_env: ".$magic_env, LOGGER_DATA);
1787                 return $magic_env;
1788         }
1789
1790         private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
1791
1792                 if ($public)
1793                         $magic_env =  self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
1794                 else
1795                         $magic_env =  self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
1796
1797                 // The data that will be transmitted is double encoded via "urlencode", strange ...
1798                 $slap = "xml=".urlencode(urlencode($magic_env));
1799                 return $slap;
1800         }
1801
1802         private function get_signature($owner, $message) {
1803                 $sigmsg = $message;
1804                 unset($sigmsg["author_signature"]);
1805                 unset($sigmsg["parent_author_signature"]);
1806
1807                 $signed_text = implode(";", $sigmsg);
1808
1809                 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
1810         }
1811
1812         private function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
1813
1814                 $a = get_app();
1815
1816                 $enabled = intval(get_config("system", "diaspora_enabled"));
1817                 if(!$enabled)
1818                         return 200;
1819
1820                 $logid = random_string(4);
1821                 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
1822                 if (!$dest_url) {
1823                         logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
1824                         return 0;
1825                 }
1826
1827                 logger("transmit: ".$logid."-".$guid." ".$dest_url);
1828
1829                 if (!$queue_run && was_recently_delayed($contact["id"])) {
1830                         $return_code = 0;
1831                 } else {
1832                         if (!intval(get_config("system", "diaspora_test"))) {
1833                                 post_url($dest_url."/", $slap);
1834                                 $return_code = $a->get_curl_code();
1835                         } else {
1836                                 logger("test_mode");
1837                                 return 200;
1838                         }
1839                 }
1840
1841                 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
1842
1843                 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
1844                         logger("queue message");
1845
1846                         $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
1847                                 intval($contact["id"]),
1848                                 dbesc(NETWORK_DIASPORA),
1849                                 dbesc($slap),
1850                                 intval($public_batch)
1851                         );
1852                         if(count($r)) {
1853                                 logger("add_to_queue ignored - identical item already in queue");
1854                         } else {
1855                                 // queue message for redelivery
1856                                 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
1857                         }
1858                 }
1859
1860
1861                 return(($return_code) ? $return_code : (-1));
1862         }
1863
1864         public static function send_share($me,$contact) {
1865                 $myaddr = self::get_my_handle($me);
1866                 $theiraddr = $contact["addr"];
1867
1868                 $data = array("XML" => array("post" => array("request" => array(
1869                                                                                 "sender_handle" => $myaddr,
1870                                                                                 "recipient_handle" => $theiraddr
1871                                                                         ))));
1872
1873                 $msg = xml::from_array($data, $xml);
1874
1875                 $slap = self::build_message($msg, $me, $contact, $me["prvkey"], $contact["pubkey"]);
1876
1877                 return(self::transmit($owner,$contact,$slap, false));
1878
1879         }
1880
1881         public static function send_unshare($me,$contact) {
1882                 $myaddr = self::get_my_handle($me);
1883
1884                 $data = array("XML" => array("post" => array("retraction" => array(
1885                                                                                 "post_guid" => $me["guid"],
1886                                                                                 "diaspora_handle" => $myaddr,
1887                                                                                 "type" => "Person"
1888                                                                         ))));
1889
1890                 $msg = xml::from_array($data, $xml);
1891
1892                 $slap = self::build_message($msg, $me, $contact, $me["prvkey"], $contact["pubkey"]);
1893
1894                 return(self::transmit($owner,$contact,$slap, false));
1895         }
1896
1897         private function is_reshare($body) {
1898                 $body = trim($body);
1899
1900                 // Skip if it isn't a pure repeated messages
1901                 // Does it start with a share?
1902                 if (strpos($body, "[share") > 0)
1903                         return(false);
1904
1905                 // Does it end with a share?
1906                 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1907                         return(false);
1908
1909                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1910                 // Skip if there is no shared message in there
1911                 if ($body == $attributes)
1912                         return(false);
1913
1914                 $guid = "";
1915                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1916                 if ($matches[1] != "")
1917                         $guid = $matches[1];
1918
1919                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1920                 if ($matches[1] != "")
1921                         $guid = $matches[1];
1922
1923                 if ($guid != "") {
1924                         $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
1925                                 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
1926                         if ($r) {
1927                                 $ret= array();
1928                                 $ret["root_handle"] = diaspora_handle_from_contact($r[0]["contact-id"]);
1929                                 $ret["root_guid"] = $guid;
1930                                 return($ret);
1931                         }
1932                 }
1933
1934                 $profile = "";
1935                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
1936                 if ($matches[1] != "")
1937                         $profile = $matches[1];
1938
1939                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
1940                 if ($matches[1] != "")
1941                         $profile = $matches[1];
1942
1943                 $ret= array();
1944
1945                 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
1946                 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
1947                         return(false);
1948
1949                 $link = "";
1950                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1951                 if ($matches[1] != "")
1952                         $link = $matches[1];
1953
1954                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1955                 if ($matches[1] != "")
1956                         $link = $matches[1];
1957
1958                 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
1959                 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
1960                         return(false);
1961                 return($ret);
1962         }
1963
1964         public static function send_status($item, $owner, $contact, $public_batch = false) {
1965
1966                 $myaddr = self::get_my_handle($owner);
1967                 $theiraddr = $contact["addr"];
1968
1969                 $title = $item["title"];
1970                 $body = $item["body"];
1971
1972                 // convert to markdown
1973                 $body = html_entity_decode(bb2diaspora($body));
1974
1975                 // Adding the title
1976                 if(strlen($title))
1977                         $body = "## ".html_entity_decode($title)."\n\n".$body;
1978
1979                 if ($item["attach"]) {
1980                         $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
1981                         if(cnt) {
1982                                 $body .= "\n".t("Attachments:")."\n";
1983                                 foreach($matches as $mtch)
1984                                         $body .= "[".$mtch[3]."](".$mtch[1].")\n";
1985                         }
1986                 }
1987
1988
1989                 $public = (($item["private"]) ? "false" : "true");
1990
1991                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
1992
1993                 // Detect a share element and do a reshare
1994                 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
1995                         $message = array("root_diaspora_id" => $ret["root_handle"],
1996                                         "root_guid" => $ret["root_guid"],
1997                                         "guid" => $item["guid"],
1998                                         "diaspora_handle" => $myaddr,
1999                                         "public" => $public,
2000                                         "created_at" => $created,
2001                                         "provider_display_name" => $item["app"]);
2002
2003                         $data = array("XML" => array("post" => array("reshare" => $message)));
2004                 } else {
2005                         $location = array();
2006
2007                         if ($item["location"] != "")
2008                                 $location["address"] = $item["location"];
2009
2010                         if ($item["coord"] != "") {
2011                                 $coord = explode(" ", $item["coord"]);
2012                                 $location["lat"] = $coord[0];
2013                                 $location["lng"] = $coord[1];
2014                         }
2015
2016                         $message = array("raw_message" => $body,
2017                                         "location" => $location,
2018                                         "guid" => $item["guid"],
2019                                         "diaspora_handle" => $myaddr,
2020                                         "public" => $public,
2021                                         "created_at" => $created,
2022                                         "provider_display_name" => $item["app"]);
2023
2024                         if (count($location) == 0)
2025                                 unset($message["location"]);
2026
2027                         $data = array("XML" => array("post" => array("status_message" => $message)));
2028                 }
2029
2030                 $msg = xml::from_array($data, $xml);
2031
2032                 logger("status: ".$owner["username"]." -> ".$contact["name"]." base message: ".$msg, LOGGER_DATA);
2033                 logger("send guid ".$item["guid"], LOGGER_DEBUG);
2034
2035                 $slap = self::build_message($msg, $owner, $contact, $owner["uprvkey"], $contact["pubkey"], $public_batch);
2036
2037                 $return_code = self::transmit($owner,$contact,$slap, false);
2038
2039                 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2040
2041                 return $return_code;
2042         }
2043
2044         private function construct_like($item,$owner,$contact,$public_batch = false, $data = null) {
2045
2046                 if (is_array($data))
2047                         $message = $data;
2048                 else {
2049                         $myaddr = self::get_my_handle($owner);
2050
2051                         $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2052                                 dbesc($item["thr-parent"]));
2053                         if(!$p)
2054                                 return false;
2055
2056                         $parent = $p[0];
2057
2058                         $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2059                         $positive = "true";
2060
2061                         $message = array("positive" => $positive,
2062                                         "guid" => $item["guid"],
2063                                         "target_type" => $target_type,
2064                                         "parent_guid" => $parent["guid"],
2065                                         "author_signature" => $authorsig,
2066                                         "diaspora_handle" => $myaddr);
2067                 }
2068
2069                 $authorsig = self::get_signature($owner, $message);
2070
2071                 if ($message["author_signature"] == "")
2072                         $message["author_signature"] = $authorsig;
2073                 else
2074                         $message["parent_author_signature"] = $authorsig;
2075
2076                 $data = array("XML" => array("post" => array("like" => $message)));
2077
2078                 return xml::from_array($data, $xml);
2079         }
2080
2081         private function construct_comment($item,$owner,$contact,$public_batch = false, $data = null) {
2082
2083                 if (is_array($data))
2084                         $message = $data;
2085                 else {
2086                         $myaddr = self::get_my_handle($owner);
2087
2088                         $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2089                                 intval($item["parent"]),
2090                                 intval($item["parent"])
2091                         );
2092
2093                         if (!$p)
2094                                 return false;
2095
2096                         $parent = $p[0];
2097
2098                         $text = html_entity_decode(bb2diaspora($item["body"]));
2099
2100                         $message = array("guid" => $item["guid"],
2101                                         "parent_guid" => $parent["guid"],
2102                                         "author_signature" => "",
2103                                         "text" => $text,
2104                                         "diaspora_handle" => $myaddr);
2105                 }
2106
2107                 $authorsig = self::get_signature($owner, $message);
2108
2109                 if ($message["author_signature"] == "")
2110                         $message["author_signature"] = $authorsig;
2111                 else
2112                         $message["parent_author_signature"] = $authorsig;
2113
2114                 $data = array("XML" => array("post" => array("comment" => $message)));
2115
2116                 return xml::from_array($data, $xml);
2117         }
2118
2119         public static function send_followup($item,$owner,$contact,$public_batch = false) {
2120
2121                 if($item['verb'] === ACTIVITY_LIKE)
2122                         $msg = self::construct_like($item, $owner, $contact, $public_batch);
2123                 else
2124                         $msg = self::construct_comment($item, $owner, $contact, $public_batch);
2125
2126                 if (!$msg)
2127                         return $msg;
2128
2129                 logger("base message: ".$msg, LOGGER_DATA);
2130                 logger("send guid ".$item["guid"], LOGGER_DEBUG);
2131
2132                 $slap = self::build_message($msg, $owner, $contact, $owner["uprvkey"], $contact["pubkey"], $public_batch);
2133
2134                 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $item["guid"]);
2135
2136                 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2137
2138                 return $return_code;
2139         }
2140
2141         function send_relay($item, $owner, $contact, $public_batch = false) {
2142
2143                 if ($item["deleted"])
2144                         $sql_sign_id = "retract_iid";
2145                 else
2146                         $sql_sign_id = "iid";
2147
2148                 // fetch the original signature if the relayable was created by a Diaspora
2149                 // or DFRN user.
2150
2151                 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `".$sql_sign_id."` = %d LIMIT 1",
2152                         intval($item["id"])
2153                 );
2154
2155                 if(count($r)) {
2156                         $orig_sign = $r[0];
2157                         $signed_text = $orig_sign['signed_text'];
2158                         $authorsig = $orig_sign['signature'];
2159                         $handle = $orig_sign['signer'];
2160
2161                         // Split the signed text
2162                         $signed_parts = explode(";", $signed_text);
2163
2164                         if ($item['verb'] === ACTIVITY_LIKE) {
2165                                 $data = array("positive" => $signed_parts[0],
2166                                                 "guid" => $signed_parts[1],
2167                                                 "target_type" => $signed_parts[2],
2168                                                 "parent_guid" => $signed_parts[3],
2169                                                 "parent_author_signature" => "",
2170                                                 "author_signature" => $orig_sign['signature'],
2171                                                 "diaspora_handle" => $signed_parts[4]);
2172                         } else {
2173                                 // Remove the comment guid
2174                                 $guid = array_shift($signed_parts);
2175
2176                                 // Remove the parent guid
2177                                 $parent_guid = array_shift($signed_parts);
2178
2179                                 // Remove the handle
2180                                 $handle = array_pop($signed_parts);
2181
2182                                 // Glue the parts together
2183                                 $text = implode(";", $signed_parts);
2184
2185                                 $data = array("guid" => $guid,
2186                                                 "parent_guid" => $parent_guid,
2187                                                 "parent_author_signature" => "",
2188                                                 "author_signature" => $orig_sign['signature'],
2189                                                 "text" => implode(";", $signed_parts),
2190                                                 "diaspora_handle" => $handle);
2191                         }
2192                 }
2193
2194                 if ($item['deleted'])
2195                         ; // Relayed Retraction
2196                 elseif($item['verb'] === ACTIVITY_LIKE)
2197                         $msg = self::construct_like($item, $owner, $contact, $public_batch, $data);
2198                 else
2199                         $msg = self::construct_comment($item, $owner, $contact, $public_batch, $data);
2200 die($msg);
2201
2202                 logger('base message: '.$msg, LOGGER_DATA);
2203                 logger('send guid '.$item['guid'], LOGGER_DEBUG);
2204
2205                 $slap = self::build_message($msg,$owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2206
2207                 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $item['guid']);
2208
2209                 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2210
2211                 return $return_code;
2212         }
2213
2214 /*
2215         // Diaspora doesn't support threaded comments, but some
2216         // versions of Diaspora (i.e. Diaspora-pistos) support
2217         // likes on comments
2218         if($item['verb'] === ACTIVITY_LIKE && $item['thr-parent']) {
2219                 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2220                         dbesc($item['thr-parent'])
2221                       );
2222         }
2223         else {
2224                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2225                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2226                 // The only item with `parent` and `id` as the parent id is the parent item.
2227                 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2228                        intval($item['parent']),
2229                        intval($item['parent'])
2230                       );
2231         }
2232         if(count($p))
2233                 $parent = $p[0];
2234         else
2235                 return;
2236
2237         $like = false;
2238         $relay_retract = false;
2239         $sql_sign_id = 'iid';
2240         if( $item['deleted']) {
2241                 $relay_retract = true;
2242
2243                 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2244
2245                 $sql_sign_id = 'retract_iid';
2246                 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2247         }
2248         elseif($item['verb'] === ACTIVITY_LIKE) {
2249                 $like = true;
2250
2251                 $target_type = ( $parent['uri'] === $parent['parent-uri']  ? 'Post' : 'Comment');
2252 //              $positive = (($item['deleted']) ? 'false' : 'true');
2253                 $positive = 'true';
2254
2255                 $tpl = get_markup_template('diaspora_like_relay.tpl');
2256         }
2257         else { // item is a comment
2258                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2259         }
2260
2261
2262         // fetch the original signature if the relayable was created by a Diaspora
2263         // or DFRN user. Relayables for other networks are not supported.
2264
2265         $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE " . $sql_sign_id . " = %d LIMIT 1",
2266                 intval($item['id'])
2267         );
2268         if(count($r)) {
2269                 $orig_sign = $r[0];
2270                 $signed_text = $orig_sign['signed_text'];
2271                 $authorsig = $orig_sign['signature'];
2272                 $handle = $orig_sign['signer'];
2273
2274                 // Split the signed text
2275                 $signed_parts = explode(";", $signed_text);
2276
2277                 // Remove the parent guid
2278                 array_shift($signed_parts);
2279
2280                 // Remove the comment guid
2281                 array_shift($signed_parts);
2282
2283                 // Remove the handle
2284                 array_pop($signed_parts);
2285
2286                 // Glue the parts together
2287                 $text = implode(";", $signed_parts);
2288         }
2289         else {
2290                 // This part is meant for cases where we don't have the signatur. (Which shouldn't happen with posts from Diaspora and Friendica)
2291                 // This means that the comment won't be accepted by newer Diaspora servers
2292
2293                 $body = $item['body'];
2294                 $text = html_entity_decode(bb2diaspora($body));
2295
2296                 $handle = diaspora_handle_from_contact($item['contact-id']);
2297                 if(! $handle)
2298                         return;
2299
2300                 if($relay_retract)
2301                         $signed_text = $item['guid'] . ';' . $target_type;
2302                 elseif($like)
2303                         $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2304                 else
2305                         $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2306
2307                 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2308         }
2309
2310         // Sign the relayable with the top-level owner's signature
2311         $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2312
2313         $msg = replace_macros($tpl,array(
2314                 '$guid' => xmlify($item['guid']),
2315                 '$parent_guid' => xmlify($parent['guid']),
2316                 '$target_type' =>xmlify($target_type),
2317                 '$authorsig' => xmlify($authorsig),
2318                 '$parentsig' => xmlify($parentauthorsig),
2319                 '$body' => xmlify($text),
2320                 '$positive' => xmlify($positive),
2321                 '$handle' => xmlify($handle)
2322         ));
2323
2324         logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2325         logger('send guid '.$item['guid'], LOGGER_DEBUG);
2326
2327         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2328         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2329
2330         return(diaspora_transmit($owner,$contact,$slap,$public_batch,false,$item['guid']));
2331 */
2332
2333         public static function send_retraction($item, $owner, $contact, $public_batch = false) {
2334
2335                 $myaddr = self::get_my_handle($owner);
2336
2337                 // Check whether the retraction is for a top-level post or whether it's a relayable
2338                 if ($item["uri"] !== $item["parent-uri"]) {
2339                         $msg_type = "relayable_retraction";
2340                         $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2341                 } else {
2342                         $msg_type = "signed_retraction";
2343                         $target_type = "StatusMessage";
2344                 }
2345
2346                 $signed_text = $item["guid"].";".$target_type;
2347
2348                 $message = array("target_guid" => $item['guid'],
2349                                 "target_type" => $target_type,
2350                                 "sender_handle" => $myaddr,
2351                                 "target_author_signature" => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2352
2353                 $data = array("XML" => array("post" => array($msg_type => $message)));
2354                 $msg = xml::from_array($data, $xml);
2355
2356                 logger("send guid ".$item["guid"], LOGGER_DEBUG);
2357
2358                 $slap = self::build_message($msg, $owner, $contact, $owner["uprvkey"], $contact["pubkey"], $public_batch);
2359
2360                 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $item["guid"]);
2361
2362                 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2363
2364                 return $return_code;
2365         }
2366
2367         public static function send_mail($item,$owner,$contact) {
2368
2369                 $myaddr = self::get_my_handle($owner);
2370
2371                 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2372                         intval($item["convid"]),
2373                         intval($item["uid"])
2374                 );
2375
2376                 if (!count($r)) {
2377                         logger("conversation not found.");
2378                         return;
2379                 }
2380                 $cnv = $r[0];
2381
2382                 $conv = array(
2383                         "guid" => $cnv["guid"],
2384                         "subject" => $cnv["subject"],
2385                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2386                         "diaspora_handle" => $cnv["creator"],
2387                         "participant_handles" => $cnv["recips"]
2388                 );
2389
2390                 $body = bb2diaspora($item["body"]);
2391                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2392
2393                 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2394
2395                 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2396
2397                 $msg = array(
2398                         "guid" => $item["guid"],
2399                         "parent_guid" => $cnv["guid"],
2400                         "parent_author_signature" => $sig,
2401                         "author_signature" => $sig,
2402                         "text" => $body,
2403                         "created_at" => $created,
2404                         "diaspora_handle" => $myaddr,
2405                         "conversation_guid" => $cnv["guid"]
2406                 );
2407
2408                 if ($item["reply"])
2409                         $data = array("XML" => array("post" => array("message" => $msg)));
2410                 else {
2411                         $message = array("guid" => $cnv["guid"],
2412                                         "subject" => $cnv["subject"],
2413                                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2414                                         "message" => $msg,
2415                                         "diaspora_handle" => $cnv["creator"],
2416                                         "participant_handles" => $cnv["recips"]);
2417
2418                         $data = array("XML" => array("post" => array("conversation" => $message)));
2419                 }
2420
2421                 $xmsg = xml::from_array($data, $xml);
2422
2423                 logger("conversation: ".print_r($xmsg,true), LOGGER_DATA);
2424                 logger("send guid ".$item["guid"], LOGGER_DEBUG);
2425
2426                 $slap = self::build_message($xmsg, $owner, $contact, $owner["uprvkey"], $contact["pubkey"], false);
2427
2428                 $return_code = self::transmit($owner, $contact, $slap, false, false, $item["guid"]);
2429
2430                 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2431
2432                 return $return_code;
2433         }
2434 }
2435 ?>