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