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