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