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