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