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