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