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