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