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