]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
Merge remote-tracking branch 'upstream/develop' into develop
[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         /**
1184          * @brief Processes an incoming comment
1185          *
1186          * @param array $importer Array of the importer user
1187          * @param string $sender The sender of the message
1188          * @param object $data The message object
1189          * @param string $xml The original XML of the message
1190          *
1191          * @return int The message id of the generated comment or "false" if there was an error
1192          */
1193         private static function receive_comment($importer, $sender, $data, $xml) {
1194                 $guid = notags(unxmlify($data->guid));
1195                 $parent_guid = notags(unxmlify($data->parent_guid));
1196                 $text = unxmlify($data->text);
1197                 $author = notags(unxmlify($data->author));
1198
1199                 if (isset($data->created_at)) {
1200                         $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1201                 } else {
1202                         $created_at = datetime_convert();
1203                 }
1204
1205                 if (isset($data->thread_parent_guid)) {
1206                         $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1207                         $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1208                 } else {
1209                         $thr_uri = "";
1210                 }
1211
1212                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1213                 if (!$contact) {
1214                         return false;
1215                 }
1216
1217                 $message_id = self::message_exists($importer["uid"], $guid);
1218                 if ($message_id) {
1219                         return $message_id;
1220                 }
1221
1222                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1223                 if (!$parent_item) {
1224                         return false;
1225                 }
1226
1227                 $person = self::person_by_handle($author);
1228                 if (!is_array($person)) {
1229                         logger("unable to find author details");
1230                         return false;
1231                 }
1232
1233                 // Fetch the contact id - if we know this contact
1234                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1235
1236                 $datarray = array();
1237
1238                 $datarray["uid"] = $importer["uid"];
1239                 $datarray["contact-id"] = $author_contact["cid"];
1240                 $datarray["network"]  = $author_contact["network"];
1241
1242                 $datarray["author-name"] = $person["name"];
1243                 $datarray["author-link"] = $person["url"];
1244                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1245
1246                 $datarray["owner-name"] = $contact["name"];
1247                 $datarray["owner-link"] = $contact["url"];
1248                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1249
1250                 $datarray["guid"] = $guid;
1251                 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1252
1253                 $datarray["type"] = "remote-comment";
1254                 $datarray["verb"] = ACTIVITY_POST;
1255                 $datarray["gravity"] = GRAVITY_COMMENT;
1256
1257                 if ($thr_uri != "") {
1258                         $datarray["parent-uri"] = $thr_uri;
1259                 } else {
1260                         $datarray["parent-uri"] = $parent_item["uri"];
1261                 }
1262
1263                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1264                 $datarray["object"] = $xml;
1265
1266                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1267
1268                 $body = diaspora2bb($text);
1269
1270                 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1271
1272                 self::fetch_guid($datarray);
1273
1274                 $message_id = item_store($datarray);
1275
1276                 if ($message_id) {
1277                         logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1278                 }
1279
1280                 // If we are the origin of the parent we store the original data and notify our followers
1281                 if($message_id AND $parent_item["origin"]) {
1282
1283                         // Formerly we stored the signed text, the signature and the author in different fields.
1284                         // We now store the raw data so that we are more flexible.
1285                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1286                                 intval($message_id),
1287                                 dbesc(json_encode($data))
1288                         );
1289
1290                         // notify others
1291                         proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1292                 }
1293
1294                 return $message_id;
1295         }
1296
1297         /**
1298          * @brief processes and stores private messages
1299          *
1300          * @param array $importer Array of the importer user
1301          * @param array $contact The contact of the message
1302          * @param object $data The message object
1303          * @param array $msg Array of the processed message, author handle and key
1304          * @param object $mesg The private message
1305          * @param array $conversation The conversation record to which this message belongs
1306          *
1307          * @return bool "true" if it was successful
1308          */
1309         private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1310                 $guid = notags(unxmlify($data->guid));
1311                 $subject = notags(unxmlify($data->subject));
1312                 $author = notags(unxmlify($data->author));
1313
1314                 $msg_guid = notags(unxmlify($mesg->guid));
1315                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1316                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1317                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1318                 $msg_text = unxmlify($mesg->text);
1319                 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1320
1321                 // "diaspora_handle" is the element name from the old version
1322                 // "author" is the element name from the new version
1323                 if ($mesg->author) {
1324                         $msg_author = notags(unxmlify($mesg->author));
1325                 } elseif ($mesg->diaspora_handle) {
1326                         $msg_author = notags(unxmlify($mesg->diaspora_handle));
1327                 } else {
1328                         return false;
1329                 }
1330
1331                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1332
1333                 if ($msg_conversation_guid != $guid) {
1334                         logger("message conversation guid does not belong to the current conversation.");
1335                         return false;
1336                 }
1337
1338                 $body = diaspora2bb($msg_text);
1339                 $message_uri = $msg_author.":".$msg_guid;
1340
1341                 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1342
1343                 $author_signature = base64_decode($msg_author_signature);
1344
1345                 if (strcasecmp($msg_author,$msg["author"]) == 0) {
1346                         $person = $contact;
1347                         $key = $msg["key"];
1348                 } else {
1349                         $person = self::person_by_handle($msg_author);
1350
1351                         if (is_array($person) && x($person, "pubkey")) {
1352                                 $key = $person["pubkey"];
1353                         } else {
1354                                 logger("unable to find author details");
1355                                         return false;
1356                         }
1357                 }
1358
1359                 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1360                         logger("verification failed.");
1361                         return false;
1362                 }
1363
1364                 if ($msg_parent_author_signature) {
1365                         $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1366
1367                         $parent_author_signature = base64_decode($msg_parent_author_signature);
1368
1369                         $key = $msg["key"];
1370
1371                         if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1372                                 logger("owner verification failed.");
1373                                 return false;
1374                         }
1375                 }
1376
1377                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1378                         dbesc($message_uri)
1379                 );
1380                 if (dbm::is_result($r)) {
1381                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1382                         return false;
1383                 }
1384
1385                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1386                         VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1387                         intval($importer["uid"]),
1388                         dbesc($msg_guid),
1389                         intval($conversation["id"]),
1390                         dbesc($person["name"]),
1391                         dbesc($person["photo"]),
1392                         dbesc($person["url"]),
1393                         intval($contact["id"]),
1394                         dbesc($subject),
1395                         dbesc($body),
1396                         0,
1397                         0,
1398                         dbesc($message_uri),
1399                         dbesc($author.":".$guid),
1400                         dbesc($msg_created_at)
1401                 );
1402
1403                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1404                         dbesc(datetime_convert()),
1405                         intval($conversation["id"])
1406                 );
1407
1408                 notification(array(
1409                         "type" => NOTIFY_MAIL,
1410                         "notify_flags" => $importer["notify-flags"],
1411                         "language" => $importer["language"],
1412                         "to_name" => $importer["username"],
1413                         "to_email" => $importer["email"],
1414                         "uid" =>$importer["uid"],
1415                         "item" => array("subject" => $subject, "body" => $body),
1416                         "source_name" => $person["name"],
1417                         "source_link" => $person["url"],
1418                         "source_photo" => $person["thumb"],
1419                         "verb" => ACTIVITY_POST,
1420                         "otype" => "mail"
1421                 ));
1422                 return true;
1423         }
1424
1425         /**
1426          * @brief Processes new private messages (answers to private messages are processed elsewhere)
1427          *
1428          * @param array $importer Array of the importer user
1429          * @param array $msg Array of the processed message, author handle and key
1430          * @param object $data The message object
1431          *
1432          * @return bool Success
1433          */
1434         private static function receive_conversation($importer, $msg, $data) {
1435                 $guid = notags(unxmlify($data->guid));
1436                 $subject = notags(unxmlify($data->subject));
1437                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1438                 $author = notags(unxmlify($data->author));
1439                 $participants = notags(unxmlify($data->participants));
1440
1441                 $messages = $data->message;
1442
1443                 if (!count($messages)) {
1444                         logger("empty conversation");
1445                         return false;
1446                 }
1447
1448                 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1449                 if (!$contact)
1450                         return false;
1451
1452                 $conversation = null;
1453
1454                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1455                         intval($importer["uid"]),
1456                         dbesc($guid)
1457                 );
1458                 if($c)
1459                         $conversation = $c[0];
1460                 else {
1461                         $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1462                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1463                                 intval($importer["uid"]),
1464                                 dbesc($guid),
1465                                 dbesc($author),
1466                                 dbesc($created_at),
1467                                 dbesc(datetime_convert()),
1468                                 dbesc($subject),
1469                                 dbesc($participants)
1470                         );
1471                         if($r)
1472                                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1473                                         intval($importer["uid"]),
1474                                         dbesc($guid)
1475                                 );
1476
1477                         if($c)
1478                                 $conversation = $c[0];
1479                 }
1480                 if (!$conversation) {
1481                         logger("unable to create conversation.");
1482                         return;
1483                 }
1484
1485                 foreach($messages as $mesg)
1486                         self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1487
1488                 return true;
1489         }
1490
1491         /**
1492          * @brief Creates the body for a "like" message
1493          *
1494          * @param array $contact The contact that send us the "like"
1495          * @param array $parent_item The item array of the parent item
1496          * @param string $guid message guid
1497          *
1498          * @return string the body
1499          */
1500         private static function construct_like_body($contact, $parent_item, $guid) {
1501                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1502
1503                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1504                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1505                 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1506
1507                 return sprintf($bodyverb, $ulink, $alink, $plink);
1508         }
1509
1510         /**
1511          * @brief Creates a XML object for a "like"
1512          *
1513          * @param array $importer Array of the importer user
1514          * @param array $parent_item The item array of the parent item
1515          *
1516          * @return string The XML
1517          */
1518         private static function construct_like_object($importer, $parent_item) {
1519                 $objtype = ACTIVITY_OBJ_NOTE;
1520                 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1521                 $parent_body = $parent_item["body"];
1522
1523                 $xmldata = array("object" => array("type" => $objtype,
1524                                                 "local" => "1",
1525                                                 "id" => $parent_item["uri"],
1526                                                 "link" => $link,
1527                                                 "title" => "",
1528                                                 "content" => $parent_body));
1529
1530                 return xml::from_array($xmldata, $xml, true);
1531         }
1532
1533         /**
1534          * @brief Processes "like" messages
1535          *
1536          * @param array $importer Array of the importer user
1537          * @param string $sender The sender of the message
1538          * @param object $data The message object
1539          *
1540          * @return int The message id of the generated like or "false" if there was an error
1541          */
1542         private static function receive_like($importer, $sender, $data) {
1543                 $positive = notags(unxmlify($data->positive));
1544                 $guid = notags(unxmlify($data->guid));
1545                 $parent_type = notags(unxmlify($data->parent_type));
1546                 $parent_guid = notags(unxmlify($data->parent_guid));
1547                 $author = notags(unxmlify($data->author));
1548
1549                 // likes on comments aren't supported by Diaspora - only on posts
1550                 // But maybe this will be supported in the future, so we will accept it.
1551                 if (!in_array($parent_type, array("Post", "Comment")))
1552                         return false;
1553
1554                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1555                 if (!$contact)
1556                         return false;
1557
1558                 $message_id = self::message_exists($importer["uid"], $guid);
1559                 if ($message_id)
1560                         return $message_id;
1561
1562                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1563                 if (!$parent_item)
1564                         return false;
1565
1566                 $person = self::person_by_handle($author);
1567                 if (!is_array($person)) {
1568                         logger("unable to find author details");
1569                         return false;
1570                 }
1571
1572                 // Fetch the contact id - if we know this contact
1573                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1574
1575                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1576                 // We would accept this anyhow.
1577                 if ($positive == "true")
1578                         $verb = ACTIVITY_LIKE;
1579                 else
1580                         $verb = ACTIVITY_DISLIKE;
1581
1582                 $datarray = array();
1583
1584                 $datarray["uid"] = $importer["uid"];
1585                 $datarray["contact-id"] = $author_contact["cid"];
1586                 $datarray["network"]  = $author_contact["network"];
1587
1588                 $datarray["author-name"] = $person["name"];
1589                 $datarray["author-link"] = $person["url"];
1590                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1591
1592                 $datarray["owner-name"] = $contact["name"];
1593                 $datarray["owner-link"] = $contact["url"];
1594                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1595
1596                 $datarray["guid"] = $guid;
1597                 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1598
1599                 $datarray["type"] = "activity";
1600                 $datarray["verb"] = $verb;
1601                 $datarray["gravity"] = GRAVITY_LIKE;
1602                 $datarray["parent-uri"] = $parent_item["uri"];
1603
1604                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1605                 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1606
1607                 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1608
1609                 $message_id = item_store($datarray);
1610
1611                 if ($message_id)
1612                         logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1613
1614                 // If we are the origin of the parent we store the original data and notify our followers
1615                 if($message_id AND $parent_item["origin"]) {
1616
1617                         // Formerly we stored the signed text, the signature and the author in different fields.
1618                         // We now store the raw data so that we are more flexible.
1619                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1620                                 intval($message_id),
1621                                 dbesc(json_encode($data))
1622                         );
1623
1624                         // notify others
1625                         proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1626                 }
1627
1628                 return $message_id;
1629         }
1630
1631         /**
1632          * @brief Processes private messages
1633          *
1634          * @param array $importer Array of the importer user
1635          * @param object $data The message object
1636          *
1637          * @return bool Success?
1638          */
1639         private static function receive_message($importer, $data) {
1640                 $guid = notags(unxmlify($data->guid));
1641                 $parent_guid = notags(unxmlify($data->parent_guid));
1642                 $text = unxmlify($data->text);
1643                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1644                 $author = notags(unxmlify($data->author));
1645                 $conversation_guid = notags(unxmlify($data->conversation_guid));
1646
1647                 $contact = self::allowed_contact_by_handle($importer, $author, true);
1648                 if (!$contact) {
1649                         return false;
1650                 }
1651
1652                 $conversation = null;
1653
1654                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1655                         intval($importer["uid"]),
1656                         dbesc($conversation_guid)
1657                 );
1658                 if ($c) {
1659                         $conversation = $c[0];
1660                 } else {
1661                         logger("conversation not available.");
1662                         return false;
1663                 }
1664
1665                 $message_uri = $author.":".$guid;
1666
1667                 $person = self::person_by_handle($author);
1668                 if (!$person) {
1669                         logger("unable to find author details");
1670                         return false;
1671                 }
1672
1673                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1674                         dbesc($message_uri),
1675                         intval($importer["uid"])
1676                 );
1677                 if (dbm::is_result($r)) {
1678                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1679                         return false;
1680                 }
1681
1682                 $body = diaspora2bb($text);
1683
1684                 $body = self::replace_people_guid($body, $person["url"]);
1685
1686                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1687                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1688                         intval($importer["uid"]),
1689                         dbesc($guid),
1690                         intval($conversation["id"]),
1691                         dbesc($person["name"]),
1692                         dbesc($person["photo"]),
1693                         dbesc($person["url"]),
1694                         intval($contact["id"]),
1695                         dbesc($conversation["subject"]),
1696                         dbesc($body),
1697                         0,
1698                         1,
1699                         dbesc($message_uri),
1700                         dbesc($author.":".$parent_guid),
1701                         dbesc($created_at)
1702                 );
1703
1704                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1705                         dbesc(datetime_convert()),
1706                         intval($conversation["id"])
1707                 );
1708
1709                 return true;
1710         }
1711
1712         /**
1713          * @brief Processes participations - unsupported by now
1714          *
1715          * @param array $importer Array of the importer user
1716          * @param object $data The message object
1717          *
1718          * @return bool always true
1719          */
1720         private static function receive_participation($importer, $data) {
1721                 // I'm not sure if we can fully support this message type
1722                 return true;
1723         }
1724
1725         /**
1726          * @brief Processes photos - unneeded
1727          *
1728          * @param array $importer Array of the importer user
1729          * @param object $data The message object
1730          *
1731          * @return bool always true
1732          */
1733         private static function receive_photo($importer, $data) {
1734                 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1735                 return true;
1736         }
1737
1738         /**
1739          * @brief Processes poll participations - unssupported
1740          *
1741          * @param array $importer Array of the importer user
1742          * @param object $data The message object
1743          *
1744          * @return bool always true
1745          */
1746         private static function receive_poll_participation($importer, $data) {
1747                 // We don't support polls by now
1748                 return true;
1749         }
1750
1751         /**
1752          * @brief Processes incoming profile updates
1753          *
1754          * @param array $importer Array of the importer user
1755          * @param object $data The message object
1756          *
1757          * @return bool Success
1758          */
1759         private static function receive_profile($importer, $data) {
1760                 $author = strtolower(notags(unxmlify($data->author)));
1761
1762                 $contact = self::contact_by_handle($importer["uid"], $author);
1763                 if (!$contact)
1764                         return false;
1765
1766                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1767                 $image_url = unxmlify($data->image_url);
1768                 $birthday = unxmlify($data->birthday);
1769                 $location = diaspora2bb(unxmlify($data->location));
1770                 $about = diaspora2bb(unxmlify($data->bio));
1771                 $gender = unxmlify($data->gender);
1772                 $searchable = (unxmlify($data->searchable) == "true");
1773                 $nsfw = (unxmlify($data->nsfw) == "true");
1774                 $tags = unxmlify($data->tag_string);
1775
1776                 $tags = explode("#", $tags);
1777
1778                 $keywords = array();
1779                 foreach ($tags as $tag) {
1780                         $tag = trim(strtolower($tag));
1781                         if ($tag != "")
1782                                 $keywords[] = $tag;
1783                 }
1784
1785                 $keywords = implode(", ", $keywords);
1786
1787                 $handle_parts = explode("@", $author);
1788                 $nick = $handle_parts[0];
1789
1790                 if($name === "")
1791                         $name = $handle_parts[0];
1792
1793                 if( preg_match("|^https?://|", $image_url) === 0)
1794                         $image_url = "http://".$handle_parts[1].$image_url;
1795
1796                 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1797
1798                 // Generic birthday. We don't know the timezone. The year is irrelevant.
1799
1800                 $birthday = str_replace("1000", "1901", $birthday);
1801
1802                 if ($birthday != "")
1803                         $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1804
1805                 // this is to prevent multiple birthday notifications in a single year
1806                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1807
1808                 if(substr($birthday,5) === substr($contact["bd"],5))
1809                         $birthday = $contact["bd"];
1810
1811                 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1812                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1813                         dbesc($name),
1814                         dbesc($nick),
1815                         dbesc($author),
1816                         dbesc(datetime_convert()),
1817                         dbesc($birthday),
1818                         dbesc($location),
1819                         dbesc($about),
1820                         dbesc($keywords),
1821                         dbesc($gender),
1822                         intval($contact["id"]),
1823                         intval($importer["uid"])
1824                 );
1825
1826                 if ($searchable) {
1827                         poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1828                                 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1829                 }
1830
1831                 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1832                                         "photo" => $image_url, "name" => $name, "location" => $location,
1833                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
1834                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1835                                         "hide" => !$searchable, "nsfw" => $nsfw);
1836
1837                 update_gcontact($gcontact);
1838
1839                 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1840
1841                 return true;
1842         }
1843
1844         /**
1845          * @brief Processes incoming friend requests
1846          *
1847          * @param array $importer Array of the importer user
1848          * @param array $contact The contact that send the request
1849          */
1850         private static function receive_request_make_friend($importer, $contact) {
1851
1852                 $a = get_app();
1853
1854                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1855                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1856                                 intval(CONTACT_IS_FRIEND),
1857                                 intval($contact["id"]),
1858                                 intval($importer["uid"])
1859                         );
1860                 }
1861                 // send notification
1862
1863                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1864                         intval($importer["uid"])
1865                 );
1866
1867                 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1868
1869                         $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1870                                 intval($importer["uid"])
1871                         );
1872
1873                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1874
1875                         if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1876
1877                                 $arr = array();
1878                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1879                                 $arr["uid"] = $importer["uid"];
1880                                 $arr["contact-id"] = $self[0]["id"];
1881                                 $arr["wall"] = 1;
1882                                 $arr["type"] = 'wall';
1883                                 $arr["gravity"] = 0;
1884                                 $arr["origin"] = 1;
1885                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1886                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1887                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1888                                 $arr["verb"] = ACTIVITY_FRIEND;
1889                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1890
1891                                 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1892                                 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1893                                 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1894                                 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1895
1896                                 $arr["object"] = self::construct_new_friend_object($contact);
1897
1898                                 $arr["last-child"] = 1;
1899
1900                                 $arr["allow_cid"] = $user[0]["allow_cid"];
1901                                 $arr["allow_gid"] = $user[0]["allow_gid"];
1902                                 $arr["deny_cid"]  = $user[0]["deny_cid"];
1903                                 $arr["deny_gid"]  = $user[0]["deny_gid"];
1904
1905                                 $i = item_store($arr);
1906                                 if($i)
1907                                         proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
1908                         }
1909                 }
1910         }
1911
1912         /**
1913          * @brief Creates a XML object for a "new friend" message
1914          *
1915          * @param array $contact Array of the contact
1916          *
1917          * @return string The XML
1918          */
1919         private static function construct_new_friend_object($contact) {
1920                 $objtype = ACTIVITY_OBJ_PERSON;
1921                 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
1922                         '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
1923
1924                 $xmldata = array("object" => array("type" => $objtype,
1925                                                 "title" => $contact["name"],
1926                                                 "id" => $contact["url"]."/".$contact["name"],
1927                                                 "link" => $link));
1928
1929                 return xml::from_array($xmldata, $xml, true);
1930         }
1931
1932         /**
1933          * @brief Processes incoming sharing notification
1934          *
1935          * @param array $importer Array of the importer user
1936          * @param object $data The message object
1937          *
1938          * @return bool Success
1939          */
1940         private static function receive_contact_request($importer, $data) {
1941                 $author = unxmlify($data->author);
1942                 $recipient = unxmlify($data->recipient);
1943
1944                 if (!$author || !$recipient) {
1945                         return false;
1946                 }
1947
1948                 // the current protocol version doesn't know these fields
1949                 // That means that we will assume their existance
1950                 if (isset($data->following)) {
1951                         $following = (unxmlify($data->following) == "true");
1952                 } else {
1953                         $following = true;
1954                 }
1955
1956                 if (isset($data->sharing)) {
1957                         $sharing = (unxmlify($data->sharing) == "true");
1958                 } else {
1959                         $sharing = true;
1960                 }
1961
1962                 $contact = self::contact_by_handle($importer["uid"],$author);
1963
1964                 // perhaps we were already sharing with this person. Now they're sharing with us.
1965                 // That makes us friends.
1966                 if ($contact) {
1967                         if ($following AND $sharing) {
1968                                 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
1969                                 self::receive_request_make_friend($importer, $contact);
1970
1971                                 // refetch the contact array
1972                                 $contact = self::contact_by_handle($importer["uid"],$author);
1973
1974                                 // If we are now friends, we are sending a share message.
1975                                 // Normally we needn't to do so, but the first message could have been vanished.
1976                                 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
1977                                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1978                                         if ($u) {
1979                                                 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
1980                                                 $ret = self::send_share($u[0], $contact);
1981                                         }
1982                                 }
1983                                 return true;
1984                         } else { /// @todo Handle all possible variations of adding and retracting of permissions
1985                                 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
1986                                 return false;
1987                         }
1988                 }
1989
1990                 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
1991                         logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
1992                         return false;
1993                 } elseif (!$following AND !$sharing) {
1994                         logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
1995                         return false;
1996                 } elseif (!$following AND $sharing) {
1997                         logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
1998                 } elseif ($following AND $sharing) {
1999                         logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2000                 } elseif ($following AND !$sharing) {
2001                         logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2002                 }
2003
2004                 $ret = self::person_by_handle($author);
2005
2006                 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2007                         logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2008                         return false;
2009                 }
2010
2011                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2012
2013                 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2014                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2015                         intval($importer["uid"]),
2016                         dbesc($ret["network"]),
2017                         dbesc($ret["addr"]),
2018                         datetime_convert(),
2019                         dbesc($ret["url"]),
2020                         dbesc(normalise_link($ret["url"])),
2021                         dbesc($batch),
2022                         dbesc($ret["name"]),
2023                         dbesc($ret["nick"]),
2024                         dbesc($ret["photo"]),
2025                         dbesc($ret["pubkey"]),
2026                         dbesc($ret["notify"]),
2027                         dbesc($ret["poll"]),
2028                         1,
2029                         2
2030                 );
2031
2032                 // find the contact record we just created
2033
2034                 $contact_record = self::contact_by_handle($importer["uid"],$author);
2035
2036                 if (!$contact_record) {
2037                         logger("unable to locate newly created contact record.");
2038                         return;
2039                 }
2040
2041                 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2042
2043                 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2044
2045                 if(intval($def_gid))
2046                         group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2047
2048                 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2049
2050                 if($importer["page-flags"] == PAGE_NORMAL) {
2051
2052                         logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2053
2054                         $hash = random_string().(string)time();   // Generate a confirm_key
2055
2056                         $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2057                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2058                                 intval($importer["uid"]),
2059                                 intval($contact_record["id"]),
2060                                 0,
2061                                 0,
2062                                 dbesc(t("Sharing notification from Diaspora network")),
2063                                 dbesc($hash),
2064                                 dbesc(datetime_convert())
2065                         );
2066                 } else {
2067
2068                         // automatic friend approval
2069
2070                         logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2071
2072                         update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2073
2074                         // technically they are sharing with us (CONTACT_IS_SHARING),
2075                         // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2076                         // we are going to change the relationship and make them a follower.
2077
2078                         if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2079                                 $new_relation = CONTACT_IS_FRIEND;
2080                         elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2081                                 $new_relation = CONTACT_IS_SHARING;
2082                         else
2083                                 $new_relation = CONTACT_IS_FOLLOWER;
2084
2085                         $r = q("UPDATE `contact` SET `rel` = %d,
2086                                 `name-date` = '%s',
2087                                 `uri-date` = '%s',
2088                                 `blocked` = 0,
2089                                 `pending` = 0,
2090                                 `writable` = 1
2091                                 WHERE `id` = %d
2092                                 ",
2093                                 intval($new_relation),
2094                                 dbesc(datetime_convert()),
2095                                 dbesc(datetime_convert()),
2096                                 intval($contact_record["id"])
2097                         );
2098
2099                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2100                         if($u) {
2101                                 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2102                                 $ret = self::send_share($u[0], $contact_record);
2103
2104                                 // Send the profile data, maybe it weren't transmitted before
2105                                 self::send_profile($importer["uid"], array($contact_record));
2106                         }
2107                 }
2108
2109                 return true;
2110         }
2111
2112         /**
2113          * @brief Fetches a message with a given guid
2114          *
2115          * @param string $guid message guid
2116          * @param string $orig_author handle of the original post
2117          * @param string $author handle of the sharer
2118          *
2119          * @return array The fetched item
2120          */
2121         private static function original_item($guid, $orig_author, $author) {
2122
2123                 // Do we already have this item?
2124                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2125                                 `author-name`, `author-link`, `author-avatar`
2126                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2127                         dbesc($guid));
2128
2129                 if (dbm::is_result($r)) {
2130                         logger("reshared message ".$guid." already exists on system.");
2131
2132                         // Maybe it is already a reshared item?
2133                         // Then refetch the content, if it is a reshare from a reshare.
2134                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2135                         if (self::is_reshare($r[0]["body"], true)) {
2136                                 $r = array();
2137                         } elseif (self::is_reshare($r[0]["body"], false)) {
2138                                 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2139
2140                                 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2141
2142                                 // Add OEmbed and other information to the body
2143                                 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2144
2145                                 return $r[0];
2146                         } else {
2147                                 return $r[0];
2148                         }
2149                 }
2150
2151                 if (!dbm::is_result($r)) {
2152                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2153                         logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2154                         $item_id = self::store_by_guid($guid, $server);
2155
2156                         if (!$item_id) {
2157                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2158                                 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2159                                 $item_id = self::store_by_guid($guid, $server);
2160                         }
2161
2162                         if ($item_id) {
2163                                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2164                                                 `author-name`, `author-link`, `author-avatar`
2165                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2166                                         intval($item_id));
2167
2168                                 if (dbm::is_result($r)) {
2169                                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2170                                         if (self::is_reshare($r[0]["body"], false)) {
2171                                                 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2172                                                 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2173                                         }
2174
2175                                         return $r[0];
2176                                 }
2177
2178                         }
2179                 }
2180                 return false;
2181         }
2182
2183         /**
2184          * @brief Processes a reshare message
2185          *
2186          * @param array $importer Array of the importer user
2187          * @param object $data The message object
2188          * @param string $xml The original XML of the message
2189          *
2190          * @return int the message id
2191          */
2192         private static function receive_reshare($importer, $data, $xml) {
2193                 $root_author = notags(unxmlify($data->root_author));
2194                 $root_guid = notags(unxmlify($data->root_guid));
2195                 $guid = notags(unxmlify($data->guid));
2196                 $author = notags(unxmlify($data->author));
2197                 $public = notags(unxmlify($data->public));
2198                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2199
2200                 $contact = self::allowed_contact_by_handle($importer, $author, false);
2201                 if (!$contact) {
2202                         return false;
2203                 }
2204
2205                 $message_id = self::message_exists($importer["uid"], $guid);
2206                 if ($message_id) {
2207                         return $message_id;
2208                 }
2209
2210                 $original_item = self::original_item($root_guid, $root_author, $author);
2211                 if (!$original_item) {
2212                         return false;
2213                 }
2214
2215                 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2216
2217                 $datarray = array();
2218
2219                 $datarray["uid"] = $importer["uid"];
2220                 $datarray["contact-id"] = $contact["id"];
2221                 $datarray["network"]  = NETWORK_DIASPORA;
2222
2223                 $datarray["author-name"] = $contact["name"];
2224                 $datarray["author-link"] = $contact["url"];
2225                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2226
2227                 $datarray["owner-name"] = $datarray["author-name"];
2228                 $datarray["owner-link"] = $datarray["author-link"];
2229                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2230
2231                 $datarray["guid"] = $guid;
2232                 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2233
2234                 $datarray["verb"] = ACTIVITY_POST;
2235                 $datarray["gravity"] = GRAVITY_PARENT;
2236
2237                 $datarray["object"] = $xml;
2238
2239                 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2240                                         $original_item["guid"], $original_item["created"], $orig_url);
2241                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2242
2243                 $datarray["tag"] = $original_item["tag"];
2244                 $datarray["app"]  = $original_item["app"];
2245
2246                 $datarray["plink"] = self::plink($author, $guid);
2247                 $datarray["private"] = (($public == "false") ? 1 : 0);
2248                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2249
2250                 $datarray["object-type"] = $original_item["object-type"];
2251
2252                 self::fetch_guid($datarray);
2253                 $message_id = item_store($datarray);
2254
2255                 if ($message_id) {
2256                         logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2257                 }
2258
2259                 return $message_id;
2260         }
2261
2262         /**
2263          * @brief Processes retractions
2264          *
2265          * @param array $importer Array of the importer user
2266          * @param array $contact The contact of the item owner
2267          * @param object $data The message object
2268          *
2269          * @return bool success
2270          */
2271         private static function item_retraction($importer, $contact, $data) {
2272                 $target_type = notags(unxmlify($data->target_type));
2273                 $target_guid = notags(unxmlify($data->target_guid));
2274                 $author = notags(unxmlify($data->author));
2275
2276                 $person = self::person_by_handle($author);
2277                 if (!is_array($person)) {
2278                         logger("unable to find author detail for ".$author);
2279                         return false;
2280                 }
2281
2282                 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2283                         dbesc($target_guid),
2284                         intval($importer["uid"])
2285                 );
2286                 if (!$r) {
2287                         return false;
2288                 }
2289
2290                 // Check if the sender is the thread owner
2291                 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2292                         intval($r[0]["parent"]));
2293
2294                 // Only delete it if the parent author really fits
2295                 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2296                         logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2297                         return false;
2298                 }
2299
2300                 // 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
2301                 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2302                         dbesc(datetime_convert()),
2303                         dbesc(datetime_convert()),
2304                         intval($r[0]["id"])
2305                 );
2306                 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2307
2308                 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2309
2310                 // Now check if the retraction needs to be relayed by us
2311                 if ($p[0]["origin"]) {
2312                         // notify others
2313                         proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2314                 }
2315
2316                 return true;
2317         }
2318
2319         /**
2320          * @brief Receives retraction messages
2321          *
2322          * @param array $importer Array of the importer user
2323          * @param string $sender The sender of the message
2324          * @param object $data The message object
2325          *
2326          * @return bool Success
2327          */
2328         private static function receive_retraction($importer, $sender, $data) {
2329                 $target_type = notags(unxmlify($data->target_type));
2330
2331                 $contact = self::contact_by_handle($importer["uid"], $sender);
2332                 if (!$contact) {
2333                         logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2334                         return false;
2335                 }
2336
2337                 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2338
2339                 switch ($target_type) {
2340                         case "Comment":
2341                         case "Like":
2342                         case "Post": // "Post" will be supported in a future version
2343                         case "Reshare":
2344                         case "StatusMessage":
2345                                 return self::item_retraction($importer, $contact, $data);;
2346
2347                         case "Contact":
2348                         case "Person":
2349                                 /// @todo What should we do with an "unshare"?
2350                                 // Removing the contact isn't correct since we still can read the public items
2351                                 contact_remove($contact["id"]);
2352                                 return true;
2353
2354                         default:
2355                                 logger("Unknown target type ".$target_type);
2356                                 return false;
2357                 }
2358                 return true;
2359         }
2360
2361         /**
2362          * @brief Receives status messages
2363          *
2364          * @param array $importer Array of the importer user
2365          * @param object $data The message object
2366          * @param string $xml The original XML of the message
2367          *
2368          * @return int The message id of the newly created item
2369          */
2370         private static function receive_status_message($importer, $data, $xml) {
2371                 $raw_message = unxmlify($data->raw_message);
2372                 $guid = notags(unxmlify($data->guid));
2373                 $author = notags(unxmlify($data->author));
2374                 $public = notags(unxmlify($data->public));
2375                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2376                 $provider_display_name = notags(unxmlify($data->provider_display_name));
2377
2378                 /// @todo enable support for polls
2379                 //if ($data->poll) {
2380                 //      foreach ($data->poll AS $poll)
2381                 //              print_r($poll);
2382                 //      die("poll!\n");
2383                 //}
2384                 $contact = self::allowed_contact_by_handle($importer, $author, false);
2385                 if (!$contact) {
2386                         return false;
2387                 }
2388
2389                 $message_id = self::message_exists($importer["uid"], $guid);
2390                 if ($message_id) {
2391                         return $message_id;
2392                 }
2393
2394                 $address = array();
2395                 if ($data->location) {
2396                         foreach ($data->location->children() AS $fieldname => $data) {
2397                                 $address[$fieldname] = notags(unxmlify($data));
2398                         }
2399                 }
2400
2401                 $body = diaspora2bb($raw_message);
2402
2403                 $datarray = array();
2404
2405                 // Attach embedded pictures to the body
2406                 if ($data->photo) {
2407                         foreach ($data->photo AS $photo) {
2408                                 $body = "[img]".unxmlify($photo->remote_photo_path).
2409                                         unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2410                         }
2411
2412                         $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2413                 } else {
2414                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2415
2416                         // Add OEmbed and other information to the body
2417                         if (!self::is_redmatrix($contact["url"])) {
2418                                 $body = add_page_info_to_body($body, false, true);
2419                         }
2420                 }
2421
2422                 $datarray["uid"] = $importer["uid"];
2423                 $datarray["contact-id"] = $contact["id"];
2424                 $datarray["network"] = NETWORK_DIASPORA;
2425
2426                 $datarray["author-name"] = $contact["name"];
2427                 $datarray["author-link"] = $contact["url"];
2428                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2429
2430                 $datarray["owner-name"] = $datarray["author-name"];
2431                 $datarray["owner-link"] = $datarray["author-link"];
2432                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2433
2434                 $datarray["guid"] = $guid;
2435                 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2436
2437                 $datarray["verb"] = ACTIVITY_POST;
2438                 $datarray["gravity"] = GRAVITY_PARENT;
2439
2440                 $datarray["object"] = $xml;
2441
2442                 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2443
2444                 if ($provider_display_name != "") {
2445                         $datarray["app"] = $provider_display_name;
2446                 }
2447
2448                 $datarray["plink"] = self::plink($author, $guid);
2449                 $datarray["private"] = (($public == "false") ? 1 : 0);
2450                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2451
2452                 if (isset($address["address"])) {
2453                         $datarray["location"] = $address["address"];
2454                 }
2455
2456                 if (isset($address["lat"]) AND isset($address["lng"])) {
2457                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
2458                 }
2459
2460                 self::fetch_guid($datarray);
2461                 $message_id = item_store($datarray);
2462
2463                 if ($message_id) {
2464                         logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2465                 }
2466
2467                 return $message_id;
2468         }
2469
2470         /* ************************************************************************************** *
2471          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2472          * ************************************************************************************** */
2473
2474         /**
2475          * @brief returnes the handle of a contact
2476          *
2477          * @param array $me contact array
2478          *
2479          * @return string the handle in the format user@domain.tld
2480          */
2481         private static function my_handle($contact) {
2482                 if ($contact["addr"] != "") {
2483                         return $contact["addr"];
2484                 }
2485
2486                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2487                 // So - just in case - we build the the address here.
2488                 if ($contact["nickname"] != "") {
2489                         $nick = $contact["nickname"];
2490                 } else {
2491                         $nick = $contact["nick"];
2492                 }
2493
2494                 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2495         }
2496
2497         /**
2498          * @brief Creates the envelope for the "fetch" endpoint
2499          *
2500          * @param string $msg The message that is to be transmitted
2501          * @param array $user The record of the sender
2502          *
2503          * @return string The envelope
2504          */
2505
2506         public static function build_magic_envelope($msg, $user) {
2507
2508                 $b64url_data = base64url_encode($msg);
2509                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2510
2511                 $key_id = base64url_encode(self::my_handle($user));
2512                 $type = "application/xml";
2513                 $encoding = "base64url";
2514                 $alg = "RSA-SHA256";
2515                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2516                 $signature = rsa_sign($signable_data, $user["prvkey"]);
2517                 $sig = base64url_encode($signature);
2518
2519                 $xmldata = array("me:env" => array("me:data" => $data,
2520                                                         "@attributes" => array("type" => $type),
2521                                                         "me:encoding" => $encoding,
2522                                                         "me:alg" => $alg,
2523                                                         "me:sig" => $sig,
2524                                                         "@attributes2" => array("key_id" => $key_id)));
2525
2526                 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2527
2528                 return xml::from_array($xmldata, $xml, false, $namespaces);
2529         }
2530
2531         /**
2532          * @brief Creates the envelope for a public message
2533          *
2534          * @param string $msg The message that is to be transmitted
2535          * @param array $user The record of the sender
2536          * @param array $contact Target of the communication
2537          * @param string $prvkey The private key of the sender
2538          * @param string $pubkey The public key of the receiver
2539          *
2540          * @return string The envelope
2541          */
2542         private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2543
2544                 logger("Message: ".$msg, LOGGER_DATA);
2545
2546                 $handle = self::my_handle($user);
2547
2548                 $b64url_data = base64url_encode($msg);
2549
2550                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2551
2552                 $type = "application/xml";
2553                 $encoding = "base64url";
2554                 $alg = "RSA-SHA256";
2555
2556                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2557
2558                 $signature = rsa_sign($signable_data,$prvkey);
2559                 $sig = base64url_encode($signature);
2560
2561                 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2562                                                         "me:env" => array("me:encoding" => $encoding,
2563                                                         "me:alg" => $alg,
2564                                                         "me:data" => $data,
2565                                                         "@attributes" => array("type" => $type),
2566                                                         "me:sig" => $sig)));
2567
2568                 $namespaces = array("" => "https://joindiaspora.com/protocol",
2569                                 "me" => "http://salmon-protocol.org/ns/magic-env");
2570
2571                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2572
2573                 logger("magic_env: ".$magic_env, LOGGER_DATA);
2574                 return $magic_env;
2575         }
2576
2577         /**
2578          * @brief Creates the envelope for a private message
2579          *
2580          * @param string $msg The message that is to be transmitted
2581          * @param array $user The record of the sender
2582          * @param array $contact Target of the communication
2583          * @param string $prvkey The private key of the sender
2584          * @param string $pubkey The public key of the receiver
2585          *
2586          * @return string The envelope
2587          */
2588         private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2589
2590                 logger("Message: ".$msg, LOGGER_DATA);
2591
2592                 // without a public key nothing will work
2593
2594                 if (!$pubkey) {
2595                         logger("pubkey missing: contact id: ".$contact["id"]);
2596                         return false;
2597                 }
2598
2599                 $inner_aes_key = random_string(32);
2600                 $b_inner_aes_key = base64_encode($inner_aes_key);
2601                 $inner_iv = random_string(16);
2602                 $b_inner_iv = base64_encode($inner_iv);
2603
2604                 $outer_aes_key = random_string(32);
2605                 $b_outer_aes_key = base64_encode($outer_aes_key);
2606                 $outer_iv = random_string(16);
2607                 $b_outer_iv = base64_encode($outer_iv);
2608
2609                 $handle = self::my_handle($user);
2610
2611                 $padded_data = pkcs5_pad($msg,16);
2612                 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2613
2614                 $b64_data = base64_encode($inner_encrypted);
2615
2616
2617                 $b64url_data = base64url_encode($b64_data);
2618                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2619
2620                 $type = "application/xml";
2621                 $encoding = "base64url";
2622                 $alg = "RSA-SHA256";
2623
2624                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2625
2626                 $signature = rsa_sign($signable_data,$prvkey);
2627                 $sig = base64url_encode($signature);
2628
2629                 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2630                                                         "aes_key" => $b_inner_aes_key,
2631                                                         "author_id" => $handle));
2632
2633                 $decrypted_header = xml::from_array($xmldata, $xml, true);
2634                 $decrypted_header = pkcs5_pad($decrypted_header,16);
2635
2636                 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2637
2638                 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2639
2640                 $encrypted_outer_key_bundle = "";
2641                 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2642
2643                 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2644
2645                 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2646
2647                 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2648                                                                 "ciphertext" => base64_encode($ciphertext)));
2649                 $cipher_json = base64_encode($encrypted_header_json_object);
2650
2651                 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2652                                                 "me:env" => array("me:encoding" => $encoding,
2653                                                                 "me:alg" => $alg,
2654                                                                 "me:data" => $data,
2655                                                                 "@attributes" => array("type" => $type),
2656                                                                 "me:sig" => $sig)));
2657
2658                 $namespaces = array("" => "https://joindiaspora.com/protocol",
2659                                 "me" => "http://salmon-protocol.org/ns/magic-env");
2660
2661                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2662
2663                 logger("magic_env: ".$magic_env, LOGGER_DATA);
2664                 return $magic_env;
2665         }
2666
2667         /**
2668          * @brief Create the envelope for a message
2669          *
2670          * @param string $msg The message that is to be transmitted
2671          * @param array $user The record of the sender
2672          * @param array $contact Target of the communication
2673          * @param string $prvkey The private key of the sender
2674          * @param string $pubkey The public key of the receiver
2675          * @param bool $public Is the message public?
2676          *
2677          * @return string The message that will be transmitted to other servers
2678          */
2679         private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2680
2681                 if ($public)
2682                         $magic_env =  self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2683                 else
2684                         $magic_env =  self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2685
2686                 // The data that will be transmitted is double encoded via "urlencode", strange ...
2687                 $slap = "xml=".urlencode(urlencode($magic_env));
2688                 return $slap;
2689         }
2690
2691         /**
2692          * @brief Creates a signature for a message
2693          *
2694          * @param array $owner the array of the owner of the message
2695          * @param array $message The message that is to be signed
2696          *
2697          * @return string The signature
2698          */
2699         private static function signature($owner, $message) {
2700                 $sigmsg = $message;
2701                 unset($sigmsg["author_signature"]);
2702                 unset($sigmsg["parent_author_signature"]);
2703
2704                 $signed_text = implode(";", $sigmsg);
2705
2706                 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2707         }
2708
2709         /**
2710          * @brief Transmit a message to a target server
2711          *
2712          * @param array $owner the array of the item owner
2713          * @param array $contact Target of the communication
2714          * @param string $slap The message that is to be transmitted
2715          * @param bool $public_batch Is it a public post?
2716          * @param bool $queue_run Is the transmission called from the queue?
2717          * @param string $guid message guid
2718          *
2719          * @return int Result of the transmission
2720          */
2721         public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2722
2723                 $a = get_app();
2724
2725                 $enabled = intval(get_config("system", "diaspora_enabled"));
2726                 if(!$enabled)
2727                         return 200;
2728
2729                 $logid = random_string(4);
2730                 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2731                 if (!$dest_url) {
2732                         logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2733                         return 0;
2734                 }
2735
2736                 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2737
2738                 if (!$queue_run && was_recently_delayed($contact["id"])) {
2739                         $return_code = 0;
2740                 } else {
2741                         if (!intval(get_config("system", "diaspora_test"))) {
2742                                 post_url($dest_url."/", $slap);
2743                                 $return_code = $a->get_curl_code();
2744                         } else {
2745                                 logger("test_mode");
2746                                 return 200;
2747                         }
2748                 }
2749
2750                 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2751
2752                 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2753                         logger("queue message");
2754
2755                         $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2756                                 intval($contact["id"]),
2757                                 dbesc(NETWORK_DIASPORA),
2758                                 dbesc($slap),
2759                                 intval($public_batch)
2760                         );
2761                         if ($r) {
2762                                 logger("add_to_queue ignored - identical item already in queue");
2763                         } else {
2764                                 // queue message for redelivery
2765                                 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2766
2767                                 // The message could not be delivered. We mark the contact as "dead"
2768                                 mark_for_death($contact);
2769                         }
2770                 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2771                         // We successfully delivered a message, the contact is alive
2772                         unmark_for_death($contact);
2773                 }
2774
2775                 return(($return_code) ? $return_code : (-1));
2776         }
2777
2778
2779         /**
2780          * @brief Build the post xml
2781          *
2782          * @param string $type The message type
2783          * @param array $message The message data
2784          *
2785          * @return string The post XML
2786          */
2787         public static function build_post_xml($type, $message) {
2788
2789                 $data = array("XML" => array("post" => array($type => $message)));
2790                 return xml::from_array($data, $xml);
2791         }
2792
2793         /**
2794          * @brief Builds and transmit messages
2795          *
2796          * @param array $owner the array of the item owner
2797          * @param array $contact Target of the communication
2798          * @param string $type The message type
2799          * @param array $message The message data
2800          * @param bool $public_batch Is it a public post?
2801          * @param string $guid message guid
2802          * @param bool $spool Should the transmission be spooled or transmitted?
2803          *
2804          * @return int Result of the transmission
2805          */
2806         private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2807
2808                 $msg = self::build_post_xml($type, $message);
2809
2810                 logger('message: '.$msg, LOGGER_DATA);
2811                 logger('send guid '.$guid, LOGGER_DEBUG);
2812
2813                 // Fallback if the private key wasn't transmitted in the expected field
2814                 if ($owner['uprvkey'] == "")
2815                         $owner['uprvkey'] = $owner['prvkey'];
2816
2817                 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2818
2819                 if ($spool) {
2820                         add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2821                         return true;
2822                 } else
2823                         $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2824
2825                 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2826
2827                 return $return_code;
2828         }
2829
2830         /**
2831          * @brief Sends a "share" message
2832          *
2833          * @param array $owner the array of the item owner
2834          * @param array $contact Target of the communication
2835          *
2836          * @return int The result of the transmission
2837          */
2838         public static function send_share($owner,$contact) {
2839
2840                 $message = array("sender_handle" => self::my_handle($owner),
2841                                 "recipient_handle" => $contact["addr"]);
2842
2843                 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2844
2845                 return self::build_and_transmit($owner, $contact, "request", $message);
2846         }
2847
2848         /**
2849          * @brief sends an "unshare"
2850          *
2851          * @param array $owner the array of the item owner
2852          * @param array $contact Target of the communication
2853          *
2854          * @return int The result of the transmission
2855          */
2856         public static function send_unshare($owner,$contact) {
2857
2858                 $message = array("post_guid" => $owner["guid"],
2859                                 "diaspora_handle" => self::my_handle($owner),
2860                                 "type" => "Person");
2861
2862                 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2863
2864                 return self::build_and_transmit($owner, $contact, "retraction", $message);
2865         }
2866
2867         /**
2868          * @brief Checks a message body if it is a reshare
2869          *
2870          * @param string $body The message body that is to be check
2871          * @param bool $complete Should it be a complete check or a simple check?
2872          *
2873          * @return array|bool Reshare details or "false" if no reshare
2874          */
2875         public static function is_reshare($body, $complete = true) {
2876                 $body = trim($body);
2877
2878                 // Skip if it isn't a pure repeated messages
2879                 // Does it start with a share?
2880                 if ((strpos($body, "[share") > 0) AND $complete)
2881                         return(false);
2882
2883                 // Does it end with a share?
2884                 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2885                         return(false);
2886
2887                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2888                 // Skip if there is no shared message in there
2889                 if ($body == $attributes)
2890                         return(false);
2891
2892                 // If we don't do the complete check we quit here
2893                 if (!$complete)
2894                         return true;
2895
2896                 $guid = "";
2897                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2898                 if ($matches[1] != "")
2899                         $guid = $matches[1];
2900
2901                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2902                 if ($matches[1] != "")
2903                         $guid = $matches[1];
2904
2905                 if ($guid != "") {
2906                         $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2907                                 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2908                         if ($r) {
2909                                 $ret= array();
2910                                 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2911                                 $ret["root_guid"] = $guid;
2912                                 return($ret);
2913                         }
2914                 }
2915
2916                 $profile = "";
2917                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2918                 if ($matches[1] != "")
2919                         $profile = $matches[1];
2920
2921                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2922                 if ($matches[1] != "")
2923                         $profile = $matches[1];
2924
2925                 $ret= array();
2926
2927                 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2928                 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2929                         return(false);
2930
2931                 $link = "";
2932                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2933                 if ($matches[1] != "")
2934                         $link = $matches[1];
2935
2936                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2937                 if ($matches[1] != "")
2938                         $link = $matches[1];
2939
2940                 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2941                 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
2942                         return(false);
2943
2944                 return($ret);
2945         }
2946
2947         /**
2948          * @brief Create an event array
2949          *
2950          * @param integer $event_id The id of the event
2951          *
2952          * @return array with event data
2953          */
2954         private static function build_event($event_id) {
2955
2956                 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
2957                 if (!dbm::is_result($r)) {
2958                         return array();
2959                 }
2960
2961                 $event = $r[0];
2962
2963                 $eventdata = array();
2964
2965                 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
2966                 if (!dbm::is_result($r)) {
2967                         return array();
2968                 }
2969
2970                 $user = $r[0];
2971
2972                 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
2973                 if (!dbm::is_result($r)) {
2974                         return array();
2975                 }
2976
2977                 $owner = $r[0];
2978
2979                 $eventdata['author'] = self::my_handle($owner);
2980
2981                 if ($event['guid']) {
2982                         $eventdata['guid'] = $event['guid'];
2983                 }
2984
2985                 $mask = 'Y-m-d\TH:i:s\Z';
2986
2987                 /// @todo - establish "all day" events in Friendica
2988                 $eventdata["all_day"] = "false";
2989
2990                 if (!$event['adjust']) {
2991                         $eventdata['timezone'] = $user['timezone'];
2992
2993                         if ($eventdata['timezone'] == "") {
2994                                 $eventdata['timezone'] = 'UTC';
2995                         }
2996                 }
2997
2998                 if ($event['start']) {
2999                         $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3000                 }
3001                 if ($event['finish'] AND !$event['nofinish']) {
3002                         $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3003                 }
3004                 if ($event['summary']) {
3005                         $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3006                 }
3007                 if ($event['desc']) {
3008                         $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3009                 }
3010                 if ($event['location']) {
3011                         $location = array();
3012                         $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3013                         $location["lat"] = 0;
3014                         $location["lng"] = 0;
3015                         $eventdata['location'] = $location;
3016                 }
3017
3018                 return $eventdata;
3019         }
3020
3021         /**
3022          * @brief Create a post (status message or reshare)
3023          *
3024          * @param array $item The item that will be exported
3025          * @param array $owner the array of the item owner
3026          *
3027          * @return array
3028          * 'type' -> Message type ("status_message" or "reshare")
3029          * 'message' -> Array of XML elements of the status
3030          */
3031         public static function build_status($item, $owner) {
3032
3033                 $cachekey = "diaspora:build_status:".$item['guid'];
3034
3035                 $result = Cache::get($cachekey);
3036                 if (!is_null($result)) {
3037                         return $result;
3038                 }
3039
3040                 $myaddr = self::my_handle($owner);
3041
3042                 $public = (($item["private"]) ? "false" : "true");
3043
3044                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3045
3046                 // Detect a share element and do a reshare
3047                 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3048                         $message = array("root_diaspora_id" => $ret["root_handle"],
3049                                         "root_guid" => $ret["root_guid"],
3050                                         "guid" => $item["guid"],
3051                                         "diaspora_handle" => $myaddr,
3052                                         "public" => $public,
3053                                         "created_at" => $created,
3054                                         "provider_display_name" => $item["app"]);
3055
3056                         $type = "reshare";
3057                 } else {
3058                         $title = $item["title"];
3059                         $body = $item["body"];
3060
3061                         // convert to markdown
3062                         $body = html_entity_decode(bb2diaspora($body));
3063
3064                         // Adding the title
3065                         if(strlen($title))
3066                                 $body = "## ".html_entity_decode($title)."\n\n".$body;
3067
3068                         if ($item["attach"]) {
3069                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3070                                 if(cnt) {
3071                                         $body .= "\n".t("Attachments:")."\n";
3072                                         foreach($matches as $mtch)
3073                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3074                                 }
3075                         }
3076
3077                         $location = array();
3078
3079                         if ($item["location"] != "")
3080                                 $location["address"] = $item["location"];
3081
3082                         if ($item["coord"] != "") {
3083                                 $coord = explode(" ", $item["coord"]);
3084                                 $location["lat"] = $coord[0];
3085                                 $location["lng"] = $coord[1];
3086                         }
3087
3088                         $message = array("raw_message" => $body,
3089                                         "location" => $location,
3090                                         "guid" => $item["guid"],
3091                                         "diaspora_handle" => $myaddr,
3092                                         "public" => $public,
3093                                         "created_at" => $created,
3094                                         "provider_display_name" => $item["app"]);
3095
3096                         // Diaspora rejects messages when they contain a location without "lat" or "lng"
3097                         if (!isset($location["lat"]) OR !isset($location["lng"])) {
3098                                 unset($message["location"]);
3099                         }
3100
3101                         if ($item['event-id'] > 0) {
3102                                 $event = self::build_event($item['event-id']);
3103                                 if (count($event)) {
3104                                         $message['event'] = $event;
3105
3106                                         /// @todo Once Diaspora supports it, we will remove the body
3107                                         // $message['raw_message'] = '';
3108                                 }
3109                         }
3110
3111                         $type = "status_message";
3112                 }
3113
3114                 $msg = array("type" => $type, "message" => $message);
3115
3116                 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3117
3118                 return $msg;
3119         }
3120
3121         /**
3122          * @brief Sends a post
3123          *
3124          * @param array $item The item that will be exported
3125          * @param array $owner the array of the item owner
3126          * @param array $contact Target of the communication
3127          * @param bool $public_batch Is it a public post?
3128          *
3129          * @return int The result of the transmission
3130          */
3131         public static function send_status($item, $owner, $contact, $public_batch = false) {
3132
3133                 $status = self::build_status($item, $owner);
3134
3135                 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3136         }
3137
3138         /**
3139          * @brief Creates a "like" object
3140          *
3141          * @param array $item The item that will be exported
3142          * @param array $owner the array of the item owner
3143          *
3144          * @return array The data for a "like"
3145          */
3146         private static function construct_like($item, $owner) {
3147
3148                 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3149                         dbesc($item["thr-parent"]));
3150                 if (!dbm::is_result($p))
3151                         return false;
3152
3153                 $parent = $p[0];
3154
3155                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3156                 if ($item['verb'] === ACTIVITY_LIKE) {
3157                         $positive = "true";
3158                 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3159                         $positive = "false";
3160                 }
3161
3162                 return(array("positive" => $positive,
3163                                 "guid" => $item["guid"],
3164                                 "target_type" => $target_type,
3165                                 "parent_guid" => $parent["guid"],
3166                                 "author_signature" => "",
3167                                 "diaspora_handle" => self::my_handle($owner)));
3168         }
3169
3170         /**
3171          * @brief Creates an "EventParticipation" object
3172          *
3173          * @param array $item The item that will be exported
3174          * @param array $owner the array of the item owner
3175          *
3176          * @return array The data for an "EventParticipation"
3177          */
3178         private static function construct_attend($item, $owner) {
3179
3180                 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3181                         dbesc($item["thr-parent"]));
3182                 if (!dbm::is_result($p))
3183                         return false;
3184
3185                 $parent = $p[0];
3186
3187                 switch ($item['verb']) {
3188                         case ACTIVITY_ATTEND:
3189                                 $attend_answer = 'accepted';
3190                                 break;
3191                         case ACTIVITY_ATTENDNO:
3192                                 $attend_answer = 'declined';
3193                                 break;
3194                         case ACTIVITY_ATTENDMAYBE:
3195                                 $attend_answer = 'tentative';
3196                                 break;
3197                         default:
3198                                 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3199                                 return false;
3200                 }
3201
3202                 return(array("author" => self::my_handle($owner),
3203                                 "guid" => $item["guid"],
3204                                 "parent_guid" => $parent["guid"],
3205                                 "status" => $attend_answer,
3206                                 "author_signature" => ""));
3207         }
3208
3209         /**
3210          * @brief Creates the object for a comment
3211          *
3212          * @param array $item The item that will be exported
3213          * @param array $owner the array of the item owner
3214          *
3215          * @return array The data for a comment
3216          */
3217         private static function construct_comment($item, $owner) {
3218
3219                 $cachekey = "diaspora:construct_comment:".$item['guid'];
3220
3221                 $result = Cache::get($cachekey);
3222                 if (!is_null($result)) {
3223                         return $result;
3224                 }
3225
3226                 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3227                         intval($item["parent"]),
3228                         intval($item["parent"])
3229                 );
3230
3231                 if (!dbm::is_result($p))
3232                         return false;
3233
3234                 $parent = $p[0];
3235
3236                 $text = html_entity_decode(bb2diaspora($item["body"]));
3237                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3238
3239                 $comment = array("guid" => $item["guid"],
3240                                 "parent_guid" => $parent["guid"],
3241                                 "author_signature" => "",
3242                                 "text" => $text,
3243                                 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3244                                 "diaspora_handle" => self::my_handle($owner));
3245
3246                 // Send the thread parent guid only if it is a threaded comment
3247                 if ($item['thr-parent'] != $item['parent-uri']) {
3248                         $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3249                 }
3250
3251                 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3252
3253                 return($comment);
3254         }
3255
3256         /**
3257          * @brief Send a like or a comment
3258          *
3259          * @param array $item The item that will be exported
3260          * @param array $owner the array of the item owner
3261          * @param array $contact Target of the communication
3262          * @param bool $public_batch Is it a public post?
3263          *
3264          * @return int The result of the transmission
3265          */
3266         public static function send_followup($item,$owner,$contact,$public_batch = false) {
3267
3268                 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3269                         $message = self::construct_attend($item, $owner);
3270                         $type = "event_participation";
3271                 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3272                         $message = self::construct_like($item, $owner);
3273                         $type = "like";
3274                 } else {
3275                         $message = self::construct_comment($item, $owner);
3276                         $type = "comment";
3277                 }
3278
3279                 if (!$message)
3280                         return false;
3281
3282                 $message["author_signature"] = self::signature($owner, $message);
3283
3284                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3285         }
3286
3287         /**
3288          * @brief Creates a message from a signature record entry
3289          *
3290          * @param array $item The item that will be exported
3291          * @param array $signature The entry of the "sign" record
3292          *
3293          * @return string The message
3294          */
3295         private static function message_from_signature($item, $signature) {
3296
3297                 // Split the signed text
3298                 $signed_parts = explode(";", $signature['signed_text']);
3299
3300                 if ($item["deleted"])
3301                         $message = array("parent_author_signature" => "",
3302                                         "target_guid" => $signed_parts[0],
3303                                         "target_type" => $signed_parts[1],
3304                                         "sender_handle" => $signature['signer'],
3305                                         "target_author_signature" => $signature['signature']);
3306                 elseif ($item['verb'] === ACTIVITY_LIKE)
3307                         $message = array("positive" => $signed_parts[0],
3308                                         "guid" => $signed_parts[1],
3309                                         "target_type" => $signed_parts[2],
3310                                         "parent_guid" => $signed_parts[3],
3311                                         "parent_author_signature" => "",
3312                                         "author_signature" => $signature['signature'],
3313                                         "diaspora_handle" => $signed_parts[4]);
3314                 else {
3315                         // Remove the comment guid
3316                         $guid = array_shift($signed_parts);
3317
3318                         // Remove the parent guid
3319                         $parent_guid = array_shift($signed_parts);
3320
3321                         // Remove the handle
3322                         $handle = array_pop($signed_parts);
3323
3324                         // Glue the parts together
3325                         $text = implode(";", $signed_parts);
3326
3327                         $message = array("guid" => $guid,
3328                                         "parent_guid" => $parent_guid,
3329                                         "parent_author_signature" => "",
3330                                         "author_signature" => $signature['signature'],
3331                                         "text" => implode(";", $signed_parts),
3332                                         "diaspora_handle" => $handle);
3333                 }
3334                 return $message;
3335         }
3336
3337         /**
3338          * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3339          *
3340          * @param array $item The item that will be exported
3341          * @param array $owner the array of the item owner
3342          * @param array $contact Target of the communication
3343          * @param bool $public_batch Is it a public post?
3344          *
3345          * @return int The result of the transmission
3346          */
3347         public static function send_relay($item, $owner, $contact, $public_batch = false) {
3348
3349                 if ($item["deleted"])
3350                         return self::send_retraction($item, $owner, $contact, $public_batch, true);
3351                 elseif ($item['verb'] === ACTIVITY_LIKE)
3352                         $type = "like";
3353                 else
3354                         $type = "comment";
3355
3356                 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3357
3358                 // fetch the original signature
3359
3360                 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3361                         intval($item["id"]));
3362
3363                 if (!$r) {
3364                         logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3365                         return false;
3366                 }
3367
3368                 $signature = $r[0];
3369
3370                 // Old way - is used by the internal Friendica functions
3371                 /// @todo Change all signatur storing functions to the new format
3372                 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3373                         $message = self::message_from_signature($item, $signature);
3374                 else {// New way
3375                         $msg = json_decode($signature['signed_text'], true);
3376
3377                         $message = array();
3378                         if (is_array($msg)) {
3379                                 foreach ($msg AS $field => $data) {
3380                                         if (!$item["deleted"]) {
3381                                                 if ($field == "author")
3382                                                         $field = "diaspora_handle";
3383                                                 if ($field == "parent_type")
3384                                                         $field = "target_type";
3385                                         }
3386
3387                                         $message[$field] = $data;
3388                                 }
3389                         } else
3390                                 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3391                 }
3392
3393                 $message["parent_author_signature"] = self::signature($owner, $message);
3394
3395                 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3396
3397                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3398         }
3399
3400         /**
3401          * @brief Sends a retraction (deletion) of a message, like or comment
3402          *
3403          * @param array $item The item that will be exported
3404          * @param array $owner the array of the item owner
3405          * @param array $contact Target of the communication
3406          * @param bool $public_batch Is it a public post?
3407          * @param bool $relay Is the retraction transmitted from a relay?
3408          *
3409          * @return int The result of the transmission
3410          */
3411         public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3412
3413                 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3414
3415                 // Check whether the retraction is for a top-level post or whether it's a relayable
3416                 if ($item["uri"] !== $item["parent-uri"]) {
3417                         $msg_type = "relayable_retraction";
3418                         $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3419                 } else {
3420                         $msg_type = "signed_retraction";
3421                         $target_type = "StatusMessage";
3422                 }
3423
3424                 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3425                         $signature = "parent_author_signature";
3426                 else
3427                         $signature = "target_author_signature";
3428
3429                 $signed_text = $item["guid"].";".$target_type;
3430
3431                 $message = array("target_guid" => $item['guid'],
3432                                 "target_type" => $target_type,
3433                                 "sender_handle" => $itemaddr,
3434                                 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3435
3436                 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3437
3438                 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3439         }
3440
3441         /**
3442          * @brief Sends a mail
3443          *
3444          * @param array $item The item that will be exported
3445          * @param array $owner The owner
3446          * @param array $contact Target of the communication
3447          *
3448          * @return int The result of the transmission
3449          */
3450         public static function send_mail($item, $owner, $contact) {
3451
3452                 $myaddr = self::my_handle($owner);
3453
3454                 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3455                         intval($item["convid"]),
3456                         intval($item["uid"])
3457                 );
3458
3459                 if (!dbm::is_result($r)) {
3460                         logger("conversation not found.");
3461                         return;
3462                 }
3463                 $cnv = $r[0];
3464
3465                 $conv = array(
3466                         "guid" => $cnv["guid"],
3467                         "subject" => $cnv["subject"],
3468                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3469                         "diaspora_handle" => $cnv["creator"],
3470                         "participant_handles" => $cnv["recips"]
3471                 );
3472
3473                 $body = bb2diaspora($item["body"]);
3474                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3475
3476                 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3477                 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3478
3479                 $msg = array(
3480                         "guid" => $item["guid"],
3481                         "parent_guid" => $cnv["guid"],
3482                         "parent_author_signature" => $sig,
3483                         "author_signature" => $sig,
3484                         "text" => $body,
3485                         "created_at" => $created,
3486                         "diaspora_handle" => $myaddr,
3487                         "conversation_guid" => $cnv["guid"]
3488                 );
3489
3490                 if ($item["reply"]) {
3491                         $message = $msg;
3492                         $type = "message";
3493                 } else {
3494                         $message = array("guid" => $cnv["guid"],
3495                                         "subject" => $cnv["subject"],
3496                                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3497                                         "message" => $msg,
3498                                         "diaspora_handle" => $cnv["creator"],
3499                                         "participant_handles" => $cnv["recips"]);
3500
3501                         $type = "conversation";
3502                 }
3503
3504                 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3505         }
3506
3507         /**
3508          * @brief Sends profile data
3509          *
3510          * @param int $uid The user id
3511          */
3512         public static function send_profile($uid, $recips = false) {
3513
3514                 if (!$uid)
3515                         return;
3516
3517                 if (!$recips)
3518                         $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3519                                 AND `uid` = %d AND `rel` != %d",
3520                                 dbesc(NETWORK_DIASPORA),
3521                                 intval($uid),
3522                                 intval(CONTACT_IS_SHARING)
3523                         );
3524                 if (!$recips)
3525                         return;
3526
3527                 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3528                         FROM `profile`
3529                         INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3530                         INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3531                         WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3532                         intval($uid)
3533                 );
3534
3535                 if (!$r)
3536                         return;
3537
3538                 $profile = $r[0];
3539
3540                 $handle = $profile["addr"];
3541                 $first = ((strpos($profile['name'],' ')
3542                         ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3543                 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3544                 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3545                 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3546                 $small = App::get_baseurl().'/photo/custom/50/'  .$profile['uid'].'.jpg';
3547                 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3548
3549                 if ($searchable === 'true') {
3550                         $dob = '1000-00-00';
3551
3552                         if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3553                                 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3554
3555                         $about = $profile['about'];
3556                         $about = strip_tags(bbcode($about));
3557
3558                         $location = formatted_location($profile);
3559                         $tags = '';
3560                         if ($profile['pub_keywords']) {
3561                                 $kw = str_replace(',',' ',$profile['pub_keywords']);
3562                                 $kw = str_replace('  ',' ',$kw);
3563                                 $arr = explode(' ',$profile['pub_keywords']);
3564                                 if (count($arr)) {
3565                                         for($x = 0; $x < 5; $x ++) {
3566                                                 if (trim($arr[$x]))
3567                                                         $tags .= '#'. trim($arr[$x]) .' ';
3568                                         }
3569                                 }
3570                         }
3571                         $tags = trim($tags);
3572                 }
3573
3574                 $message = array("diaspora_handle" => $handle,
3575                                 "first_name" => $first,
3576                                 "last_name" => $last,
3577                                 "image_url" => $large,
3578                                 "image_url_medium" => $medium,
3579                                 "image_url_small" => $small,
3580                                 "birthday" => $dob,
3581                                 "gender" => $profile['gender'],
3582                                 "bio" => $about,
3583                                 "location" => $location,
3584                                 "searchable" => $searchable,
3585                                 "tag_string" => $tags);
3586
3587                 foreach($recips as $recip) {
3588                         logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3589                         self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3590                 }
3591         }
3592
3593         /**
3594          * @brief Stores the signature for likes that are created on our system
3595          *
3596          * @param array $contact The contact array of the "like"
3597          * @param int $post_id The post id of the "like"
3598          *
3599          * @return bool Success
3600          */
3601         public static function store_like_signature($contact, $post_id) {
3602
3603                 // Is the contact the owner? Then fetch the private key
3604                 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3605                         logger("No owner post, so not storing signature", LOGGER_DEBUG);
3606                         return false;
3607                 }
3608
3609                 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3610                 if(!$r)
3611                         return false;
3612
3613                 $contact["uprvkey"] = $r[0]['prvkey'];
3614
3615                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3616                 if (!$r)
3617                         return false;
3618
3619                 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
3620                         return false;
3621
3622                 $message = self::construct_like($r[0], $contact);
3623                 $message["author_signature"] = self::signature($contact, $message);
3624
3625                 // We now store the signature more flexible to dynamically support new fields.
3626                 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3627                 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3628                         intval($message_id),
3629                         dbesc(json_encode($message))
3630                 );
3631
3632                 logger('Stored diaspora like signature');
3633                 return true;
3634         }
3635
3636         /**
3637          * @brief Stores the signature for comments that are created on our system
3638          *
3639          * @param array $item The item array of the comment
3640          * @param array $contact The contact array of the item owner
3641          * @param string $uprvkey The private key of the sender
3642          * @param int $message_id The message id of the comment
3643          *
3644          * @return bool Success
3645          */
3646         public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3647
3648                 if ($uprvkey == "") {
3649                         logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3650                         return false;
3651                 }
3652
3653                 $contact["uprvkey"] = $uprvkey;
3654
3655                 $message = self::construct_comment($item, $contact);
3656                 $message["author_signature"] = self::signature($contact, $message);
3657
3658                 // We now store the signature more flexible to dynamically support new fields.
3659                 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3660                 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3661                         intval($message_id),
3662                         dbesc(json_encode($message))
3663                 );
3664
3665                 logger('Stored diaspora comment signature');
3666                 return true;
3667         }
3668 }
3669 ?>