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