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