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