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