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