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