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