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