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