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