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