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