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