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