]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
Merge remote-tracking branch 'upstream/develop' into 1612-diaspora
[friendica.git] / include / diaspora.php
1 <?php
2 /**
3  * @file include/diaspora.php
4  * @brief The implementation of the diaspora protocol
5  *
6  * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7  * Currently this implementation here interprets the old and the new protocol and sends the old one.
8  * This will change in the future.
9  */
10
11 require_once("include/items.php");
12 require_once("include/bb2diaspora.php");
13 require_once("include/Scrape.php");
14 require_once("include/Contact.php");
15 require_once("include/Photo.php");
16 require_once("include/socgraph.php");
17 require_once("include/group.php");
18 require_once("include/xml.php");
19 require_once("include/datetime.php");
20 require_once("include/queue_fn.php");
21 require_once("include/cache.php");
22
23 /**
24  * @brief This class contain functions to create and send Diaspora XML files
25  *
26  */
27 class Diaspora {
28
29         /**
30          * @brief Return a list of relay servers
31          *
32          * This is an experimental Diaspora feature.
33          *
34          * @return array of relay servers
35          */
36         public static function relay_list() {
37
38                 $serverdata = get_config("system", "relay_server");
39                 if ($serverdata == "")
40                         return array();
41
42                 $relay = array();
43
44                 $servers = explode(",", $serverdata);
45
46                 foreach($servers AS $server) {
47                         $server = trim($server);
48                         $batch = $server."/receive/public";
49
50                         $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
51
52                         if (!$relais) {
53                                 $addr = "relay@".str_replace("http://", "", normalise_link($server));
54
55                                 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
56                                         VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
57                                         datetime_convert(),
58                                         dbesc($addr),
59                                         dbesc($addr),
60                                         dbesc($server),
61                                         dbesc(normalise_link($server)),
62                                         dbesc($batch),
63                                         dbesc(NETWORK_DIASPORA),
64                                         intval(CONTACT_IS_FOLLOWER),
65                                         dbesc(datetime_convert()),
66                                         dbesc(datetime_convert()),
67                                         dbesc(datetime_convert())
68                                 );
69
70                                 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
71                                 if ($relais)
72                                         $relay[] = $relais[0];
73                         } else
74                                 $relay[] = $relais[0];
75                 }
76
77                 return $relay;
78         }
79
80         /**
81          * @brief repairs a signature that was double encoded
82          *
83          * The function is unused at the moment. It was copied from the old implementation.
84          *
85          * @param string $signature The signature
86          * @param string $handle The handle of the signature owner
87          * @param integer $level This value is only set inside this function to avoid endless loops
88          *
89          * @return string the repaired signature
90          */
91         private static function repair_signature($signature, $handle = "", $level = 1) {
92
93                 if ($signature == "")
94                         return ($signature);
95
96                 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
97                         $signature = base64_decode($signature);
98                         logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
99
100                         // Do a recursive call to be able to fix even multiple levels
101                         if ($level < 10)
102                                 $signature = self::repair_signature($signature, $handle, ++$level);
103                 }
104
105                 return($signature);
106         }
107
108         /**
109          * @brief verify the envelope and return the verified data
110          *
111          * @param string $envelope The magic envelope
112          *
113          * @return string verified data
114          */
115         private static function verify_magic_envelope($envelope) {
116
117                 $basedom = parse_xml_string($envelope, false);
118
119                 if (!is_object($basedom)) {
120                         logger("Envelope is no XML file");
121                         return false;
122                 }
123
124                 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
125
126                 if (sizeof($children) == 0) {
127                         logger("XML has no children");
128                         return false;
129                 }
130
131                 $handle = "";
132
133                 $data = base64url_decode($children->data);
134                 $type = $children->data->attributes()->type[0];
135
136                 $encoding = $children->encoding;
137
138                 $alg = $children->alg;
139
140                 $sig = base64url_decode($children->sig);
141                 $key_id = $children->sig->attributes()->key_id[0];
142                 if ($key_id != "")
143                         $handle = base64url_decode($key_id);
144
145                 $b64url_data = base64url_encode($data);
146                 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
147
148                 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
149
150                 $key = self::key($handle);
151
152                 $verify = rsa_verify($signable_data, $sig, $key);
153                 if (!$verify) {
154                         logger('Message did not verify. Discarding.');
155                         return false;
156                 }
157
158                 return $data;
159         }
160
161         /**
162          * @brief: Decodes incoming Diaspora message
163          *
164          * @param array $importer Array of the importer user
165          * @param string $xml urldecoded Diaspora salmon
166          *
167          * @return array
168          * 'message' -> decoded Diaspora XML message
169          * 'author' -> author diaspora handle
170          * 'key' -> author public key (converted to pkcs#8)
171          */
172         public static function decode($importer, $xml) {
173
174                 $public = false;
175                 $basedom = parse_xml_string($xml);
176
177                 if (!is_object($basedom))
178                         return false;
179
180                 $children = $basedom->children('https://joindiaspora.com/protocol');
181
182                 if($children->header) {
183                         $public = true;
184                         $author_link = str_replace('acct:','',$children->header->author_id);
185                 } else {
186
187                         $encrypted_header = json_decode(base64_decode($children->encrypted_header));
188
189                         $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
190                         $ciphertext = base64_decode($encrypted_header->ciphertext);
191
192                         $outer_key_bundle = '';
193                         openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
194
195                         $j_outer_key_bundle = json_decode($outer_key_bundle);
196
197                         $outer_iv = base64_decode($j_outer_key_bundle->iv);
198                         $outer_key = base64_decode($j_outer_key_bundle->key);
199
200                         $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
201
202
203                         $decrypted = pkcs5_unpad($decrypted);
204
205                         logger('decrypted: '.$decrypted, LOGGER_DEBUG);
206                         $idom = parse_xml_string($decrypted,false);
207
208                         $inner_iv = base64_decode($idom->iv);
209                         $inner_aes_key = base64_decode($idom->aes_key);
210
211                         $author_link = str_replace('acct:','',$idom->author_id);
212                 }
213
214                 $dom = $basedom->children(NAMESPACE_SALMON_ME);
215
216                 // figure out where in the DOM tree our data is hiding
217
218                 if($dom->provenance->data)
219                         $base = $dom->provenance;
220                 elseif($dom->env->data)
221                         $base = $dom->env;
222                 elseif($dom->data)
223                         $base = $dom;
224
225                 if (!$base) {
226                         logger('unable to locate salmon data in xml');
227                         http_status_exit(400);
228                 }
229
230
231                 // Stash the signature away for now. We have to find their key or it won't be good for anything.
232                 $signature = base64url_decode($base->sig);
233
234                 // unpack the  data
235
236                 // strip whitespace so our data element will return to one big base64 blob
237                 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
238
239
240                 // stash away some other stuff for later
241
242                 $type = $base->data[0]->attributes()->type[0];
243                 $keyhash = $base->sig[0]->attributes()->keyhash[0];
244                 $encoding = $base->encoding;
245                 $alg = $base->alg;
246
247
248                 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
249
250
251                 // decode the data
252                 $data = base64url_decode($data);
253
254
255                 if($public)
256                         $inner_decrypted = $data;
257                 else {
258
259                         // Decode the encrypted blob
260
261                         $inner_encrypted = base64_decode($data);
262                         $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
263                         $inner_decrypted = pkcs5_unpad($inner_decrypted);
264                 }
265
266                 if (!$author_link) {
267                         logger('Could not retrieve author URI.');
268                         http_status_exit(400);
269                 }
270                 // Once we have the author URI, go to the web and try to find their public key
271                 // (first this will look it up locally if it is in the fcontact cache)
272                 // This will also convert diaspora public key from pkcs#1 to pkcs#8
273
274                 logger('Fetching key for '.$author_link);
275                 $key = self::key($author_link);
276
277                 if (!$key) {
278                         logger('Could not retrieve author key.');
279                         http_status_exit(400);
280                 }
281
282                 $verify = rsa_verify($signed_data,$signature,$key);
283
284                 if (!$verify) {
285                         logger('Message did not verify. Discarding.');
286                         http_status_exit(400);
287                 }
288
289                 logger('Message verified.');
290
291                 return array('message' => (string)$inner_decrypted,
292                                 'author' => unxmlify($author_link),
293                                 'key' => (string)$key);
294         }
295
296
297         /**
298          * @brief Dispatches public messages and find the fitting receivers
299          *
300          * @param array $msg The post that will be dispatched
301          *
302          * @return int The message id of the generated message, "true" or "false" if there was an error
303          */
304         public static function dispatch_public($msg) {
305
306                 $enabled = intval(get_config("system", "diaspora_enabled"));
307                 if (!$enabled) {
308                         logger("diaspora is disabled");
309                         return false;
310                 }
311
312                 // Use a dummy importer to import the data for the public copy
313                 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
314                 $message_id = self::dispatch($importer,$msg);
315
316                 // Now distribute it to the followers
317                 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
318                         (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
319                         AND NOT `account_expired` AND NOT `account_removed`",
320                         dbesc(NETWORK_DIASPORA),
321                         dbesc($msg["author"])
322                 );
323                 if ($r) {
324                         foreach ($r as $rr) {
325                                 logger("delivering to: ".$rr["username"]);
326                                 self::dispatch($rr,$msg);
327                         }
328                 } else
329                         logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
330
331                 return $message_id;
332         }
333
334         /**
335          * @brief Dispatches the different message types to the different functions
336          *
337          * @param array $importer Array of the importer user
338          * @param array $msg The post that will be dispatched
339          *
340          * @return int The message id of the generated message, "true" or "false" if there was an error
341          */
342         public static function dispatch($importer, $msg) {
343
344                 // The sender is the handle of the contact that sent the message.
345                 // This will often be different with relayed messages (for example "like" and "comment")
346                 $sender = $msg["author"];
347
348                 if (!self::valid_posting($msg, $fields)) {
349                         logger("Invalid posting");
350                         return false;
351                 }
352
353                 $type = $fields->getName();
354
355                 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
356
357                 switch ($type) {
358                         case "account_deletion":
359                                 return self::receive_account_deletion($importer, $fields);
360
361                         case "comment":
362                                 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
363
364                         case "contact":
365                                 return self::receive_contact_request($importer, $fields);
366
367                         case "conversation":
368                                 return self::receive_conversation($importer, $msg, $fields);
369
370                         case "like":
371                                 return self::receive_like($importer, $sender, $fields);
372
373                         case "message":
374                                 return self::receive_message($importer, $fields);
375
376                         case "participation": // Not implemented
377                                 return self::receive_participation($importer, $fields);
378
379                         case "photo": // Not implemented
380                                 return self::receive_photo($importer, $fields);
381
382                         case "poll_participation": // Not implemented
383                                 return self::receive_poll_participation($importer, $fields);
384
385                         case "profile":
386                                 return self::receive_profile($importer, $fields);
387
388                         case "reshare":
389                                 return self::receive_reshare($importer, $fields, $msg["message"]);
390
391                         case "retraction":
392                                 return self::receive_retraction($importer, $sender, $fields);
393
394                         case "status_message":
395                                 return self::receive_status_message($importer, $fields, $msg["message"]);
396
397                         default:
398                                 logger("Unknown message type ".$type);
399                                 return false;
400                 }
401
402                 return true;
403         }
404
405         /**
406          * @brief Checks if a posting is valid and fetches the data fields.
407          *
408          * This function does not only check the signature.
409          * It also does the conversion between the old and the new diaspora format.
410          *
411          * @param array $msg Array with the XML, the sender handle and the sender signature
412          * @param object $fields SimpleXML object that contains the posting when it is valid
413          *
414          * @return bool Is the posting valid?
415          */
416         private static function valid_posting($msg, &$fields) {
417
418                 $data = parse_xml_string($msg["message"], false);
419
420                 if (!is_object($data)) {
421                         logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
422                         return false;
423                 }
424
425                 $first_child = $data->getName();
426
427                 // Is this the new or the old version?
428                 if ($data->getName() == "XML") {
429                         $oldXML = true;
430                         foreach ($data->post->children() as $child)
431                                 $element = $child;
432                 } else {
433                         $oldXML = false;
434                         $element = $data;
435                 }
436
437                 $type = $element->getName();
438                 $orig_type = $type;
439
440                 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
441
442                 // All retractions are handled identically from now on.
443                 // In the new version there will only be "retraction".
444                 if (in_array($type, array("signed_retraction", "relayable_retraction")))
445                         $type = "retraction";
446
447                 if ($type == "request")
448                         $type = "contact";
449
450                 $fields = new SimpleXMLElement("<".$type."/>");
451
452                 $signed_data = "";
453
454                 foreach ($element->children() AS $fieldname => $entry) {
455                         if ($oldXML) {
456                                 // Translation for the old XML structure
457                                 if ($fieldname == "diaspora_handle")
458                                         $fieldname = "author";
459
460                                 if ($fieldname == "participant_handles")
461                                         $fieldname = "participants";
462
463                                 if (in_array($type, array("like", "participation"))) {
464                                         if ($fieldname == "target_type")
465                                                 $fieldname = "parent_type";
466                                 }
467
468                                 if ($fieldname == "sender_handle")
469                                         $fieldname = "author";
470
471                                 if ($fieldname == "recipient_handle")
472                                         $fieldname = "recipient";
473
474                                 if ($fieldname == "root_diaspora_id")
475                                         $fieldname = "root_author";
476
477                                 if ($type == "retraction") {
478                                         if ($fieldname == "post_guid")
479                                                 $fieldname = "target_guid";
480
481                                         if ($fieldname == "type")
482                                                 $fieldname = "target_type";
483                                 }
484                         }
485
486                         if (($fieldname == "author_signature") AND ($entry != ""))
487                                 $author_signature = base64_decode($entry);
488                         elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
489                                 $parent_author_signature = base64_decode($entry);
490                         elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
491                                 if ($signed_data != "") {
492                                         $signed_data .= ";";
493                                         $signed_data_parent .= ";";
494                                 }
495
496                                 $signed_data .= $entry;
497                         }
498                         if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
499                                 ($orig_type == "relayable_retraction"))
500                                 xml::copy($entry, $fields, $fieldname);
501                 }
502
503                 // This is something that shouldn't happen at all.
504                 if (in_array($type, array("status_message", "reshare", "profile")))
505                         if ($msg["author"] != $fields->author) {
506                                 logger("Message handle is not the same as envelope sender. Quitting this message.");
507                                 return false;
508                         }
509
510                 // Only some message types have signatures. So we quit here for the other types.
511                 if (!in_array($type, array("comment", "message", "like")))
512                         return true;
513
514                 // No author_signature? This is a must, so we quit.
515                 if (!isset($author_signature)) {
516                         logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
517                         return false;
518                 }
519
520                 if (isset($parent_author_signature)) {
521                         $key = self::key($msg["author"]);
522
523                         if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
524                                 logger("No valid parent author signature for parent author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature, LOGGER_DEBUG);
525                                 return false;
526                         }
527                 }
528
529                 $key = self::key($fields->author);
530
531                 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
532                         logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
533                         return false;
534                 } else
535                         return true;
536         }
537
538         /**
539          * @brief Fetches the public key for a given handle
540          *
541          * @param string $handle The handle
542          *
543          * @return string The public key
544          */
545         private static function key($handle) {
546                 $handle = strval($handle);
547
548                 logger("Fetching diaspora key for: ".$handle);
549
550                 $r = self::person_by_handle($handle);
551                 if($r)
552                         return $r["pubkey"];
553
554                 return "";
555         }
556
557         /**
558          * @brief Fetches data for a given handle
559          *
560          * @param string $handle The handle
561          *
562          * @return array the queried data
563          */
564         private static function person_by_handle($handle) {
565
566                 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
567                         dbesc(NETWORK_DIASPORA),
568                         dbesc($handle)
569                 );
570                 if ($r) {
571                         $person = $r[0];
572                         logger("In cache ".print_r($r,true), LOGGER_DEBUG);
573
574                         // update record occasionally so it doesn't get stale
575                         $d = strtotime($person["updated"]." +00:00");
576                         if ($d < strtotime("now - 14 days"))
577                                 $update = true;
578
579                         if ($person["guid"] == "")
580                                 $update = true;
581                 }
582
583                 if (!$person OR $update) {
584                         logger("create or refresh", LOGGER_DEBUG);
585                         $r = probe_url($handle, PROBE_DIASPORA);
586
587                         // Note that Friendica contacts will return a "Diaspora person"
588                         // if Diaspora connectivity is enabled on their server
589                         if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
590                                 self::add_fcontact($r, $update);
591                                 $person = $r;
592                         }
593                 }
594                 return $person;
595         }
596
597         /**
598          * @brief Updates the fcontact table
599          *
600          * @param array $arr The fcontact data
601          * @param bool $update Update or insert?
602          *
603          * @return string The id of the fcontact entry
604          */
605         private static function add_fcontact($arr, $update = false) {
606
607                 if($update) {
608                         $r = q("UPDATE `fcontact` SET
609                                         `name` = '%s',
610                                         `photo` = '%s',
611                                         `request` = '%s',
612                                         `nick` = '%s',
613                                         `addr` = '%s',
614                                         `guid` = '%s',
615                                         `batch` = '%s',
616                                         `notify` = '%s',
617                                         `poll` = '%s',
618                                         `confirm` = '%s',
619                                         `alias` = '%s',
620                                         `pubkey` = '%s',
621                                         `updated` = '%s'
622                                 WHERE `url` = '%s' AND `network` = '%s'",
623                                         dbesc($arr["name"]),
624                                         dbesc($arr["photo"]),
625                                         dbesc($arr["request"]),
626                                         dbesc($arr["nick"]),
627                                         dbesc(strtolower($arr["addr"])),
628                                         dbesc($arr["guid"]),
629                                         dbesc($arr["batch"]),
630                                         dbesc($arr["notify"]),
631                                         dbesc($arr["poll"]),
632                                         dbesc($arr["confirm"]),
633                                         dbesc($arr["alias"]),
634                                         dbesc($arr["pubkey"]),
635                                         dbesc(datetime_convert()),
636                                         dbesc($arr["url"]),
637                                         dbesc($arr["network"])
638                                 );
639                 } else {
640                         $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
641                                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
642                                 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
643                                         dbesc($arr["url"]),
644                                         dbesc($arr["name"]),
645                                         dbesc($arr["photo"]),
646                                         dbesc($arr["request"]),
647                                         dbesc($arr["nick"]),
648                                         dbesc($arr["addr"]),
649                                         dbesc($arr["guid"]),
650                                         dbesc($arr["batch"]),
651                                         dbesc($arr["notify"]),
652                                         dbesc($arr["poll"]),
653                                         dbesc($arr["confirm"]),
654                                         dbesc($arr["network"]),
655                                         dbesc($arr["alias"]),
656                                         dbesc($arr["pubkey"]),
657                                         dbesc(datetime_convert())
658                                 );
659                 }
660
661                 return $r;
662         }
663
664         /**
665          * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
666          *
667          * @param int $contact_id The id in the contact table
668          * @param int $gcontact_id The id in the gcontact table
669          *
670          * @return string the handle
671          */
672         public static function handle_from_contact($contact_id, $gcontact_id = 0) {
673                 $handle = false;
674
675                 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
676
677                 if ($gcontact_id != 0) {
678                         $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
679                                 intval($gcontact_id));
680
681                         if (dbm::is_result($r)) {
682                                 return strtolower($r[0]["addr"]);
683                         }
684                 }
685
686                 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
687                         intval($contact_id));
688
689                 if (dbm::is_result($r)) {
690                         $contact = $r[0];
691
692                         logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
693
694                         if ($contact['addr'] != "") {
695                                 $handle = $contact['addr'];
696                         } else {
697                                 $baseurl_start = strpos($contact['url'],'://') + 3;
698                                 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
699                                 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
700                                 $handle = $contact['nick'].'@'.$baseurl;
701                         }
702                 }
703
704                 return strtolower($handle);
705         }
706
707         /**
708          * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
709          * fcontact guid
710          *
711          * @param mixed $fcontact_guid Hexadecimal string guid
712          *
713          * @return string the contact url or null
714          */
715         public static function url_from_contact_guid($fcontact_guid) {
716                 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
717
718                 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
719                         dbesc(NETWORK_DIASPORA),
720                         dbesc($fcontact_guid)
721                 );
722
723                 if (dbm::is_result($r)) {
724                         return $r[0]['url'];
725                 }
726
727                 return null;
728         }
729
730         /**
731          * @brief Get a contact id for a given handle
732          *
733          * @param int $uid The user id
734          * @param string $handle The handle in the format user@domain.tld
735          *
736          * @return The contact id
737          */
738         private static function contact_by_handle($uid, $handle) {
739                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
740                         intval($uid),
741                         dbesc($handle)
742                 );
743
744                 if ($r)
745                         return $r[0];
746
747                 $handle_parts = explode("@", $handle);
748                 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
749                 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
750                         dbesc(NETWORK_DFRN),
751                         intval($uid),
752                         dbesc($nurl_sql)
753                 );
754                 if($r)
755                         return $r[0];
756
757                 return false;
758         }
759
760         /**
761          * @brief Check if posting is allowed for this contact
762          *
763          * @param array $importer Array of the importer user
764          * @param array $contact The contact that is checked
765          * @param bool $is_comment Is the check for a comment?
766          *
767          * @return bool is the contact allowed to post?
768          */
769         private static function post_allow($importer, $contact, $is_comment = false) {
770
771                 // perhaps we were already sharing with this person. Now they're sharing with us.
772                 // That makes us friends.
773                 // Normally this should have handled by getting a request - but this could get lost
774                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
775                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
776                                 intval(CONTACT_IS_FRIEND),
777                                 intval($contact["id"]),
778                                 intval($importer["uid"])
779                         );
780                         $contact["rel"] = CONTACT_IS_FRIEND;
781                         logger("defining user ".$contact["nick"]." as friend");
782                 }
783
784                 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
785                         return false;
786                 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
787                         return true;
788                 if($contact["rel"] == CONTACT_IS_FOLLOWER)
789                         if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
790                                 return true;
791
792                 // Messages for the global users are always accepted
793                 if ($importer["uid"] == 0)
794                         return true;
795
796                 return false;
797         }
798
799         /**
800          * @brief Fetches the contact id for a handle and checks if posting is allowed
801          *
802          * @param array $importer Array of the importer user
803          * @param string $handle The checked handle in the format user@domain.tld
804          * @param bool $is_comment Is the check for a comment?
805          *
806          * @return array The contact data
807          */
808         private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
809                 $contact = self::contact_by_handle($importer["uid"], $handle);
810                 if (!$contact) {
811                         logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
812                         return false;
813                 }
814
815                 if (!self::post_allow($importer, $contact, $is_comment)) {
816                         logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
817                         return false;
818                 }
819                 return $contact;
820         }
821
822         /**
823          * @brief Does the message already exists on the system?
824          *
825          * @param int $uid The user id
826          * @param string $guid The guid of the message
827          *
828          * @return int|bool message id if the message already was stored into the system - or false.
829          */
830         private static function message_exists($uid, $guid) {
831                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
832                         intval($uid),
833                         dbesc($guid)
834                 );
835
836                 if ($r) {
837                         logger("message ".$guid." already exists for user ".$uid);
838                         return $r[0]["id"];
839                 }
840
841                 return false;
842         }
843
844         /**
845          * @brief Checks for links to posts in a message
846          *
847          * @param array $item The item array
848          */
849         private static function fetch_guid($item) {
850                 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
851                         function ($match) use ($item){
852                                 return(self::fetch_guid_sub($match, $item));
853                         },$item["body"]);
854         }
855
856         /**
857          * @brief Checks for relative /people/* links in an item body to match local
858          * contacts or prepends the remote host taken from the author link.
859          *
860          * @param string $body The item body to replace links from
861          * @param string $author_link The author link for missing local contact fallback
862          *
863          * @return the replaced string
864          */
865         public function replace_people_guid($body, $author_link) {
866                 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
867                         function ($match) use ($author_link) {
868                                 // $match
869                                 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
870                                 // 1 => '0123456789abcdef'
871                                 // 2 => 'Foo Bar'
872                                 $handle = self::url_from_contact_guid($match[1]);
873
874                                 if ($handle) {
875                                         $return = '@[url='.$handle.']'.$match[2].'[/url]';
876                                 } else {
877                                         // No local match, restoring absolute remote URL from author scheme and host
878                                         $author_url = parse_url($author_link);
879                                         $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
880                                 }
881
882                                 return $return;
883                         }, $body);
884
885                 return $return;
886         }
887
888         /**
889          * @brief sub function of "fetch_guid" which checks for links in messages
890          *
891          * @param array $match array containing a link that has to be checked for a message link
892          * @param array $item The item array
893          */
894         private static function fetch_guid_sub($match, $item) {
895                 if (!self::store_by_guid($match[1], $item["author-link"]))
896                         self::store_by_guid($match[1], $item["owner-link"]);
897         }
898
899         /**
900          * @brief Fetches an item with a given guid from a given server
901          *
902          * @param string $guid the message guid
903          * @param string $server The server address
904          * @param int $uid The user id of the user
905          *
906          * @return int the message id of the stored message or false
907          */
908         private static function store_by_guid($guid, $server, $uid = 0) {
909                 $serverparts = parse_url($server);
910                 $server = $serverparts["scheme"]."://".$serverparts["host"];
911
912                 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
913
914                 $msg = self::message($guid, $server);
915
916                 if (!$msg)
917                         return false;
918
919                 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
920
921                 // Now call the dispatcher
922                 return self::dispatch_public($msg);
923         }
924
925         /**
926          * @brief Fetches a message from a server
927          *
928          * @param string $guid message guid
929          * @param string $server The url of the server
930          * @param int $level Endless loop prevention
931          *
932          * @return array
933          *      'message' => The message XML
934          *      'author' => The author handle
935          *      'key' => The public key of the author
936          */
937         private static function message($guid, $server, $level = 0) {
938
939                 if ($level > 5)
940                         return false;
941
942                 // This will work for new Diaspora servers and Friendica servers from 3.5
943                 $source_url = $server."/fetch/post/".$guid;
944                 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
945
946                 $envelope = fetch_url($source_url);
947                 if($envelope) {
948                         logger("Envelope was fetched.", LOGGER_DEBUG);
949                         $x = self::verify_magic_envelope($envelope);
950                         if (!$x)
951                                 logger("Envelope could not be verified.", LOGGER_DEBUG);
952                         else
953                                 logger("Envelope was verified.", LOGGER_DEBUG);
954                 } else
955                         $x = false;
956
957                 // This will work for older Diaspora and Friendica servers
958                 if (!$x) {
959                         $source_url = $server."/p/".$guid.".xml";
960                         logger("Fetch post from ".$source_url, LOGGER_DEBUG);
961
962                         $x = fetch_url($source_url);
963                         if(!$x)
964                                 return false;
965                 }
966
967                 $source_xml = parse_xml_string($x, false);
968
969                 if (!is_object($source_xml))
970                         return false;
971
972                 if ($source_xml->post->reshare) {
973                         // Reshare of a reshare - old Diaspora version
974                         logger("Message is a reshare", LOGGER_DEBUG);
975                         return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
976                 } elseif ($source_xml->getName() == "reshare") {
977                         // Reshare of a reshare - new Diaspora version
978                         logger("Message is a new reshare", LOGGER_DEBUG);
979                         return self::message($source_xml->root_guid, $server, ++$level);
980                 }
981
982                 $author = "";
983
984                 // Fetch the author - for the old and the new Diaspora version
985                 if ($source_xml->post->status_message->diaspora_handle)
986                         $author = (string)$source_xml->post->status_message->diaspora_handle;
987                 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
988                         $author = (string)$source_xml->author;
989
990                 // If this isn't a "status_message" then quit
991                 if (!$author) {
992                         logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
993                         return false;
994                 }
995
996                 $msg = array("message" => $x, "author" => $author);
997
998                 $msg["key"] = self::key($msg["author"]);
999
1000                 return $msg;
1001         }
1002
1003         /**
1004          * @brief Fetches the item record of a given guid
1005          *
1006          * @param int $uid The user id
1007          * @param string $guid message guid
1008          * @param string $author The handle of the item
1009          * @param array $contact The contact of the item owner
1010          *
1011          * @return array the item record
1012          */
1013         private static function parent_item($uid, $guid, $author, $contact) {
1014                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1015                                 `author-name`, `author-link`, `author-avatar`,
1016                                 `owner-name`, `owner-link`, `owner-avatar`
1017                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1018                         intval($uid), dbesc($guid));
1019
1020                 if(!$r) {
1021                         $result = self::store_by_guid($guid, $contact["url"], $uid);
1022
1023                         if (!$result) {
1024                                 $person = self::person_by_handle($author);
1025                                 $result = self::store_by_guid($guid, $person["url"], $uid);
1026                         }
1027
1028                         if ($result) {
1029                                 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1030
1031                                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1032                                                 `author-name`, `author-link`, `author-avatar`,
1033                                                 `owner-name`, `owner-link`, `owner-avatar`
1034                                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1035                                         intval($uid), dbesc($guid));
1036                         }
1037                 }
1038
1039                 if (!$r) {
1040                         logger("parent item not found: parent: ".$guid." - user: ".$uid);
1041                         return false;
1042                 } else {
1043                         logger("parent item found: parent: ".$guid." - user: ".$uid);
1044                         return $r[0];
1045                 }
1046         }
1047
1048         /**
1049          * @brief returns contact details
1050          *
1051          * @param array $contact The default contact if the person isn't found
1052          * @param array $person The record of the person
1053          * @param int $uid The user id
1054          *
1055          * @return array
1056          *      'cid' => contact id
1057          *      'network' => network type
1058          */
1059         private static function author_contact_by_url($contact, $person, $uid) {
1060
1061                 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1062                         dbesc(normalise_link($person["url"])), intval($uid));
1063                 if ($r) {
1064                         $cid = $r[0]["id"];
1065                         $network = $r[0]["network"];
1066
1067                         // We are receiving content from a user that is about to be terminated
1068                         // This means the user is vital, so we remove a possible termination date.
1069                         unmark_for_death($contact);
1070                 } else {
1071                         $cid = $contact["id"];
1072                         $network = NETWORK_DIASPORA;
1073                 }
1074
1075                 return array("cid" => $cid, "network" => $network);
1076         }
1077
1078         /**
1079          * @brief Is the profile a hubzilla profile?
1080          *
1081          * @param string $url The profile link
1082          *
1083          * @return bool is it a hubzilla server?
1084          */
1085         public static function is_redmatrix($url) {
1086                 return(strstr($url, "/channel/"));
1087         }
1088
1089         /**
1090          * @brief Generate a post link with a given handle and message guid
1091          *
1092          * @param string $addr The user handle
1093          * @param string $guid message guid
1094          *
1095          * @return string the post link
1096          */
1097         private static function plink($addr, $guid) {
1098                 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1099
1100                 // Fallback
1101                 if (!$r)
1102                         return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1103
1104                 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1105                 // So we try another way as well.
1106                 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1107                 if ($s)
1108                         $r[0]["network"] = $s[0]["network"];
1109
1110                 if ($r[0]["network"] == NETWORK_DFRN)
1111                         return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1112
1113                 if (self::is_redmatrix($r[0]["url"]))
1114                         return $r[0]["url"]."/?f=&mid=".$guid;
1115
1116                 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1117         }
1118
1119         /**
1120          * @brief Processes an account deletion
1121          *
1122          * @param array $importer Array of the importer user
1123          * @param object $data The message object
1124          *
1125          * @return bool Success
1126          */
1127         private static function receive_account_deletion($importer, $data) {
1128
1129                 /// @todo Account deletion should remove the contact from the global contacts as well
1130
1131                 $author = notags(unxmlify($data->author));
1132
1133                 $contact = self::contact_by_handle($importer["uid"], $author);
1134                 if (!$contact) {
1135                         logger("cannot find contact for author: ".$author);
1136                         return false;
1137                 }
1138
1139                 // We now remove the contact
1140                 contact_remove($contact["id"]);
1141                 return true;
1142         }
1143
1144         /**
1145          * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1146          *
1147          * @param string $author Author handle
1148          * @param string $guid Message guid
1149          * @param boolean $onlyfound Only return uri when found in the database
1150          *
1151          * @return string The constructed uri or the one from our database
1152          */
1153         private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1154
1155                 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1156                 if (dbm::is_result($r)) {
1157                         return $r[0]["uri"];
1158                 } elseif (!$onlyfound) {
1159                         return $author.":".$guid;
1160                 }
1161
1162                 return "";
1163         }
1164
1165         /**
1166          * @brief Fetch the guid from our database with a given uri
1167          *
1168          * @param string $author Author handle
1169          * @param string $uri Message uri
1170          *
1171          * @return string The post guid
1172          */
1173         private static function get_guid_from_uri($uri, $uid) {
1174
1175                 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1176                 if (dbm::is_result($r))
1177                         return $r[0]["guid"];
1178                 else
1179                         return false;
1180         }
1181
1182         /**
1183          * @brief Processes an incoming comment
1184          *
1185          * @param array $importer Array of the importer user
1186          * @param string $sender The sender of the message
1187          * @param object $data The message object
1188          * @param string $xml The original XML of the message
1189          *
1190          * @return int The message id of the generated comment or "false" if there was an error
1191          */
1192         private static function receive_comment($importer, $sender, $data, $xml) {
1193                 $guid = notags(unxmlify($data->guid));
1194                 $parent_guid = notags(unxmlify($data->parent_guid));
1195                 $text = unxmlify($data->text);
1196                 $author = notags(unxmlify($data->author));
1197
1198                 if (isset($data->created_at)) {
1199                         $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1200                 } else {
1201                         $created_at = datetime_convert();
1202                 }
1203
1204                 if (isset($data->thread_parent_guid)) {
1205                         $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1206                         $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1207                 } else {
1208                         $thr_uri = "";
1209                 }
1210
1211                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1212                 if (!$contact) {
1213                         return false;
1214                 }
1215
1216                 $message_id = self::message_exists($importer["uid"], $guid);
1217                 if ($message_id) {
1218                         return $message_id;
1219                 }
1220
1221                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1222                 if (!$parent_item) {
1223                         return false;
1224                 }
1225
1226                 $person = self::person_by_handle($author);
1227                 if (!is_array($person)) {
1228                         logger("unable to find author details");
1229                         return false;
1230                 }
1231
1232                 // Fetch the contact id - if we know this contact
1233                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1234
1235                 $datarray = array();
1236
1237                 $datarray["uid"] = $importer["uid"];
1238                 $datarray["contact-id"] = $author_contact["cid"];
1239                 $datarray["network"]  = $author_contact["network"];
1240
1241                 $datarray["author-name"] = $person["name"];
1242                 $datarray["author-link"] = $person["url"];
1243                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1244
1245                 $datarray["owner-name"] = $contact["name"];
1246                 $datarray["owner-link"] = $contact["url"];
1247                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1248
1249                 $datarray["guid"] = $guid;
1250                 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1251
1252                 $datarray["type"] = "remote-comment";
1253                 $datarray["verb"] = ACTIVITY_POST;
1254                 $datarray["gravity"] = GRAVITY_COMMENT;
1255
1256                 if ($thr_uri != "") {
1257                         $datarray["parent-uri"] = $thr_uri;
1258                 } else {
1259                         $datarray["parent-uri"] = $parent_item["uri"];
1260                 }
1261
1262                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1263                 $datarray["object"] = $xml;
1264
1265                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1266
1267                 $body = diaspora2bb($text);
1268
1269                 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1270
1271                 self::fetch_guid($datarray);
1272
1273                 $message_id = item_store($datarray);
1274
1275                 if ($message_id) {
1276                         logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1277                 }
1278
1279                 // If we are the origin of the parent we store the original data and notify our followers
1280                 if($message_id AND $parent_item["origin"]) {
1281
1282                         // Formerly we stored the signed text, the signature and the author in different fields.
1283                         // We now store the raw data so that we are more flexible.
1284                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1285                                 intval($message_id),
1286                                 dbesc(json_encode($data))
1287                         );
1288
1289                         // notify others
1290                         proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1291                 }
1292
1293                 return $message_id;
1294         }
1295
1296         /**
1297          * @brief processes and stores private messages
1298          *
1299          * @param array $importer Array of the importer user
1300          * @param array $contact The contact of the message
1301          * @param object $data The message object
1302          * @param array $msg Array of the processed message, author handle and key
1303          * @param object $mesg The private message
1304          * @param array $conversation The conversation record to which this message belongs
1305          *
1306          * @return bool "true" if it was successful
1307          */
1308         private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1309                 $guid = notags(unxmlify($data->guid));
1310                 $subject = notags(unxmlify($data->subject));
1311                 $author = notags(unxmlify($data->author));
1312
1313                 $msg_guid = notags(unxmlify($mesg->guid));
1314                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1315                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1316                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1317                 $msg_text = unxmlify($mesg->text);
1318                 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1319
1320                 // "diaspora_handle" is the element name from the old version
1321                 // "author" is the element name from the new version
1322                 if ($mesg->author) {
1323                         $msg_author = notags(unxmlify($mesg->author));
1324                 } elseif ($mesg->diaspora_handle) {
1325                         $msg_author = notags(unxmlify($mesg->diaspora_handle));
1326                 } else {
1327                         return false;
1328                 }
1329
1330                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1331
1332                 if ($msg_conversation_guid != $guid) {
1333                         logger("message conversation guid does not belong to the current conversation.");
1334                         return false;
1335                 }
1336
1337                 $body = diaspora2bb($msg_text);
1338                 $message_uri = $msg_author.":".$msg_guid;
1339
1340                 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1341
1342                 $author_signature = base64_decode($msg_author_signature);
1343
1344                 if (strcasecmp($msg_author,$msg["author"]) == 0) {
1345                         $person = $contact;
1346                         $key = $msg["key"];
1347                 } else {
1348                         $person = self::person_by_handle($msg_author);
1349
1350                         if (is_array($person) && x($person, "pubkey")) {
1351                                 $key = $person["pubkey"];
1352                         } else {
1353                                 logger("unable to find author details");
1354                                         return false;
1355                         }
1356                 }
1357
1358                 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1359                         logger("verification failed.");
1360                         return false;
1361                 }
1362
1363                 if ($msg_parent_author_signature) {
1364                         $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1365
1366                         $parent_author_signature = base64_decode($msg_parent_author_signature);
1367
1368                         $key = $msg["key"];
1369
1370                         if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1371                                 logger("owner verification failed.");
1372                                 return false;
1373                         }
1374                 }
1375
1376                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1377                         dbesc($message_uri)
1378                 );
1379                 if (dbm::is_result($r)) {
1380                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1381                         return false;
1382                 }
1383
1384                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1385                         VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1386                         intval($importer["uid"]),
1387                         dbesc($msg_guid),
1388                         intval($conversation["id"]),
1389                         dbesc($person["name"]),
1390                         dbesc($person["photo"]),
1391                         dbesc($person["url"]),
1392                         intval($contact["id"]),
1393                         dbesc($subject),
1394                         dbesc($body),
1395                         0,
1396                         0,
1397                         dbesc($message_uri),
1398                         dbesc($author.":".$guid),
1399                         dbesc($msg_created_at)
1400                 );
1401
1402                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1403                         dbesc(datetime_convert()),
1404                         intval($conversation["id"])
1405                 );
1406
1407                 notification(array(
1408                         "type" => NOTIFY_MAIL,
1409                         "notify_flags" => $importer["notify-flags"],
1410                         "language" => $importer["language"],
1411                         "to_name" => $importer["username"],
1412                         "to_email" => $importer["email"],
1413                         "uid" =>$importer["uid"],
1414                         "item" => array("subject" => $subject, "body" => $body),
1415                         "source_name" => $person["name"],
1416                         "source_link" => $person["url"],
1417                         "source_photo" => $person["thumb"],
1418                         "verb" => ACTIVITY_POST,
1419                         "otype" => "mail"
1420                 ));
1421                 return true;
1422         }
1423
1424         /**
1425          * @brief Processes new private messages (answers to private messages are processed elsewhere)
1426          *
1427          * @param array $importer Array of the importer user
1428          * @param array $msg Array of the processed message, author handle and key
1429          * @param object $data The message object
1430          *
1431          * @return bool Success
1432          */
1433         private static function receive_conversation($importer, $msg, $data) {
1434                 $guid = notags(unxmlify($data->guid));
1435                 $subject = notags(unxmlify($data->subject));
1436                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1437                 $author = notags(unxmlify($data->author));
1438                 $participants = notags(unxmlify($data->participants));
1439
1440                 $messages = $data->message;
1441
1442                 if (!count($messages)) {
1443                         logger("empty conversation");
1444                         return false;
1445                 }
1446
1447                 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1448                 if (!$contact)
1449                         return false;
1450
1451                 $conversation = null;
1452
1453                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1454                         intval($importer["uid"]),
1455                         dbesc($guid)
1456                 );
1457                 if($c)
1458                         $conversation = $c[0];
1459                 else {
1460                         $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1461                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1462                                 intval($importer["uid"]),
1463                                 dbesc($guid),
1464                                 dbesc($author),
1465                                 dbesc($created_at),
1466                                 dbesc(datetime_convert()),
1467                                 dbesc($subject),
1468                                 dbesc($participants)
1469                         );
1470                         if($r)
1471                                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1472                                         intval($importer["uid"]),
1473                                         dbesc($guid)
1474                                 );
1475
1476                         if($c)
1477                                 $conversation = $c[0];
1478                 }
1479                 if (!$conversation) {
1480                         logger("unable to create conversation.");
1481                         return;
1482                 }
1483
1484                 foreach($messages as $mesg)
1485                         self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1486
1487                 return true;
1488         }
1489
1490         /**
1491          * @brief Creates the body for a "like" message
1492          *
1493          * @param array $contact The contact that send us the "like"
1494          * @param array $parent_item The item array of the parent item
1495          * @param string $guid message guid
1496          *
1497          * @return string the body
1498          */
1499         private static function construct_like_body($contact, $parent_item, $guid) {
1500                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1501
1502                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1503                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1504                 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1505
1506                 return sprintf($bodyverb, $ulink, $alink, $plink);
1507         }
1508
1509         /**
1510          * @brief Creates a XML object for a "like"
1511          *
1512          * @param array $importer Array of the importer user
1513          * @param array $parent_item The item array of the parent item
1514          *
1515          * @return string The XML
1516          */
1517         private static function construct_like_object($importer, $parent_item) {
1518                 $objtype = ACTIVITY_OBJ_NOTE;
1519                 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1520                 $parent_body = $parent_item["body"];
1521
1522                 $xmldata = array("object" => array("type" => $objtype,
1523                                                 "local" => "1",
1524                                                 "id" => $parent_item["uri"],
1525                                                 "link" => $link,
1526                                                 "title" => "",
1527                                                 "content" => $parent_body));
1528
1529                 return xml::from_array($xmldata, $xml, true);
1530         }
1531
1532         /**
1533          * @brief Processes "like" messages
1534          *
1535          * @param array $importer Array of the importer user
1536          * @param string $sender The sender of the message
1537          * @param object $data The message object
1538          *
1539          * @return int The message id of the generated like or "false" if there was an error
1540          */
1541         private static function receive_like($importer, $sender, $data) {
1542                 $positive = notags(unxmlify($data->positive));
1543                 $guid = notags(unxmlify($data->guid));
1544                 $parent_type = notags(unxmlify($data->parent_type));
1545                 $parent_guid = notags(unxmlify($data->parent_guid));
1546                 $author = notags(unxmlify($data->author));
1547
1548                 // likes on comments aren't supported by Diaspora - only on posts
1549                 // But maybe this will be supported in the future, so we will accept it.
1550                 if (!in_array($parent_type, array("Post", "Comment")))
1551                         return false;
1552
1553                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1554                 if (!$contact)
1555                         return false;
1556
1557                 $message_id = self::message_exists($importer["uid"], $guid);
1558                 if ($message_id)
1559                         return $message_id;
1560
1561                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1562                 if (!$parent_item)
1563                         return false;
1564
1565                 $person = self::person_by_handle($author);
1566                 if (!is_array($person)) {
1567                         logger("unable to find author details");
1568                         return false;
1569                 }
1570
1571                 // Fetch the contact id - if we know this contact
1572                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1573
1574                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1575                 // We would accept this anyhow.
1576                 if ($positive == "true")
1577                         $verb = ACTIVITY_LIKE;
1578                 else
1579                         $verb = ACTIVITY_DISLIKE;
1580
1581                 $datarray = array();
1582
1583                 $datarray["uid"] = $importer["uid"];
1584                 $datarray["contact-id"] = $author_contact["cid"];
1585                 $datarray["network"]  = $author_contact["network"];
1586
1587                 $datarray["author-name"] = $person["name"];
1588                 $datarray["author-link"] = $person["url"];
1589                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1590
1591                 $datarray["owner-name"] = $contact["name"];
1592                 $datarray["owner-link"] = $contact["url"];
1593                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1594
1595                 $datarray["guid"] = $guid;
1596                 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1597
1598                 $datarray["type"] = "activity";
1599                 $datarray["verb"] = $verb;
1600                 $datarray["gravity"] = GRAVITY_LIKE;
1601                 $datarray["parent-uri"] = $parent_item["uri"];
1602
1603                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1604                 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1605
1606                 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1607
1608                 $message_id = item_store($datarray);
1609
1610                 if ($message_id)
1611                         logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1612
1613                 // If we are the origin of the parent we store the original data and notify our followers
1614                 if($message_id AND $parent_item["origin"]) {
1615
1616                         // Formerly we stored the signed text, the signature and the author in different fields.
1617                         // We now store the raw data so that we are more flexible.
1618                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1619                                 intval($message_id),
1620                                 dbesc(json_encode($data))
1621                         );
1622
1623                         // notify others
1624                         proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1625                 }
1626
1627                 return $message_id;
1628         }
1629
1630         /**
1631          * @brief Processes private messages
1632          *
1633          * @param array $importer Array of the importer user
1634          * @param object $data The message object
1635          *
1636          * @return bool Success?
1637          */
1638         private static function receive_message($importer, $data) {
1639                 $guid = notags(unxmlify($data->guid));
1640                 $parent_guid = notags(unxmlify($data->parent_guid));
1641                 $text = unxmlify($data->text);
1642                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1643                 $author = notags(unxmlify($data->author));
1644                 $conversation_guid = notags(unxmlify($data->conversation_guid));
1645
1646                 $contact = self::allowed_contact_by_handle($importer, $author, true);
1647                 if (!$contact) {
1648                         return false;
1649                 }
1650
1651                 $conversation = null;
1652
1653                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1654                         intval($importer["uid"]),
1655                         dbesc($conversation_guid)
1656                 );
1657                 if ($c) {
1658                         $conversation = $c[0];
1659                 } else {
1660                         logger("conversation not available.");
1661                         return false;
1662                 }
1663
1664                 $message_uri = $author.":".$guid;
1665
1666                 $person = self::person_by_handle($author);
1667                 if (!$person) {
1668                         logger("unable to find author details");
1669                         return false;
1670                 }
1671
1672                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1673                         dbesc($message_uri),
1674                         intval($importer["uid"])
1675                 );
1676                 if (dbm::is_result($r)) {
1677                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1678                         return false;
1679                 }
1680
1681                 $body = diaspora2bb($text);
1682
1683                 $body = self::replace_people_guid($body, $person["url"]);
1684
1685                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1686                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1687                         intval($importer["uid"]),
1688                         dbesc($guid),
1689                         intval($conversation["id"]),
1690                         dbesc($person["name"]),
1691                         dbesc($person["photo"]),
1692                         dbesc($person["url"]),
1693                         intval($contact["id"]),
1694                         dbesc($conversation["subject"]),
1695                         dbesc($body),
1696                         0,
1697                         1,
1698                         dbesc($message_uri),
1699                         dbesc($author.":".$parent_guid),
1700                         dbesc($created_at)
1701                 );
1702
1703                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1704                         dbesc(datetime_convert()),
1705                         intval($conversation["id"])
1706                 );
1707
1708                 return true;
1709         }
1710
1711         /**
1712          * @brief Processes participations - unsupported by now
1713          *
1714          * @param array $importer Array of the importer user
1715          * @param object $data The message object
1716          *
1717          * @return bool always true
1718          */
1719         private static function receive_participation($importer, $data) {
1720                 // I'm not sure if we can fully support this message type
1721                 return true;
1722         }
1723
1724         /**
1725          * @brief Processes photos - unneeded
1726          *
1727          * @param array $importer Array of the importer user
1728          * @param object $data The message object
1729          *
1730          * @return bool always true
1731          */
1732         private static function receive_photo($importer, $data) {
1733                 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1734                 return true;
1735         }
1736
1737         /**
1738          * @brief Processes poll participations - unssupported
1739          *
1740          * @param array $importer Array of the importer user
1741          * @param object $data The message object
1742          *
1743          * @return bool always true
1744          */
1745         private static function receive_poll_participation($importer, $data) {
1746                 // We don't support polls by now
1747                 return true;
1748         }
1749
1750         /**
1751          * @brief Processes incoming profile updates
1752          *
1753          * @param array $importer Array of the importer user
1754          * @param object $data The message object
1755          *
1756          * @return bool Success
1757          */
1758         private static function receive_profile($importer, $data) {
1759                 $author = strtolower(notags(unxmlify($data->author)));
1760
1761                 $contact = self::contact_by_handle($importer["uid"], $author);
1762                 if (!$contact)
1763                         return false;
1764
1765                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1766                 $image_url = unxmlify($data->image_url);
1767                 $birthday = unxmlify($data->birthday);
1768                 $location = diaspora2bb(unxmlify($data->location));
1769                 $about = diaspora2bb(unxmlify($data->bio));
1770                 $gender = unxmlify($data->gender);
1771                 $searchable = (unxmlify($data->searchable) == "true");
1772                 $nsfw = (unxmlify($data->nsfw) == "true");
1773                 $tags = unxmlify($data->tag_string);
1774
1775                 $tags = explode("#", $tags);
1776
1777                 $keywords = array();
1778                 foreach ($tags as $tag) {
1779                         $tag = trim(strtolower($tag));
1780                         if ($tag != "")
1781                                 $keywords[] = $tag;
1782                 }
1783
1784                 $keywords = implode(", ", $keywords);
1785
1786                 $handle_parts = explode("@", $author);
1787                 $nick = $handle_parts[0];
1788
1789                 if($name === "")
1790                         $name = $handle_parts[0];
1791
1792                 if( preg_match("|^https?://|", $image_url) === 0)
1793                         $image_url = "http://".$handle_parts[1].$image_url;
1794
1795                 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1796
1797                 // Generic birthday. We don't know the timezone. The year is irrelevant.
1798
1799                 $birthday = str_replace("1000", "1901", $birthday);
1800
1801                 if ($birthday != "")
1802                         $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1803
1804                 // this is to prevent multiple birthday notifications in a single year
1805                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1806
1807                 if(substr($birthday,5) === substr($contact["bd"],5))
1808                         $birthday = $contact["bd"];
1809
1810                 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1811                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1812                         dbesc($name),
1813                         dbesc($nick),
1814                         dbesc($author),
1815                         dbesc(datetime_convert()),
1816                         dbesc($birthday),
1817                         dbesc($location),
1818                         dbesc($about),
1819                         dbesc($keywords),
1820                         dbesc($gender),
1821                         intval($contact["id"]),
1822                         intval($importer["uid"])
1823                 );
1824
1825                 if ($searchable) {
1826                         poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1827                                 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1828                 }
1829
1830                 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1831                                         "photo" => $image_url, "name" => $name, "location" => $location,
1832                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
1833                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1834                                         "hide" => !$searchable, "nsfw" => $nsfw);
1835
1836                 update_gcontact($gcontact);
1837
1838                 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1839
1840                 return true;
1841         }
1842
1843         /**
1844          * @brief Processes incoming friend requests
1845          *
1846          * @param array $importer Array of the importer user
1847          * @param array $contact The contact that send the request
1848          */
1849         private static function receive_request_make_friend($importer, $contact) {
1850
1851                 $a = get_app();
1852
1853                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1854                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1855                                 intval(CONTACT_IS_FRIEND),
1856                                 intval($contact["id"]),
1857                                 intval($importer["uid"])
1858                         );
1859                 }
1860                 // send notification
1861
1862                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1863                         intval($importer["uid"])
1864                 );
1865
1866                 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1867
1868                         $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1869                                 intval($importer["uid"])
1870                         );
1871
1872                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1873
1874                         if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1875
1876                                 $arr = array();
1877                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1878                                 $arr["uid"] = $importer["uid"];
1879                                 $arr["contact-id"] = $self[0]["id"];
1880                                 $arr["wall"] = 1;
1881                                 $arr["type"] = 'wall';
1882                                 $arr["gravity"] = 0;
1883                                 $arr["origin"] = 1;
1884                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1885                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1886                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1887                                 $arr["verb"] = ACTIVITY_FRIEND;
1888                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1889
1890                                 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1891                                 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1892                                 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1893                                 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1894
1895                                 $arr["object"] = self::construct_new_friend_object($contact);
1896
1897                                 $arr["last-child"] = 1;
1898
1899                                 $arr["allow_cid"] = $user[0]["allow_cid"];
1900                                 $arr["allow_gid"] = $user[0]["allow_gid"];
1901                                 $arr["deny_cid"]  = $user[0]["deny_cid"];
1902                                 $arr["deny_gid"]  = $user[0]["deny_gid"];
1903
1904                                 $i = item_store($arr);
1905                                 if($i)
1906                                         proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
1907                         }
1908                 }
1909         }
1910
1911         /**
1912          * @brief Creates a XML object for a "new friend" message
1913          *
1914          * @param array $contact Array of the contact
1915          *
1916          * @return string The XML
1917          */
1918         private static function construct_new_friend_object($contact) {
1919                 $objtype = ACTIVITY_OBJ_PERSON;
1920                 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
1921                         '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
1922
1923                 $xmldata = array("object" => array("type" => $objtype,
1924                                                 "title" => $contact["name"],
1925                                                 "id" => $contact["url"]."/".$contact["name"],
1926                                                 "link" => $link));
1927
1928                 return xml::from_array($xmldata, $xml, true);
1929         }
1930
1931         /**
1932          * @brief Processes incoming sharing notification
1933          *
1934          * @param array $importer Array of the importer user
1935          * @param object $data The message object
1936          *
1937          * @return bool Success
1938          */
1939         private static function receive_contact_request($importer, $data) {
1940                 $author = unxmlify($data->author);
1941                 $recipient = unxmlify($data->recipient);
1942
1943                 if (!$author || !$recipient) {
1944                         return false;
1945                 }
1946
1947                 // the current protocol version doesn't know these fields
1948                 // That means that we will assume their existance
1949                 if (isset($data->following)) {
1950                         $following = (unxmlify($data->following) == "true");
1951                 } else {
1952                         $following = true;
1953                 }
1954
1955                 if (isset($data->sharing)) {
1956                         $sharing = (unxmlify($data->sharing) == "true");
1957                 } else {
1958                         $sharing = true;
1959                 }
1960
1961                 $contact = self::contact_by_handle($importer["uid"],$author);
1962
1963                 // perhaps we were already sharing with this person. Now they're sharing with us.
1964                 // That makes us friends.
1965                 if ($contact) {
1966                         if ($following AND $sharing) {
1967                                 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
1968                                 self::receive_request_make_friend($importer, $contact);
1969
1970                                 // refetch the contact array
1971                                 $contact = self::contact_by_handle($importer["uid"],$author);
1972
1973                                 // If we are now friends, we are sending a share message.
1974                                 // Normally we needn't to do so, but the first message could have been vanished.
1975                                 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
1976                                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1977                                         if ($u) {
1978                                                 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
1979                                                 $ret = self::send_share($u[0], $contact);
1980                                         }
1981                                 }
1982                                 return true;
1983                         } else { /// @todo Handle all possible variations of adding and retracting of permissions
1984                                 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
1985                                 return false;
1986                         }
1987                 }
1988
1989                 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
1990                         logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
1991                         return false;
1992                 } elseif (!$following AND !$sharing) {
1993                         logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
1994                         return false;
1995                 } elseif (!$following AND $sharing) {
1996                         logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
1997                 } elseif ($following AND $sharing) {
1998                         logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
1999                 } elseif ($following AND !$sharing) {
2000                         logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2001                 }
2002
2003                 $ret = self::person_by_handle($author);
2004
2005                 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2006                         logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2007                         return false;
2008                 }
2009
2010                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2011
2012                 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2013                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2014                         intval($importer["uid"]),
2015                         dbesc($ret["network"]),
2016                         dbesc($ret["addr"]),
2017                         datetime_convert(),
2018                         dbesc($ret["url"]),
2019                         dbesc(normalise_link($ret["url"])),
2020                         dbesc($batch),
2021                         dbesc($ret["name"]),
2022                         dbesc($ret["nick"]),
2023                         dbesc($ret["photo"]),
2024                         dbesc($ret["pubkey"]),
2025                         dbesc($ret["notify"]),
2026                         dbesc($ret["poll"]),
2027                         1,
2028                         2
2029                 );
2030
2031                 // find the contact record we just created
2032
2033                 $contact_record = self::contact_by_handle($importer["uid"],$author);
2034
2035                 if (!$contact_record) {
2036                         logger("unable to locate newly created contact record.");
2037                         return;
2038                 }
2039
2040                 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2041
2042                 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2043
2044                 if(intval($def_gid))
2045                         group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2046
2047                 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2048
2049                 if($importer["page-flags"] == PAGE_NORMAL) {
2050
2051                         logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2052
2053                         $hash = random_string().(string)time();   // Generate a confirm_key
2054
2055                         $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2056                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2057                                 intval($importer["uid"]),
2058                                 intval($contact_record["id"]),
2059                                 0,
2060                                 0,
2061                                 dbesc(t("Sharing notification from Diaspora network")),
2062                                 dbesc($hash),
2063                                 dbesc(datetime_convert())
2064                         );
2065                 } else {
2066
2067                         // automatic friend approval
2068
2069                         logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2070
2071                         update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2072
2073                         // technically they are sharing with us (CONTACT_IS_SHARING),
2074                         // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2075                         // we are going to change the relationship and make them a follower.
2076
2077                         if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2078                                 $new_relation = CONTACT_IS_FRIEND;
2079                         elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2080                                 $new_relation = CONTACT_IS_SHARING;
2081                         else
2082                                 $new_relation = CONTACT_IS_FOLLOWER;
2083
2084                         $r = q("UPDATE `contact` SET `rel` = %d,
2085                                 `name-date` = '%s',
2086                                 `uri-date` = '%s',
2087                                 `blocked` = 0,
2088                                 `pending` = 0,
2089                                 `writable` = 1
2090                                 WHERE `id` = %d
2091                                 ",
2092                                 intval($new_relation),
2093                                 dbesc(datetime_convert()),
2094                                 dbesc(datetime_convert()),
2095                                 intval($contact_record["id"])
2096                         );
2097
2098                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2099                         if($u) {
2100                                 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2101                                 $ret = self::send_share($u[0], $contact_record);
2102
2103                                 // Send the profile data, maybe it weren't transmitted before
2104                                 self::send_profile($importer["uid"], array($contact_record));
2105                         }
2106                 }
2107
2108                 return true;
2109         }
2110
2111         /**
2112          * @brief Fetches a message with a given guid
2113          *
2114          * @param string $guid message guid
2115          * @param string $orig_author handle of the original post
2116          * @param string $author handle of the sharer
2117          *
2118          * @return array The fetched item
2119          */
2120         private static function original_item($guid, $orig_author, $author) {
2121
2122                 // Do we already have this item?
2123                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2124                                 `author-name`, `author-link`, `author-avatar`
2125                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2126                         dbesc($guid));
2127
2128                 if (dbm::is_result($r)) {
2129                         logger("reshared message ".$guid." already exists on system.");
2130
2131                         // Maybe it is already a reshared item?
2132                         // Then refetch the content, if it is a reshare from a reshare.
2133                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2134                         if (self::is_reshare($r[0]["body"], true)) {
2135                                 $r = array();
2136                         } elseif (self::is_reshare($r[0]["body"], false)) {
2137                                 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2138
2139                                 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2140
2141                                 // Add OEmbed and other information to the body
2142                                 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2143
2144                                 return $r[0];
2145                         } else {
2146                                 return $r[0];
2147                         }
2148                 }
2149
2150                 if (!dbm::is_result($r)) {
2151                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2152                         logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2153                         $item_id = self::store_by_guid($guid, $server);
2154
2155                         if (!$item_id) {
2156                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2157                                 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2158                                 $item_id = self::store_by_guid($guid, $server);
2159                         }
2160
2161                         if ($item_id) {
2162                                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2163                                                 `author-name`, `author-link`, `author-avatar`
2164                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2165                                         intval($item_id));
2166
2167                                 if (dbm::is_result($r)) {
2168                                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2169                                         if (self::is_reshare($r[0]["body"], false)) {
2170                                                 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2171                                                 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2172                                         }
2173
2174                                         return $r[0];
2175                                 }
2176
2177                         }
2178                 }
2179                 return false;
2180         }
2181
2182         /**
2183          * @brief Processes a reshare message
2184          *
2185          * @param array $importer Array of the importer user
2186          * @param object $data The message object
2187          * @param string $xml The original XML of the message
2188          *
2189          * @return int the message id
2190          */
2191         private static function receive_reshare($importer, $data, $xml) {
2192                 $root_author = notags(unxmlify($data->root_author));
2193                 $root_guid = notags(unxmlify($data->root_guid));
2194                 $guid = notags(unxmlify($data->guid));
2195                 $author = notags(unxmlify($data->author));
2196                 $public = notags(unxmlify($data->public));
2197                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2198
2199                 $contact = self::allowed_contact_by_handle($importer, $author, false);
2200                 if (!$contact) {
2201                         return false;
2202                 }
2203
2204                 $message_id = self::message_exists($importer["uid"], $guid);
2205                 if ($message_id) {
2206                         return $message_id;
2207                 }
2208
2209                 $original_item = self::original_item($root_guid, $root_author, $author);
2210                 if (!$original_item) {
2211                         return false;
2212                 }
2213
2214                 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2215
2216                 $datarray = array();
2217
2218                 $datarray["uid"] = $importer["uid"];
2219                 $datarray["contact-id"] = $contact["id"];
2220                 $datarray["network"]  = NETWORK_DIASPORA;
2221
2222                 $datarray["author-name"] = $contact["name"];
2223                 $datarray["author-link"] = $contact["url"];
2224                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2225
2226                 $datarray["owner-name"] = $datarray["author-name"];
2227                 $datarray["owner-link"] = $datarray["author-link"];
2228                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2229
2230                 $datarray["guid"] = $guid;
2231                 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2232
2233                 $datarray["verb"] = ACTIVITY_POST;
2234                 $datarray["gravity"] = GRAVITY_PARENT;
2235
2236                 $datarray["object"] = $xml;
2237
2238                 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2239                                         $original_item["guid"], $original_item["created"], $orig_url);
2240                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2241
2242                 $datarray["tag"] = $original_item["tag"];
2243                 $datarray["app"]  = $original_item["app"];
2244
2245                 $datarray["plink"] = self::plink($author, $guid);
2246                 $datarray["private"] = (($public == "false") ? 1 : 0);
2247                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2248
2249                 $datarray["object-type"] = $original_item["object-type"];
2250
2251                 self::fetch_guid($datarray);
2252                 $message_id = item_store($datarray);
2253
2254                 if ($message_id) {
2255                         logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2256                 }
2257
2258                 return $message_id;
2259         }
2260
2261         /**
2262          * @brief Processes retractions
2263          *
2264          * @param array $importer Array of the importer user
2265          * @param array $contact The contact of the item owner
2266          * @param object $data The message object
2267          *
2268          * @return bool success
2269          */
2270         private static function item_retraction($importer, $contact, $data) {
2271                 $target_type = notags(unxmlify($data->target_type));
2272                 $target_guid = notags(unxmlify($data->target_guid));
2273                 $author = notags(unxmlify($data->author));
2274
2275                 $person = self::person_by_handle($author);
2276                 if (!is_array($person)) {
2277                         logger("unable to find author detail for ".$author);
2278                         return false;
2279                 }
2280
2281                 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2282                         dbesc($target_guid),
2283                         intval($importer["uid"])
2284                 );
2285                 if (!$r)
2286                         return false;
2287
2288                 // Check if the sender is the thread owner
2289                 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2290                         intval($r[0]["parent"]));
2291
2292                 // Only delete it if the parent author really fits
2293                 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2294                         logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2295                         return false;
2296                 }
2297
2298                 // 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
2299                 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2300                         dbesc(datetime_convert()),
2301                         dbesc(datetime_convert()),
2302                         intval($r[0]["id"])
2303                 );
2304                 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2305
2306                 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2307
2308                 // Now check if the retraction needs to be relayed by us
2309                 if($p[0]["origin"]) {
2310                         // notify others
2311                         proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2312                 }
2313
2314                 return true;
2315         }
2316
2317         /**
2318          * @brief Receives retraction messages
2319          *
2320          * @param array $importer Array of the importer user
2321          * @param string $sender The sender of the message
2322          * @param object $data The message object
2323          *
2324          * @return bool Success
2325          */
2326         private static function receive_retraction($importer, $sender, $data) {
2327                 $target_type = notags(unxmlify($data->target_type));
2328
2329                 $contact = self::contact_by_handle($importer["uid"], $sender);
2330                 if (!$contact) {
2331                         logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2332                         return false;
2333                 }
2334
2335                 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2336
2337                 switch ($target_type) {
2338                         case "Comment":
2339                         case "Like":
2340                         case "Post": // "Post" will be supported in a future version
2341                         case "Reshare":
2342                         case "StatusMessage":
2343                                 return self::item_retraction($importer, $contact, $data);;
2344
2345                         case "Contact":
2346                         case "Person":
2347                                 /// @todo What should we do with an "unshare"?
2348                                 // Removing the contact isn't correct since we still can read the public items
2349                                 contact_remove($contact["id"]);
2350                                 return true;
2351
2352                         default:
2353                                 logger("Unknown target type ".$target_type);
2354                                 return false;
2355                 }
2356                 return true;
2357         }
2358
2359         /**
2360          * @brief Receives status messages
2361          *
2362          * @param array $importer Array of the importer user
2363          * @param object $data The message object
2364          * @param string $xml The original XML of the message
2365          *
2366          * @return int The message id of the newly created item
2367          */
2368         private static function receive_status_message($importer, $data, $xml) {
2369                 $raw_message = unxmlify($data->raw_message);
2370                 $guid = notags(unxmlify($data->guid));
2371                 $author = notags(unxmlify($data->author));
2372                 $public = notags(unxmlify($data->public));
2373                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2374                 $provider_display_name = notags(unxmlify($data->provider_display_name));
2375
2376                 /// @todo enable support for polls
2377                 //if ($data->poll) {
2378                 //      foreach ($data->poll AS $poll)
2379                 //              print_r($poll);
2380                 //      die("poll!\n");
2381                 //}
2382                 $contact = self::allowed_contact_by_handle($importer, $author, false);
2383                 if (!$contact) {
2384                         return false;
2385                 }
2386
2387                 $message_id = self::message_exists($importer["uid"], $guid);
2388                 if ($message_id) {
2389                         return $message_id;
2390                 }
2391
2392                 $address = array();
2393                 if ($data->location) {
2394                         foreach ($data->location->children() AS $fieldname => $data) {
2395                                 $address[$fieldname] = notags(unxmlify($data));
2396                         }
2397                 }
2398
2399                 $body = diaspora2bb($raw_message);
2400
2401                 $datarray = array();
2402
2403                 // Attach embedded pictures to the body
2404                 if ($data->photo) {
2405                         foreach ($data->photo AS $photo) {
2406                                 $body = "[img]".unxmlify($photo->remote_photo_path).
2407                                         unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2408                         }
2409
2410                         $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2411                 } else {
2412                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2413
2414                         // Add OEmbed and other information to the body
2415                         if (!self::is_redmatrix($contact["url"])) {
2416                                 $body = add_page_info_to_body($body, false, true);
2417                         }
2418                 }
2419
2420                 $datarray["uid"] = $importer["uid"];
2421                 $datarray["contact-id"] = $contact["id"];
2422                 $datarray["network"] = NETWORK_DIASPORA;
2423
2424                 $datarray["author-name"] = $contact["name"];
2425                 $datarray["author-link"] = $contact["url"];
2426                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2427
2428                 $datarray["owner-name"] = $datarray["author-name"];
2429                 $datarray["owner-link"] = $datarray["author-link"];
2430                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2431
2432                 $datarray["guid"] = $guid;
2433                 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2434
2435                 $datarray["verb"] = ACTIVITY_POST;
2436                 $datarray["gravity"] = GRAVITY_PARENT;
2437
2438                 $datarray["object"] = $xml;
2439
2440                 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2441
2442                 if ($provider_display_name != "") {
2443                         $datarray["app"] = $provider_display_name;
2444                 }
2445
2446                 $datarray["plink"] = self::plink($author, $guid);
2447                 $datarray["private"] = (($public == "false") ? 1 : 0);
2448                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2449
2450                 if (isset($address["address"])) {
2451                         $datarray["location"] = $address["address"];
2452                 }
2453
2454                 if (isset($address["lat"]) AND isset($address["lng"])) {
2455                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
2456                 }
2457
2458                 self::fetch_guid($datarray);
2459                 $message_id = item_store($datarray);
2460
2461                 if ($message_id) {
2462                         logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2463                 }
2464
2465                 return $message_id;
2466         }
2467
2468         /* ************************************************************************************** *
2469          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2470          * ************************************************************************************** */
2471
2472         /**
2473          * @brief returnes the handle of a contact
2474          *
2475          * @param array $me contact array
2476          *
2477          * @return string the handle in the format user@domain.tld
2478          */
2479         private static function my_handle($contact) {
2480                 if ($contact["addr"] != "")
2481                         return $contact["addr"];
2482
2483                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2484                 // So - just in case - we build the the address here.
2485                 if ($contact["nickname"] != "")
2486                         $nick = $contact["nickname"];
2487                 else
2488                         $nick = $contact["nick"];
2489
2490                 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2491         }
2492
2493         /**
2494          * @brief Creates the envelope for the "fetch" endpoint
2495          *
2496          * @param string $msg The message that is to be transmitted
2497          * @param array $user The record of the sender
2498          *
2499          * @return string The envelope
2500          */
2501
2502         public static function build_magic_envelope($msg, $user) {
2503
2504                 $b64url_data = base64url_encode($msg);
2505                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2506
2507                 $key_id = base64url_encode(self::my_handle($user));
2508                 $type = "application/xml";
2509                 $encoding = "base64url";
2510                 $alg = "RSA-SHA256";
2511                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2512                 $signature = rsa_sign($signable_data, $user["prvkey"]);
2513                 $sig = base64url_encode($signature);
2514
2515                 $xmldata = array("me:env" => array("me:data" => $data,
2516                                                         "@attributes" => array("type" => $type),
2517                                                         "me:encoding" => $encoding,
2518                                                         "me:alg" => $alg,
2519                                                         "me:sig" => $sig,
2520                                                         "@attributes2" => array("key_id" => $key_id)));
2521
2522                 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2523
2524                 return xml::from_array($xmldata, $xml, false, $namespaces);
2525         }
2526
2527         /**
2528          * @brief Creates the envelope for a public message
2529          *
2530          * @param string $msg The message that is to be transmitted
2531          * @param array $user The record of the sender
2532          * @param array $contact Target of the communication
2533          * @param string $prvkey The private key of the sender
2534          * @param string $pubkey The public key of the receiver
2535          *
2536          * @return string The envelope
2537          */
2538         private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2539
2540                 logger("Message: ".$msg, LOGGER_DATA);
2541
2542                 $handle = self::my_handle($user);
2543
2544                 $b64url_data = base64url_encode($msg);
2545
2546                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2547
2548                 $type = "application/xml";
2549                 $encoding = "base64url";
2550                 $alg = "RSA-SHA256";
2551
2552                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2553
2554                 $signature = rsa_sign($signable_data,$prvkey);
2555                 $sig = base64url_encode($signature);
2556
2557                 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2558                                                         "me:env" => array("me:encoding" => $encoding,
2559                                                         "me:alg" => $alg,
2560                                                         "me:data" => $data,
2561                                                         "@attributes" => array("type" => $type),
2562                                                         "me:sig" => $sig)));
2563
2564                 $namespaces = array("" => "https://joindiaspora.com/protocol",
2565                                 "me" => "http://salmon-protocol.org/ns/magic-env");
2566
2567                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2568
2569                 logger("magic_env: ".$magic_env, LOGGER_DATA);
2570                 return $magic_env;
2571         }
2572
2573         /**
2574          * @brief Creates the envelope for a private message
2575          *
2576          * @param string $msg The message that is to be transmitted
2577          * @param array $user The record of the sender
2578          * @param array $contact Target of the communication
2579          * @param string $prvkey The private key of the sender
2580          * @param string $pubkey The public key of the receiver
2581          *
2582          * @return string The envelope
2583          */
2584         private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2585
2586                 logger("Message: ".$msg, LOGGER_DATA);
2587
2588                 // without a public key nothing will work
2589
2590                 if (!$pubkey) {
2591                         logger("pubkey missing: contact id: ".$contact["id"]);
2592                         return false;
2593                 }
2594
2595                 $inner_aes_key = random_string(32);
2596                 $b_inner_aes_key = base64_encode($inner_aes_key);
2597                 $inner_iv = random_string(16);
2598                 $b_inner_iv = base64_encode($inner_iv);
2599
2600                 $outer_aes_key = random_string(32);
2601                 $b_outer_aes_key = base64_encode($outer_aes_key);
2602                 $outer_iv = random_string(16);
2603                 $b_outer_iv = base64_encode($outer_iv);
2604
2605                 $handle = self::my_handle($user);
2606
2607                 $padded_data = pkcs5_pad($msg,16);
2608                 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2609
2610                 $b64_data = base64_encode($inner_encrypted);
2611
2612
2613                 $b64url_data = base64url_encode($b64_data);
2614                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2615
2616                 $type = "application/xml";
2617                 $encoding = "base64url";
2618                 $alg = "RSA-SHA256";
2619
2620                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2621
2622                 $signature = rsa_sign($signable_data,$prvkey);
2623                 $sig = base64url_encode($signature);
2624
2625                 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2626                                                         "aes_key" => $b_inner_aes_key,
2627                                                         "author_id" => $handle));
2628
2629                 $decrypted_header = xml::from_array($xmldata, $xml, true);
2630                 $decrypted_header = pkcs5_pad($decrypted_header,16);
2631
2632                 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2633
2634                 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2635
2636                 $encrypted_outer_key_bundle = "";
2637                 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2638
2639                 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2640
2641                 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2642
2643                 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2644                                                                 "ciphertext" => base64_encode($ciphertext)));
2645                 $cipher_json = base64_encode($encrypted_header_json_object);
2646
2647                 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2648                                                 "me:env" => array("me:encoding" => $encoding,
2649                                                                 "me:alg" => $alg,
2650                                                                 "me:data" => $data,
2651                                                                 "@attributes" => array("type" => $type),
2652                                                                 "me:sig" => $sig)));
2653
2654                 $namespaces = array("" => "https://joindiaspora.com/protocol",
2655                                 "me" => "http://salmon-protocol.org/ns/magic-env");
2656
2657                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2658
2659                 logger("magic_env: ".$magic_env, LOGGER_DATA);
2660                 return $magic_env;
2661         }
2662
2663         /**
2664          * @brief Create the envelope for a message
2665          *
2666          * @param string $msg The message that is to be transmitted
2667          * @param array $user The record of the sender
2668          * @param array $contact Target of the communication
2669          * @param string $prvkey The private key of the sender
2670          * @param string $pubkey The public key of the receiver
2671          * @param bool $public Is the message public?
2672          *
2673          * @return string The message that will be transmitted to other servers
2674          */
2675         private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2676
2677                 if ($public)
2678                         $magic_env =  self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2679                 else
2680                         $magic_env =  self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2681
2682                 // The data that will be transmitted is double encoded via "urlencode", strange ...
2683                 $slap = "xml=".urlencode(urlencode($magic_env));
2684                 return $slap;
2685         }
2686
2687         /**
2688          * @brief Creates a signature for a message
2689          *
2690          * @param array $owner the array of the owner of the message
2691          * @param array $message The message that is to be signed
2692          *
2693          * @return string The signature
2694          */
2695         private static function signature($owner, $message) {
2696                 $sigmsg = $message;
2697                 unset($sigmsg["author_signature"]);
2698                 unset($sigmsg["parent_author_signature"]);
2699
2700                 $signed_text = implode(";", $sigmsg);
2701
2702                 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2703         }
2704
2705         /**
2706          * @brief Transmit a message to a target server
2707          *
2708          * @param array $owner the array of the item owner
2709          * @param array $contact Target of the communication
2710          * @param string $slap The message that is to be transmitted
2711          * @param bool $public_batch Is it a public post?
2712          * @param bool $queue_run Is the transmission called from the queue?
2713          * @param string $guid message guid
2714          *
2715          * @return int Result of the transmission
2716          */
2717         public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2718
2719                 $a = get_app();
2720
2721                 $enabled = intval(get_config("system", "diaspora_enabled"));
2722                 if(!$enabled)
2723                         return 200;
2724
2725                 $logid = random_string(4);
2726                 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2727                 if (!$dest_url) {
2728                         logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2729                         return 0;
2730                 }
2731
2732                 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2733
2734                 if (!$queue_run && was_recently_delayed($contact["id"])) {
2735                         $return_code = 0;
2736                 } else {
2737                         if (!intval(get_config("system", "diaspora_test"))) {
2738                                 post_url($dest_url."/", $slap);
2739                                 $return_code = $a->get_curl_code();
2740                         } else {
2741                                 logger("test_mode");
2742                                 return 200;
2743                         }
2744                 }
2745
2746                 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2747
2748                 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2749                         logger("queue message");
2750
2751                         $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2752                                 intval($contact["id"]),
2753                                 dbesc(NETWORK_DIASPORA),
2754                                 dbesc($slap),
2755                                 intval($public_batch)
2756                         );
2757                         if ($r) {
2758                                 logger("add_to_queue ignored - identical item already in queue");
2759                         } else {
2760                                 // queue message for redelivery
2761                                 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2762
2763                                 // The message could not be delivered. We mark the contact as "dead"
2764                                 mark_for_death($contact);
2765                         }
2766                 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2767                         // We successfully delivered a message, the contact is alive
2768                         unmark_for_death($contact);
2769                 }
2770
2771                 return(($return_code) ? $return_code : (-1));
2772         }
2773
2774
2775         /**
2776          * @brief Build the post xml
2777          *
2778          * @param string $type The message type
2779          * @param array $message The message data
2780          *
2781          * @return string The post XML
2782          */
2783         public static function build_post_xml($type, $message) {
2784
2785                 $data = array("XML" => array("post" => array($type => $message)));
2786                 return xml::from_array($data, $xml);
2787         }
2788
2789         /**
2790          * @brief Builds and transmit messages
2791          *
2792          * @param array $owner the array of the item owner
2793          * @param array $contact Target of the communication
2794          * @param string $type The message type
2795          * @param array $message The message data
2796          * @param bool $public_batch Is it a public post?
2797          * @param string $guid message guid
2798          * @param bool $spool Should the transmission be spooled or transmitted?
2799          *
2800          * @return int Result of the transmission
2801          */
2802         private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2803
2804                 $msg = self::build_post_xml($type, $message);
2805
2806                 logger('message: '.$msg, LOGGER_DATA);
2807                 logger('send guid '.$guid, LOGGER_DEBUG);
2808
2809                 // Fallback if the private key wasn't transmitted in the expected field
2810                 if ($owner['uprvkey'] == "")
2811                         $owner['uprvkey'] = $owner['prvkey'];
2812
2813                 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2814
2815                 if ($spool) {
2816                         add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2817                         return true;
2818                 } else
2819                         $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2820
2821                 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2822
2823                 return $return_code;
2824         }
2825
2826         /**
2827          * @brief Sends a "share" message
2828          *
2829          * @param array $owner the array of the item owner
2830          * @param array $contact Target of the communication
2831          *
2832          * @return int The result of the transmission
2833          */
2834         public static function send_share($owner,$contact) {
2835
2836                 $message = array("sender_handle" => self::my_handle($owner),
2837                                 "recipient_handle" => $contact["addr"]);
2838
2839                 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2840
2841                 return self::build_and_transmit($owner, $contact, "request", $message);
2842         }
2843
2844         /**
2845          * @brief sends an "unshare"
2846          *
2847          * @param array $owner the array of the item owner
2848          * @param array $contact Target of the communication
2849          *
2850          * @return int The result of the transmission
2851          */
2852         public static function send_unshare($owner,$contact) {
2853
2854                 $message = array("post_guid" => $owner["guid"],
2855                                 "diaspora_handle" => self::my_handle($owner),
2856                                 "type" => "Person");
2857
2858                 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2859
2860                 return self::build_and_transmit($owner, $contact, "retraction", $message);
2861         }
2862
2863         /**
2864          * @brief Checks a message body if it is a reshare
2865          *
2866          * @param string $body The message body that is to be check
2867          * @param bool $complete Should it be a complete check or a simple check?
2868          *
2869          * @return array|bool Reshare details or "false" if no reshare
2870          */
2871         public static function is_reshare($body, $complete = true) {
2872                 $body = trim($body);
2873
2874                 // Skip if it isn't a pure repeated messages
2875                 // Does it start with a share?
2876                 if ((strpos($body, "[share") > 0) AND $complete)
2877                         return(false);
2878
2879                 // Does it end with a share?
2880                 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2881                         return(false);
2882
2883                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2884                 // Skip if there is no shared message in there
2885                 if ($body == $attributes)
2886                         return(false);
2887
2888                 // If we don't do the complete check we quit here
2889                 if (!$complete)
2890                         return true;
2891
2892                 $guid = "";
2893                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2894                 if ($matches[1] != "")
2895                         $guid = $matches[1];
2896
2897                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2898                 if ($matches[1] != "")
2899                         $guid = $matches[1];
2900
2901                 if ($guid != "") {
2902                         $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2903                                 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2904                         if ($r) {
2905                                 $ret= array();
2906                                 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2907                                 $ret["root_guid"] = $guid;
2908                                 return($ret);
2909                         }
2910                 }
2911
2912                 $profile = "";
2913                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2914                 if ($matches[1] != "")
2915                         $profile = $matches[1];
2916
2917                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2918                 if ($matches[1] != "")
2919                         $profile = $matches[1];
2920
2921                 $ret= array();
2922
2923                 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2924                 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2925                         return(false);
2926
2927                 $link = "";
2928                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2929                 if ($matches[1] != "")
2930                         $link = $matches[1];
2931
2932                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2933                 if ($matches[1] != "")
2934                         $link = $matches[1];
2935
2936                 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2937                 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
2938                         return(false);
2939
2940                 return($ret);
2941         }
2942
2943         /**
2944          * @brief Create an event array
2945          *
2946          * @param integer $event_id The id of the event
2947          *
2948          * @return array with event data
2949          */
2950         private static function build_event($event_id) {
2951
2952                 $r = q("SELECT `uid`, `start`, `finish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
2953                 if (!dbm::is_result($r)) {
2954                         return array();
2955                 }
2956
2957                 $event = $r[0];
2958
2959                 $eventdata = array();
2960
2961                 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
2962                 if (!dbm::is_result($r)) {
2963                         return array();
2964                 }
2965
2966                 $user = $r[0];
2967
2968                 if ($event['adjust']) {
2969                         $eventdata['timezone'] = $user['timezone'];
2970
2971                         if ($eventdata['timezone'] == "") {
2972                                 $eventdata['timezone'] = 'UTC';
2973                         }
2974                         $mask = 'Y-m-d\TH:i:s\Z';
2975                 } else {
2976                         $mask = 'Y-m-d\TH:i:s';
2977                 }
2978
2979                 if ($event['start']) {
2980                         $eventdata['start'] = datetime_convert("UTC", "UTC", $event['start'], $mask);
2981                 }
2982                 if ($event['finish']) {
2983                         $eventdata['end'] = datetime_convert("UTC", "UTC", $event['finish'], $mask);
2984                 }
2985                 if ($event['summary']) {
2986                         $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
2987                 }
2988                 if ($event['desc']) {
2989                         $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
2990                 }
2991                 if ($event['location']) {
2992                         $location = array();
2993                         $location["address"] = html_entity_decode(bb2diaspora($event['location']));
2994                         $location["lat"] = 0;
2995                         $location["lng"] = 0;
2996                         $eventdata['location'] = $location;
2997                 }
2998
2999                 return $eventdata;
3000         }
3001
3002         /**
3003          * @brief Create a post (status message or reshare)
3004          *
3005          * @param array $item The item that will be exported
3006          * @param array $owner the array of the item owner
3007          *
3008          * @return array
3009          * 'type' -> Message type ("status_message" or "reshare")
3010          * 'message' -> Array of XML elements of the status
3011          */
3012         public static function build_status($item, $owner) {
3013
3014                 $cachekey = "diaspora:build_status:".$item['guid'];
3015
3016                 $result = Cache::get($cachekey);
3017                 if (!is_null($result)) {
3018                         return $result;
3019                 }
3020
3021                 $myaddr = self::my_handle($owner);
3022
3023                 $public = (($item["private"]) ? "false" : "true");
3024
3025                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3026
3027                 // Detect a share element and do a reshare
3028                 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3029                         $message = array("root_diaspora_id" => $ret["root_handle"],
3030                                         "root_guid" => $ret["root_guid"],
3031                                         "guid" => $item["guid"],
3032                                         "diaspora_handle" => $myaddr,
3033                                         "public" => $public,
3034                                         "created_at" => $created,
3035                                         "provider_display_name" => $item["app"]);
3036
3037                         $type = "reshare";
3038                 } else {
3039                         $title = $item["title"];
3040                         $body = $item["body"];
3041
3042                         // convert to markdown
3043                         $body = html_entity_decode(bb2diaspora($body));
3044
3045                         // Adding the title
3046                         if(strlen($title))
3047                                 $body = "## ".html_entity_decode($title)."\n\n".$body;
3048
3049                         if ($item["attach"]) {
3050                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3051                                 if(cnt) {
3052                                         $body .= "\n".t("Attachments:")."\n";
3053                                         foreach($matches as $mtch)
3054                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3055                                 }
3056                         }
3057
3058                         $location = array();
3059
3060                         if ($item["location"] != "")
3061                                 $location["address"] = $item["location"];
3062
3063                         if ($item["coord"] != "") {
3064                                 $coord = explode(" ", $item["coord"]);
3065                                 $location["lat"] = $coord[0];
3066                                 $location["lng"] = $coord[1];
3067                         }
3068
3069                         $message = array("raw_message" => $body,
3070                                         "location" => $location,
3071                                         "guid" => $item["guid"],
3072                                         "diaspora_handle" => $myaddr,
3073                                         "public" => $public,
3074                                         "created_at" => $created,
3075                                         "provider_display_name" => $item["app"]);
3076
3077                         // Diaspora rejects messages when they contain a location without "lat" or "lng"
3078                         if (!isset($location["lat"]) OR !isset($location["lng"])) {
3079                                 unset($message["location"]);
3080                         }
3081
3082                         if ($item['event-id'] > 0) {
3083                                 $event = self::build_event($item['event-id']);
3084                                 if (count($event)) {
3085                                         $message['event'] = $event;
3086                                 }
3087                         }
3088
3089                         $type = "status_message";
3090                 }
3091
3092                 $msg = array("type" => $type, "message" => $message);
3093
3094                 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3095
3096                 return $msg;
3097         }
3098
3099         /**
3100          * @brief Sends a post
3101          *
3102          * @param array $item The item that will be exported
3103          * @param array $owner the array of the item owner
3104          * @param array $contact Target of the communication
3105          * @param bool $public_batch Is it a public post?
3106          *
3107          * @return int The result of the transmission
3108          */
3109         public static function send_status($item, $owner, $contact, $public_batch = false) {
3110
3111                 $status = self::build_status($item, $owner);
3112
3113                 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3114         }
3115
3116         /**
3117          * @brief Creates a "like" object
3118          *
3119          * @param array $item The item that will be exported
3120          * @param array $owner the array of the item owner
3121          *
3122          * @return array The data for a "like"
3123          */
3124         private static function construct_like($item, $owner) {
3125
3126                 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3127                         dbesc($item["thr-parent"]));
3128                 if (!dbm::is_result($p))
3129                         return false;
3130
3131                 $parent = $p[0];
3132
3133                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3134                 $positive = "true";
3135
3136                 return(array("positive" => $positive,
3137                                 "guid" => $item["guid"],
3138                                 "target_type" => $target_type,
3139                                 "parent_guid" => $parent["guid"],
3140                                 "author_signature" => "",
3141                                 "diaspora_handle" => self::my_handle($owner)));
3142         }
3143
3144         /**
3145          * @brief Creates the object for a comment
3146          *
3147          * @param array $item The item that will be exported
3148          * @param array $owner the array of the item owner
3149          *
3150          * @return array The data for a comment
3151          */
3152         private static function construct_comment($item, $owner) {
3153
3154                 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3155                         intval($item["parent"]),
3156                         intval($item["parent"])
3157                 );
3158
3159                 if (!dbm::is_result($p))
3160                         return false;
3161
3162                 $parent = $p[0];
3163
3164                 $text = html_entity_decode(bb2diaspora($item["body"]));
3165                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3166
3167                 $comment = array("guid" => $item["guid"],
3168                                 "parent_guid" => $parent["guid"],
3169                                 "author_signature" => "",
3170                                 "text" => $text,
3171                                 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3172                                 "diaspora_handle" => self::my_handle($owner));
3173
3174                 // Send the thread parent guid only if it is a threaded comment
3175                 if ($item['thr-parent'] != $item['parent-uri']) {
3176                         $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3177                 }
3178                 return($comment);
3179         }
3180
3181         /**
3182          * @brief Send a like or a comment
3183          *
3184          * @param array $item The item that will be exported
3185          * @param array $owner the array of the item owner
3186          * @param array $contact Target of the communication
3187          * @param bool $public_batch Is it a public post?
3188          *
3189          * @return int The result of the transmission
3190          */
3191         public static function send_followup($item,$owner,$contact,$public_batch = false) {
3192
3193                 if($item['verb'] === ACTIVITY_LIKE) {
3194                         $message = self::construct_like($item, $owner);
3195                         $type = "like";
3196                 } else {
3197                         $message = self::construct_comment($item, $owner);
3198                         $type = "comment";
3199                 }
3200
3201                 if (!$message)
3202                         return false;
3203
3204                 $message["author_signature"] = self::signature($owner, $message);
3205
3206                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3207         }
3208
3209         /**
3210          * @brief Creates a message from a signature record entry
3211          *
3212          * @param array $item The item that will be exported
3213          * @param array $signature The entry of the "sign" record
3214          *
3215          * @return string The message
3216          */
3217         private static function message_from_signature($item, $signature) {
3218
3219                 // Split the signed text
3220                 $signed_parts = explode(";", $signature['signed_text']);
3221
3222                 if ($item["deleted"])
3223                         $message = array("parent_author_signature" => "",
3224                                         "target_guid" => $signed_parts[0],
3225                                         "target_type" => $signed_parts[1],
3226                                         "sender_handle" => $signature['signer'],
3227                                         "target_author_signature" => $signature['signature']);
3228                 elseif ($item['verb'] === ACTIVITY_LIKE)
3229                         $message = array("positive" => $signed_parts[0],
3230                                         "guid" => $signed_parts[1],
3231                                         "target_type" => $signed_parts[2],
3232                                         "parent_guid" => $signed_parts[3],
3233                                         "parent_author_signature" => "",
3234                                         "author_signature" => $signature['signature'],
3235                                         "diaspora_handle" => $signed_parts[4]);
3236                 else {
3237                         // Remove the comment guid
3238                         $guid = array_shift($signed_parts);
3239
3240                         // Remove the parent guid
3241                         $parent_guid = array_shift($signed_parts);
3242
3243                         // Remove the handle
3244                         $handle = array_pop($signed_parts);
3245
3246                         // Glue the parts together
3247                         $text = implode(";", $signed_parts);
3248
3249                         $message = array("guid" => $guid,
3250                                         "parent_guid" => $parent_guid,
3251                                         "parent_author_signature" => "",
3252                                         "author_signature" => $signature['signature'],
3253                                         "text" => implode(";", $signed_parts),
3254                                         "diaspora_handle" => $handle);
3255                 }
3256                 return $message;
3257         }
3258
3259         /**
3260          * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3261          *
3262          * @param array $item The item that will be exported
3263          * @param array $owner the array of the item owner
3264          * @param array $contact Target of the communication
3265          * @param bool $public_batch Is it a public post?
3266          *
3267          * @return int The result of the transmission
3268          */
3269         public static function send_relay($item, $owner, $contact, $public_batch = false) {
3270
3271                 if ($item["deleted"])
3272                         return self::send_retraction($item, $owner, $contact, $public_batch, true);
3273                 elseif ($item['verb'] === ACTIVITY_LIKE)
3274                         $type = "like";
3275                 else
3276                         $type = "comment";
3277
3278                 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3279
3280                 // fetch the original signature
3281
3282                 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3283                         intval($item["id"]));
3284
3285                 if (!$r) {
3286                         logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3287                         return false;
3288                 }
3289
3290                 $signature = $r[0];
3291
3292                 // Old way - is used by the internal Friendica functions
3293                 /// @todo Change all signatur storing functions to the new format
3294                 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3295                         $message = self::message_from_signature($item, $signature);
3296                 else {// New way
3297                         $msg = json_decode($signature['signed_text'], true);
3298
3299                         $message = array();
3300                         if (is_array($msg)) {
3301                                 foreach ($msg AS $field => $data) {
3302                                         if (!$item["deleted"]) {
3303                                                 if ($field == "author")
3304                                                         $field = "diaspora_handle";
3305                                                 if ($field == "parent_type")
3306                                                         $field = "target_type";
3307                                         }
3308
3309                                         $message[$field] = $data;
3310                                 }
3311                         } else
3312                                 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3313                 }
3314
3315                 $message["parent_author_signature"] = self::signature($owner, $message);
3316
3317                 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3318
3319                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3320         }
3321
3322         /**
3323          * @brief Sends a retraction (deletion) of a message, like or comment
3324          *
3325          * @param array $item The item that will be exported
3326          * @param array $owner the array of the item owner
3327          * @param array $contact Target of the communication
3328          * @param bool $public_batch Is it a public post?
3329          * @param bool $relay Is the retraction transmitted from a relay?
3330          *
3331          * @return int The result of the transmission
3332          */
3333         public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3334
3335                 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3336
3337                 // Check whether the retraction is for a top-level post or whether it's a relayable
3338                 if ($item["uri"] !== $item["parent-uri"]) {
3339                         $msg_type = "relayable_retraction";
3340                         $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3341                 } else {
3342                         $msg_type = "signed_retraction";
3343                         $target_type = "StatusMessage";
3344                 }
3345
3346                 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3347                         $signature = "parent_author_signature";
3348                 else
3349                         $signature = "target_author_signature";
3350
3351                 $signed_text = $item["guid"].";".$target_type;
3352
3353                 $message = array("target_guid" => $item['guid'],
3354                                 "target_type" => $target_type,
3355                                 "sender_handle" => $itemaddr,
3356                                 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3357
3358                 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3359
3360                 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3361         }
3362
3363         /**
3364          * @brief Sends a mail
3365          *
3366          * @param array $item The item that will be exported
3367          * @param array $owner The owner
3368          * @param array $contact Target of the communication
3369          *
3370          * @return int The result of the transmission
3371          */
3372         public static function send_mail($item, $owner, $contact) {
3373
3374                 $myaddr = self::my_handle($owner);
3375
3376                 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3377                         intval($item["convid"]),
3378                         intval($item["uid"])
3379                 );
3380
3381                 if (!dbm::is_result($r)) {
3382                         logger("conversation not found.");
3383                         return;
3384                 }
3385                 $cnv = $r[0];
3386
3387                 $conv = array(
3388                         "guid" => $cnv["guid"],
3389                         "subject" => $cnv["subject"],
3390                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3391                         "diaspora_handle" => $cnv["creator"],
3392                         "participant_handles" => $cnv["recips"]
3393                 );
3394
3395                 $body = bb2diaspora($item["body"]);
3396                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3397
3398                 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3399                 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3400
3401                 $msg = array(
3402                         "guid" => $item["guid"],
3403                         "parent_guid" => $cnv["guid"],
3404                         "parent_author_signature" => $sig,
3405                         "author_signature" => $sig,
3406                         "text" => $body,
3407                         "created_at" => $created,
3408                         "diaspora_handle" => $myaddr,
3409                         "conversation_guid" => $cnv["guid"]
3410                 );
3411
3412                 if ($item["reply"]) {
3413                         $message = $msg;
3414                         $type = "message";
3415                 } else {
3416                         $message = array("guid" => $cnv["guid"],
3417                                         "subject" => $cnv["subject"],
3418                                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3419                                         "message" => $msg,
3420                                         "diaspora_handle" => $cnv["creator"],
3421                                         "participant_handles" => $cnv["recips"]);
3422
3423                         $type = "conversation";
3424                 }
3425
3426                 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3427         }
3428
3429         /**
3430          * @brief Sends profile data
3431          *
3432          * @param int $uid The user id
3433          */
3434         public static function send_profile($uid, $recips = false) {
3435
3436                 if (!$uid)
3437                         return;
3438
3439                 if (!$recips)
3440                         $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3441                                 AND `uid` = %d AND `rel` != %d",
3442                                 dbesc(NETWORK_DIASPORA),
3443                                 intval($uid),
3444                                 intval(CONTACT_IS_SHARING)
3445                         );
3446                 if (!$recips)
3447                         return;
3448
3449                 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3450                         FROM `profile`
3451                         INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3452                         INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3453                         WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3454                         intval($uid)
3455                 );
3456
3457                 if (!$r)
3458                         return;
3459
3460                 $profile = $r[0];
3461
3462                 $handle = $profile["addr"];
3463                 $first = ((strpos($profile['name'],' ')
3464                         ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3465                 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3466                 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3467                 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3468                 $small = App::get_baseurl().'/photo/custom/50/'  .$profile['uid'].'.jpg';
3469                 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3470
3471                 if ($searchable === 'true') {
3472                         $dob = '1000-00-00';
3473
3474                         if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3475                                 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3476
3477                         $about = $profile['about'];
3478                         $about = strip_tags(bbcode($about));
3479
3480                         $location = formatted_location($profile);
3481                         $tags = '';
3482                         if ($profile['pub_keywords']) {
3483                                 $kw = str_replace(',',' ',$profile['pub_keywords']);
3484                                 $kw = str_replace('  ',' ',$kw);
3485                                 $arr = explode(' ',$profile['pub_keywords']);
3486                                 if (count($arr)) {
3487                                         for($x = 0; $x < 5; $x ++) {
3488                                                 if (trim($arr[$x]))
3489                                                         $tags .= '#'. trim($arr[$x]) .' ';
3490                                         }
3491                                 }
3492                         }
3493                         $tags = trim($tags);
3494                 }
3495
3496                 $message = array("diaspora_handle" => $handle,
3497                                 "first_name" => $first,
3498                                 "last_name" => $last,
3499                                 "image_url" => $large,
3500                                 "image_url_medium" => $medium,
3501                                 "image_url_small" => $small,
3502                                 "birthday" => $dob,
3503                                 "gender" => $profile['gender'],
3504                                 "bio" => $about,
3505                                 "location" => $location,
3506                                 "searchable" => $searchable,
3507                                 "tag_string" => $tags);
3508
3509                 foreach($recips as $recip) {
3510                         logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3511                         self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3512                 }
3513         }
3514
3515         /**
3516          * @brief Stores the signature for likes that are created on our system
3517          *
3518          * @param array $contact The contact array of the "like"
3519          * @param int $post_id The post id of the "like"
3520          *
3521          * @return bool Success
3522          */
3523         public static function store_like_signature($contact, $post_id) {
3524
3525                 // Is the contact the owner? Then fetch the private key
3526                 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3527                         logger("No owner post, so not storing signature", LOGGER_DEBUG);
3528                         return false;
3529                 }
3530
3531                 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3532                 if(!$r)
3533                         return false;
3534
3535                 $contact["uprvkey"] = $r[0]['prvkey'];
3536
3537                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3538                 if (!$r)
3539                         return false;
3540
3541                 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
3542                         return false;
3543
3544                 $message = self::construct_like($r[0], $contact);
3545                 $message["author_signature"] = self::signature($contact, $message);
3546
3547                 // We now store the signature more flexible to dynamically support new fields.
3548                 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3549                 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3550                         intval($message_id),
3551                         dbesc(json_encode($message))
3552                 );
3553
3554                 logger('Stored diaspora like signature');
3555                 return true;
3556         }
3557
3558         /**
3559          * @brief Stores the signature for comments that are created on our system
3560          *
3561          * @param array $item The item array of the comment
3562          * @param array $contact The contact array of the item owner
3563          * @param string $uprvkey The private key of the sender
3564          * @param int $message_id The message id of the comment
3565          *
3566          * @return bool Success
3567          */
3568         public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3569
3570                 if ($uprvkey == "") {
3571                         logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3572                         return false;
3573                 }
3574
3575                 $contact["uprvkey"] = $uprvkey;
3576
3577                 $message = self::construct_comment($item, $contact);
3578                 $message["author_signature"] = self::signature($contact, $message);
3579
3580                 // We now store the signature more flexible to dynamically support new fields.
3581                 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3582                 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3583                         intval($message_id),
3584                         dbesc(json_encode($message))
3585                 );
3586
3587                 logger('Stored diaspora comment signature');
3588                 return true;
3589         }
3590 }
3591 ?>