]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Diaspora.php
Move Object\Contact to Model\Contact
[friendica.git] / src / Protocol / Diaspora.php
1 <?php
2 /**
3  * @file include/diaspora.php
4  * @brief The implementation of the diaspora protocol
5  *
6  * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7  * This implementation here interprets the old and the new protocol and sends the new one.
8  * In the future we will remove most stuff from "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\GlobalContact;
21 use Friendica\Model\Profile;
22 use Friendica\Network\Probe;
23 use Friendica\Util\XML;
24
25 use dba;
26 use SimpleXMLElement;
27
28 require_once 'include/items.php';
29 require_once 'include/bb2diaspora.php';
30 require_once 'include/group.php';
31 require_once 'include/datetime.php';
32 require_once 'include/queue_fn.php';
33
34 /**
35  * @brief This class contain functions to create and send Diaspora XML files
36  *
37  */
38 class Diaspora
39 {
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                 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
996                         dba::update(
997                                 'contact',
998                                 array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
999                                 array('id' => $contact["id"], 'uid' => $contact["uid"])
1000                         );
1001
1002                         $contact["rel"] = CONTACT_IS_FRIEND;
1003                         logger("defining user ".$contact["nick"]." as friend");
1004                 }
1005
1006                 // We don't seem to like that person
1007                 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
1008                         // Maybe blocked, don't accept.
1009                         return false;
1010                         // We are following this person?
1011                 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1012                         // Yes, then it is fine.
1013                         return true;
1014                         // Is it a post to a community?
1015                 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
1016                         // That's good
1017                         return true;
1018                         // Is the message a global user or a comment?
1019                 } elseif (($importer["uid"] == 0) || $is_comment) {
1020                         // Messages for the global users and comments are always accepted
1021                         return true;
1022                 }
1023
1024                 return false;
1025         }
1026
1027         /**
1028          * @brief Fetches the contact id for a handle and checks if posting is allowed
1029          *
1030          * @param array  $importer   Array of the importer user
1031          * @param string $handle     The checked handle in the format user@domain.tld
1032          * @param bool   $is_comment Is the check for a comment?
1033          *
1034          * @return array The contact data
1035          */
1036         private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1037         {
1038                 $contact = self::contactByHandle($importer["uid"], $handle);
1039                 if (!$contact) {
1040                         logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1041                         // If a contact isn't found, we accept it anyway if it is a comment
1042                         if ($is_comment) {
1043                                 return $importer;
1044                         } else {
1045                                 return false;
1046                         }
1047                 }
1048
1049                 if (!self::postAllow($importer, $contact, $is_comment)) {
1050                         logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1051                         return false;
1052                 }
1053                 return $contact;
1054         }
1055
1056         /**
1057          * @brief Does the message already exists on the system?
1058          *
1059          * @param int    $uid  The user id
1060          * @param string $guid The guid of the message
1061          *
1062          * @return int|bool message id if the message already was stored into the system - or false.
1063          */
1064         private static function messageExists($uid, $guid)
1065         {
1066                 $r = q(
1067                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1068                         intval($uid),
1069                         dbesc($guid)
1070                 );
1071
1072                 if (DBM::is_result($r)) {
1073                         logger("message ".$guid." already exists for user ".$uid);
1074                         return $r[0]["id"];
1075                 }
1076
1077                 return false;
1078         }
1079
1080         /**
1081          * @brief Checks for links to posts in a message
1082          *
1083          * @param array $item The item array
1084          * @return void
1085          */
1086         private static function fetchGuid($item)
1087         {
1088                 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1089                 preg_replace_callback(
1090                         $expression,
1091                         function ($match) use ($item) {
1092                                 return self::fetchGuidSub($match, $item);
1093                         },
1094                         $item["body"]
1095                 );
1096
1097                 preg_replace_callback(
1098                         "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1099                         function ($match) use ($item) {
1100                                 return self::fetchGuidSub($match, $item);
1101                         },
1102                         $item["body"]
1103                 );
1104         }
1105
1106         /**
1107          * @brief Checks for relative /people/* links in an item body to match local
1108          * contacts or prepends the remote host taken from the author link.
1109          *
1110          * @param string $body        The item body to replace links from
1111          * @param string $author_link The author link for missing local contact fallback
1112          *
1113          * @return the replaced string
1114          */
1115         public static function replacePeopleGuid($body, $author_link)
1116         {
1117                 $return = preg_replace_callback(
1118                         "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1119                         function ($match) use ($author_link) {
1120                                 // $match
1121                                 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1122                                 // 1 => '0123456789abcdef'
1123                                 // 2 => 'Foo Bar'
1124                                 $handle = self::urlFromContactGuid($match[1]);
1125
1126                                 if ($handle) {
1127                                         $return = '@[url='.$handle.']'.$match[2].'[/url]';
1128                                 } else {
1129                                         // No local match, restoring absolute remote URL from author scheme and host
1130                                         $author_url = parse_url($author_link);
1131                                         $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1132                                 }
1133
1134                                 return $return;
1135                         },
1136                         $body
1137                 );
1138
1139                 return $return;
1140         }
1141
1142         /**
1143          * @brief sub function of "fetchGuid" which checks for links in messages
1144          *
1145          * @param array $match array containing a link that has to be checked for a message link
1146          * @param array $item  The item array
1147          * @return void
1148          */
1149         private static function fetchGuidSub($match, $item)
1150         {
1151                 if (!self::storeByGuid($match[1], $item["author-link"])) {
1152                         self::storeByGuid($match[1], $item["owner-link"]);
1153                 }
1154         }
1155
1156         /**
1157          * @brief Fetches an item with a given guid from a given server
1158          *
1159          * @param string $guid   the message guid
1160          * @param string $server The server address
1161          * @param int    $uid    The user id of the user
1162          *
1163          * @return int the message id of the stored message or false
1164          */
1165         private static function storeByGuid($guid, $server, $uid = 0)
1166         {
1167                 $serverparts = parse_url($server);
1168                 $server = $serverparts["scheme"]."://".$serverparts["host"];
1169
1170                 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1171
1172                 $msg = self::message($guid, $server);
1173
1174                 if (!$msg) {
1175                         return false;
1176                 }
1177
1178                 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1179
1180                 // Now call the dispatcher
1181                 return self::dispatchPublic($msg);
1182         }
1183
1184         /**
1185          * @brief Fetches a message from a server
1186          *
1187          * @param string $guid   message guid
1188          * @param string $server The url of the server
1189          * @param int    $level  Endless loop prevention
1190          *
1191          * @return array
1192          *      'message' => The message XML
1193          *      'author' => The author handle
1194          *      'key' => The public key of the author
1195          */
1196         private static function message($guid, $server, $level = 0)
1197         {
1198                 if ($level > 5) {
1199                         return false;
1200                 }
1201
1202                 // This will work for new Diaspora servers and Friendica servers from 3.5
1203                 $source_url = $server."/fetch/post/".urlencode($guid);
1204
1205                 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1206
1207                 $envelope = fetch_url($source_url);
1208                 if ($envelope) {
1209                         logger("Envelope was fetched.", LOGGER_DEBUG);
1210                         $x = self::verifyMagicEnvelope($envelope);
1211                         if (!$x) {
1212                                 logger("Envelope could not be verified.", LOGGER_DEBUG);
1213                         } else {
1214                                 logger("Envelope was verified.", LOGGER_DEBUG);
1215                         }
1216                 } else {
1217                         $x = false;
1218                 }
1219
1220                 // This will work for older Diaspora and Friendica servers
1221                 if (!$x) {
1222                         $source_url = $server."/p/".urlencode($guid).".xml";
1223                         logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1224
1225                         $x = fetch_url($source_url);
1226                         if (!$x) {
1227                                 return false;
1228                         }
1229                 }
1230
1231                 $source_xml = parse_xml_string($x);
1232
1233                 if (!is_object($source_xml)) {
1234                         return false;
1235                 }
1236
1237                 if ($source_xml->post->reshare) {
1238                         // Reshare of a reshare - old Diaspora version
1239                         logger("Message is a reshare", LOGGER_DEBUG);
1240                         return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1241                 } elseif ($source_xml->getName() == "reshare") {
1242                         // Reshare of a reshare - new Diaspora version
1243                         logger("Message is a new reshare", LOGGER_DEBUG);
1244                         return self::message($source_xml->root_guid, $server, ++$level);
1245                 }
1246
1247                 $author = "";
1248
1249                 // Fetch the author - for the old and the new Diaspora version
1250                 if ($source_xml->post->status_message->diaspora_handle) {
1251                         $author = (string)$source_xml->post->status_message->diaspora_handle;
1252                 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1253                         $author = (string)$source_xml->author;
1254                 }
1255
1256                 // If this isn't a "status_message" then quit
1257                 if (!$author) {
1258                         logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1259                         return false;
1260                 }
1261
1262                 $msg = array("message" => $x, "author" => $author);
1263
1264                 $msg["key"] = self::key($msg["author"]);
1265
1266                 return $msg;
1267         }
1268
1269         /**
1270          * @brief Fetches the item record of a given guid
1271          *
1272          * @param int    $uid     The user id
1273          * @param string $guid    message guid
1274          * @param string $author  The handle of the item
1275          * @param array  $contact The contact of the item owner
1276          *
1277          * @return array the item record
1278          */
1279         private static function parentItem($uid, $guid, $author, $contact)
1280         {
1281                 $r = q(
1282                         "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1283                                 `author-name`, `author-link`, `author-avatar`,
1284                                 `owner-name`, `owner-link`, `owner-avatar`
1285                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1286                         intval($uid),
1287                         dbesc($guid)
1288                 );
1289
1290                 if (!$r) {
1291                         $result = self::storeByGuid($guid, $contact["url"], $uid);
1292
1293                         if (!$result) {
1294                                 $person = self::personByHandle($author);
1295                                 $result = self::storeByGuid($guid, $person["url"], $uid);
1296                         }
1297
1298                         if ($result) {
1299                                 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1300
1301                                 $r = q(
1302                                         "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1303                                                 `author-name`, `author-link`, `author-avatar`,
1304                                                 `owner-name`, `owner-link`, `owner-avatar`
1305                                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1306                                         intval($uid),
1307                                         dbesc($guid)
1308                                 );
1309                         }
1310                 }
1311
1312                 if (!$r) {
1313                         logger("parent item not found: parent: ".$guid." - user: ".$uid);
1314                         return false;
1315                 } else {
1316                         logger("parent item found: parent: ".$guid." - user: ".$uid);
1317                         return $r[0];
1318                 }
1319         }
1320
1321         /**
1322          * @brief returns contact details
1323          *
1324          * @param array $contact The default contact if the person isn't found
1325          * @param array $person  The record of the person
1326          * @param int   $uid     The user id
1327          *
1328          * @return array
1329          *      'cid' => contact id
1330          *      'network' => network type
1331          */
1332         private static function authorContactByUrl($contact, $person, $uid)
1333         {
1334                 $r = q(
1335                         "SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1336                         dbesc(normalise_link($person["url"])),
1337                         intval($uid)
1338                 );
1339                 if ($r) {
1340                         $cid = $r[0]["id"];
1341                         $network = $r[0]["network"];
1342                 } else {
1343                         $cid = $contact["id"];
1344                         $network = NETWORK_DIASPORA;
1345                 }
1346
1347                 return array("cid" => $cid, "network" => $network);
1348         }
1349
1350         /**
1351          * @brief Is the profile a hubzilla profile?
1352          *
1353          * @param string $url The profile link
1354          *
1355          * @return bool is it a hubzilla server?
1356          */
1357         public static function isRedmatrix($url)
1358         {
1359                 return(strstr($url, "/channel/"));
1360         }
1361
1362         /**
1363          * @brief Generate a post link with a given handle and message guid
1364          *
1365          * @param string $addr        The user handle
1366          * @param string $guid        message guid
1367          * @param string $parent_guid optional parent guid
1368          *
1369          * @return string the post link
1370          */
1371         private static function plink($addr, $guid, $parent_guid = '')
1372         {
1373                 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1374
1375                 // Fallback
1376                 if (!DBM::is_result($r)) {
1377                         if ($parent_guid != '') {
1378                                 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1379                         } else {
1380                                 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1381                         }
1382                 }
1383
1384                 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1385                 // So we try another way as well.
1386                 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1387                 if (DBM::is_result($s)) {
1388                         $r[0]["network"] = $s[0]["network"];
1389                 }
1390
1391                 if ($r[0]["network"] == NETWORK_DFRN) {
1392                         return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1393                 }
1394
1395                 if (self::isRedmatrix($r[0]["url"])) {
1396                         return $r[0]["url"]."/?f=&mid=".$guid;
1397                 }
1398
1399                 if ($parent_guid != '') {
1400                         return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1401                 } else {
1402                         return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1403                 }
1404         }
1405
1406         /**
1407          * @brief Receives account migration
1408          *
1409          * @param array  $importer Array of the importer user
1410          * @param object $data     The message object
1411          *
1412          * @return bool Success
1413          */
1414         private static function receiveAccountMigration($importer, $data)
1415         {
1416                 $old_handle = notags(unxmlify($data->author));
1417                 $new_handle = notags(unxmlify($data->profile->author));
1418                 $signature = notags(unxmlify($data->signature));
1419
1420                 $contact = self::contactByHandle($importer["uid"], $old_handle);
1421                 if (!$contact) {
1422                         logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1423                         return false;
1424                 }
1425
1426                 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1427
1428                 // Check signature
1429                 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1430                 $key = self::key($old_handle);
1431                 if (!rsa_verify($signed_text, $signature, $key, "sha256")) {
1432                         logger('No valid signature for migration.');
1433                         return false;
1434                 }
1435
1436                 // Update the profile
1437                 self::receiveProfile($importer, $data->profile);
1438
1439                 // change the technical stuff in contact and gcontact
1440                 $data = Probe::uri($new_handle);
1441                 if ($data['network'] == NETWORK_PHANTOM) {
1442                         logger('Account for '.$new_handle." couldn't be probed.");
1443                         return false;
1444                 }
1445
1446                 $fields = array('url' => $data['url'], 'nurl' => normalise_link($data['url']),
1447                                 'name' => $data['name'], 'nick' => $data['nick'],
1448                                 'addr' => $data['addr'], 'batch' => $data['batch'],
1449                                 'notify' => $data['notify'], 'poll' => $data['poll'],
1450                                 'network' => $data['network']);
1451
1452                 dba::update('contact', $fields, array('addr' => $old_handle));
1453
1454                 $fields = array('url' => $data['url'], 'nurl' => normalise_link($data['url']),
1455                                 'name' => $data['name'], 'nick' => $data['nick'],
1456                                 'addr' => $data['addr'], 'connect' => $data['addr'],
1457                                 'notify' => $data['notify'], 'photo' => $data['photo'],
1458                                 'server_url' => $data['baseurl'], 'network' => $data['network']);
1459
1460                 dba::update('gcontact', $fields, array('addr' => $old_handle));
1461
1462                 logger('Contacts are updated.');
1463
1464                 // update items
1465                 /// @todo This is an extreme performance killer
1466                 $fields = array(
1467                         'owner-link' => array($contact["url"], $data["url"]),
1468                         'author-link' => array($contact["url"], $data["url"]),
1469                 );
1470                 foreach ($fields as $n => $f) {
1471                         $r = q(
1472                                 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1473                                 $n,
1474                                 dbesc($f[0]),
1475                                 intval($importer["uid"])
1476                         );
1477
1478                         if (DBM::is_result($r)) {
1479                                 $x = q(
1480                                         "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1481                                         $n,
1482                                         dbesc($f[1]),
1483                                         $n,
1484                                         dbesc($f[0]),
1485                                         intval($importer["uid"])
1486                                 );
1487
1488                                 if ($x === false) {
1489                                         return false;
1490                                 }
1491                         }
1492                 }
1493
1494                 logger('Items are updated.');
1495
1496                 return true;
1497         }
1498
1499         /**
1500          * @brief Processes an account deletion
1501          *
1502          * @param array  $importer Array of the importer user
1503          * @param object $data     The message object
1504          *
1505          * @return bool Success
1506          */
1507         private static function receiveAccountDeletion($importer, $data)
1508         {
1509                 /// @todo Account deletion should remove the contact from the global contacts as well
1510
1511                 $author = notags(unxmlify($data->author));
1512
1513                 $contact = self::contactByHandle($importer["uid"], $author);
1514                 if (!$contact) {
1515                         logger("cannot find contact for author: ".$author);
1516                         return false;
1517                 }
1518
1519                 // We now remove the contact
1520                 Contact::remove($contact["id"]);
1521                 return true;
1522         }
1523
1524         /**
1525          * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1526          *
1527          * @param string  $author    Author handle
1528          * @param string  $guid      Message guid
1529          * @param boolean $onlyfound Only return uri when found in the database
1530          *
1531          * @return string The constructed uri or the one from our database
1532          */
1533         private static function getUriFromGuid($author, $guid, $onlyfound = false)
1534         {
1535                 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1536                 if (DBM::is_result($r)) {
1537                         return $r[0]["uri"];
1538                 } elseif (!$onlyfound) {
1539                         return $author.":".$guid;
1540                 }
1541
1542                 return "";
1543         }
1544
1545         /**
1546          * @brief Fetch the guid from our database with a given uri
1547          *
1548          * @param string $uri Message uri
1549          * @param string $uid Author handle
1550          *
1551          * @return string The post guid
1552          */
1553         private static function getGuidFromUri($uri, $uid)
1554         {
1555                 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1556                 if (DBM::is_result($r)) {
1557                         return $r[0]["guid"];
1558                 } else {
1559                         return false;
1560                 }
1561         }
1562
1563         /**
1564          * @brief Find the best importer for a comment, like, ...
1565          *
1566          * @param string $guid The guid of the item
1567          *
1568          * @return array|boolean the origin owner of that post - or false
1569          */
1570         private static function importerForGuid($guid)
1571         {
1572                 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1573
1574                 if (DBM::is_result($item)) {
1575                         logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1576                         $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1577                         if (DBM::is_result($contact)) {
1578                                 return $contact;
1579                         }
1580                 }
1581                 return false;
1582         }
1583
1584         /**
1585          * @brief Processes an incoming comment
1586          *
1587          * @param array  $importer Array of the importer user
1588          * @param string $sender   The sender of the message
1589          * @param object $data     The message object
1590          * @param string $xml      The original XML of the message
1591          *
1592          * @return int The message id of the generated comment or "false" if there was an error
1593          */
1594         private static function receiveComment($importer, $sender, $data, $xml)
1595         {
1596                 $author = notags(unxmlify($data->author));
1597                 $guid = notags(unxmlify($data->guid));
1598                 $parent_guid = notags(unxmlify($data->parent_guid));
1599                 $text = unxmlify($data->text);
1600
1601                 if (isset($data->created_at)) {
1602                         $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1603                 } else {
1604                         $created_at = datetime_convert();
1605                 }
1606
1607                 if (isset($data->thread_parent_guid)) {
1608                         $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1609                         $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1610                 } else {
1611                         $thr_uri = "";
1612                 }
1613
1614                 $contact = self::allowedContactByHandle($importer, $sender, true);
1615                 if (!$contact) {
1616                         return false;
1617                 }
1618
1619                 $message_id = self::messageExists($importer["uid"], $guid);
1620                 if ($message_id) {
1621                         return true;
1622                 }
1623
1624                 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1625                 if (!$parent_item) {
1626                         return false;
1627                 }
1628
1629                 $person = self::personByHandle($author);
1630                 if (!is_array($person)) {
1631                         logger("unable to find author details");
1632                         return false;
1633                 }
1634
1635                 // Fetch the contact id - if we know this contact
1636                 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1637
1638                 $datarray = array();
1639
1640                 $datarray["uid"] = $importer["uid"];
1641                 $datarray["contact-id"] = $author_contact["cid"];
1642                 $datarray["network"]  = $author_contact["network"];
1643
1644                 $datarray["author-name"] = $person["name"];
1645                 $datarray["author-link"] = $person["url"];
1646                 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1647
1648                 $datarray["owner-name"] = $contact["name"];
1649                 $datarray["owner-link"] = $contact["url"];
1650                 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1651
1652                 $datarray["guid"] = $guid;
1653                 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1654
1655                 $datarray["type"] = "remote-comment";
1656                 $datarray["verb"] = ACTIVITY_POST;
1657                 $datarray["gravity"] = GRAVITY_COMMENT;
1658
1659                 if ($thr_uri != "") {
1660                         $datarray["parent-uri"] = $thr_uri;
1661                 } else {
1662                         $datarray["parent-uri"] = $parent_item["uri"];
1663                 }
1664
1665                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1666
1667                 $datarray["protocol"] = PROTOCOL_DIASPORA;
1668                 $datarray["source"] = $xml;
1669
1670                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1671
1672                 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1673
1674                 $body = diaspora2bb($text);
1675
1676                 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1677
1678                 self::fetchGuid($datarray);
1679
1680                 $message_id = item_store($datarray);
1681
1682                 if ($message_id <= 0) {
1683                         return false;
1684                 }
1685
1686                 if ($message_id) {
1687                         logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1688                 }
1689
1690                 // If we are the origin of the parent we store the original data and notify our followers
1691                 if ($message_id && $parent_item["origin"]) {
1692                         // Formerly we stored the signed text, the signature and the author in different fields.
1693                         // We now store the raw data so that we are more flexible.
1694                         dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
1695
1696                         // notify others
1697                         Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1698                 }
1699
1700                 return true;
1701         }
1702
1703         /**
1704          * @brief processes and stores private messages
1705          *
1706          * @param array  $importer     Array of the importer user
1707          * @param array  $contact      The contact of the message
1708          * @param object $data         The message object
1709          * @param array  $msg          Array of the processed message, author handle and key
1710          * @param object $mesg         The private message
1711          * @param array  $conversation The conversation record to which this message belongs
1712          *
1713          * @return bool "true" if it was successful
1714          */
1715         private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1716         {
1717                 $author = notags(unxmlify($data->author));
1718                 $guid = notags(unxmlify($data->guid));
1719                 $subject = notags(unxmlify($data->subject));
1720
1721                 // "diaspora_handle" is the element name from the old version
1722                 // "author" is the element name from the new version
1723                 if ($mesg->author) {
1724                         $msg_author = notags(unxmlify($mesg->author));
1725                 } elseif ($mesg->diaspora_handle) {
1726                         $msg_author = notags(unxmlify($mesg->diaspora_handle));
1727                 } else {
1728                         return false;
1729                 }
1730
1731                 $msg_guid = notags(unxmlify($mesg->guid));
1732                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1733                 $msg_text = unxmlify($mesg->text);
1734                 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1735
1736                 if ($msg_conversation_guid != $guid) {
1737                         logger("message conversation guid does not belong to the current conversation.");
1738                         return false;
1739                 }
1740
1741                 $body = diaspora2bb($msg_text);
1742                 $message_uri = $msg_author.":".$msg_guid;
1743
1744                 $person = self::personByHandle($msg_author);
1745
1746                 dba::lock('mail');
1747
1748                 $r = q(
1749                         "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1750                         dbesc($msg_guid),
1751                         intval($importer["uid"])
1752                 );
1753                 if (DBM::is_result($r)) {
1754                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1755                         return false;
1756                 }
1757
1758                 q(
1759                         "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1760                         VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1761                         intval($importer["uid"]),
1762                         dbesc($msg_guid),
1763                         intval($conversation["id"]),
1764                         dbesc($person["name"]),
1765                         dbesc($person["photo"]),
1766                         dbesc($person["url"]),
1767                         intval($contact["id"]),
1768                         dbesc($subject),
1769                         dbesc($body),
1770                         0,
1771                         0,
1772                         dbesc($message_uri),
1773                         dbesc($author.":".$guid),
1774                         dbesc($msg_created_at)
1775                 );
1776
1777                 dba::unlock();
1778
1779                 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
1780
1781                 notification(
1782                         array(
1783                         "type" => NOTIFY_MAIL,
1784                         "notify_flags" => $importer["notify-flags"],
1785                         "language" => $importer["language"],
1786                         "to_name" => $importer["username"],
1787                         "to_email" => $importer["email"],
1788                         "uid" =>$importer["uid"],
1789                         "item" => array("subject" => $subject, "body" => $body),
1790                         "source_name" => $person["name"],
1791                         "source_link" => $person["url"],
1792                         "source_photo" => $person["thumb"],
1793                         "verb" => ACTIVITY_POST,
1794                         "otype" => "mail")
1795                 );
1796                 return true;
1797         }
1798
1799         /**
1800          * @brief Processes new private messages (answers to private messages are processed elsewhere)
1801          *
1802          * @param array  $importer Array of the importer user
1803          * @param array  $msg      Array of the processed message, author handle and key
1804          * @param object $data     The message object
1805          *
1806          * @return bool Success
1807          */
1808         private static function receiveConversation($importer, $msg, $data)
1809         {
1810                 $author = notags(unxmlify($data->author));
1811                 $guid = notags(unxmlify($data->guid));
1812                 $subject = notags(unxmlify($data->subject));
1813                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1814                 $participants = notags(unxmlify($data->participants));
1815
1816                 $messages = $data->message;
1817
1818                 if (!count($messages)) {
1819                         logger("empty conversation");
1820                         return false;
1821                 }
1822
1823                 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1824                 if (!$contact) {
1825                         return false;
1826                 }
1827
1828                 $conversation = null;
1829
1830                 $c = q(
1831                         "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1832                         intval($importer["uid"]),
1833                         dbesc($guid)
1834                 );
1835                 if ($c)
1836                         $conversation = $c[0];
1837                 else {
1838                         $r = q(
1839                                 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1840                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1841                                 intval($importer["uid"]),
1842                                 dbesc($guid),
1843                                 dbesc($author),
1844                                 dbesc($created_at),
1845                                 dbesc(datetime_convert()),
1846                                 dbesc($subject),
1847                                 dbesc($participants)
1848                         );
1849                         if ($r) {
1850                                 $c = q(
1851                                         "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1852                                         intval($importer["uid"]),
1853                                         dbesc($guid)
1854                                 );
1855                         }
1856
1857                         if ($c) {
1858                                 $conversation = $c[0];
1859                         }
1860                 }
1861                 if (!$conversation) {
1862                         logger("unable to create conversation.");
1863                         return false;
1864                 }
1865
1866                 foreach ($messages as $mesg) {
1867                         self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1868                 }
1869
1870                 return true;
1871         }
1872
1873         /**
1874          * @brief Creates the body for a "like" message
1875          *
1876          * @param array  $contact     The contact that send us the "like"
1877          * @param array  $parent_item The item array of the parent item
1878          * @param string $guid        message guid
1879          *
1880          * @return string the body
1881          */
1882         private static function constructLikeBody($contact, $parent_item, $guid)
1883         {
1884                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1885
1886                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1887                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1888                 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1889
1890                 return sprintf($bodyverb, $ulink, $alink, $plink);
1891         }
1892
1893         /**
1894          * @brief Creates a XML object for a "like"
1895          *
1896          * @param array $importer    Array of the importer user
1897          * @param array $parent_item The item array of the parent item
1898          *
1899          * @return string The XML
1900          */
1901         private static function constructLikeObject($importer, $parent_item)
1902         {
1903                 $objtype = ACTIVITY_OBJ_NOTE;
1904                 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1905                 $parent_body = $parent_item["body"];
1906
1907                 $xmldata = array("object" => array("type" => $objtype,
1908                                                 "local" => "1",
1909                                                 "id" => $parent_item["uri"],
1910                                                 "link" => $link,
1911                                                 "title" => "",
1912                                                 "content" => $parent_body));
1913
1914                 return XML::fromArray($xmldata, $xml, true);
1915         }
1916
1917         /**
1918          * @brief Processes "like" messages
1919          *
1920          * @param array  $importer Array of the importer user
1921          * @param string $sender   The sender of the message
1922          * @param object $data     The message object
1923          *
1924          * @return int The message id of the generated like or "false" if there was an error
1925          */
1926         private static function receiveLike($importer, $sender, $data)
1927         {
1928                 $author = notags(unxmlify($data->author));
1929                 $guid = notags(unxmlify($data->guid));
1930                 $parent_guid = notags(unxmlify($data->parent_guid));
1931                 $parent_type = notags(unxmlify($data->parent_type));
1932                 $positive = notags(unxmlify($data->positive));
1933
1934                 // likes on comments aren't supported by Diaspora - only on posts
1935                 // But maybe this will be supported in the future, so we will accept it.
1936                 if (!in_array($parent_type, array("Post", "Comment"))) {
1937                         return false;
1938                 }
1939
1940                 $contact = self::allowedContactByHandle($importer, $sender, true);
1941                 if (!$contact) {
1942                         return false;
1943                 }
1944
1945                 $message_id = self::messageExists($importer["uid"], $guid);
1946                 if ($message_id) {
1947                         return true;
1948                 }
1949
1950                 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1951                 if (!$parent_item) {
1952                         return false;
1953                 }
1954
1955                 $person = self::personByHandle($author);
1956                 if (!is_array($person)) {
1957                         logger("unable to find author details");
1958                         return false;
1959                 }
1960
1961                 // Fetch the contact id - if we know this contact
1962                 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1963
1964                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1965                 // We would accept this anyhow.
1966                 if ($positive == "true") {
1967                         $verb = ACTIVITY_LIKE;
1968                 } else {
1969                         $verb = ACTIVITY_DISLIKE;
1970                 }
1971
1972                 $datarray = array();
1973
1974                 $datarray["protocol"] = PROTOCOL_DIASPORA;
1975
1976                 $datarray["uid"] = $importer["uid"];
1977                 $datarray["contact-id"] = $author_contact["cid"];
1978                 $datarray["network"]  = $author_contact["network"];
1979
1980                 $datarray["author-name"] = $person["name"];
1981                 $datarray["author-link"] = $person["url"];
1982                 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1983
1984                 $datarray["owner-name"] = $contact["name"];
1985                 $datarray["owner-link"] = $contact["url"];
1986                 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1987
1988                 $datarray["guid"] = $guid;
1989                 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1990
1991                 $datarray["type"] = "activity";
1992                 $datarray["verb"] = $verb;
1993                 $datarray["gravity"] = GRAVITY_LIKE;
1994                 $datarray["parent-uri"] = $parent_item["uri"];
1995
1996                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1997                 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
1998
1999                 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2000
2001                 $message_id = item_store($datarray);
2002
2003                 if ($message_id <= 0) {
2004                         return false;
2005                 }
2006
2007                 if ($message_id) {
2008                         logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2009                 }
2010
2011                 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2012                 if ($parent_item["id"] != $parent_item["parent"]) {
2013                         $toplevel = dba::select('item', array('origin'), array('id' => $parent_item["parent"]), array('limit' => 1));
2014                         $origin = $toplevel["origin"];
2015                 } else {
2016                         $origin = $parent_item["origin"];
2017                 }
2018
2019                 // If we are the origin of the parent we store the original data and notify our followers
2020                 if ($message_id && $origin) {
2021                         // Formerly we stored the signed text, the signature and the author in different fields.
2022                         // We now store the raw data so that we are more flexible.
2023                         dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
2024
2025                         // notify others
2026                         Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2027                 }
2028
2029                 return true;
2030         }
2031
2032         /**
2033          * @brief Processes private messages
2034          *
2035          * @param array  $importer Array of the importer user
2036          * @param object $data     The message object
2037          *
2038          * @return bool Success?
2039          */
2040         private static function receiveMessage($importer, $data)
2041         {
2042                 $author = notags(unxmlify($data->author));
2043                 $guid = notags(unxmlify($data->guid));
2044                 $conversation_guid = notags(unxmlify($data->conversation_guid));
2045                 $text = unxmlify($data->text);
2046                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2047
2048                 $contact = self::allowedContactByHandle($importer, $author, true);
2049                 if (!$contact) {
2050                         return false;
2051                 }
2052
2053                 $conversation = null;
2054
2055                 $c = q(
2056                         "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2057                         intval($importer["uid"]),
2058                         dbesc($conversation_guid)
2059                 );
2060                 if ($c) {
2061                         $conversation = $c[0];
2062                 } else {
2063                         logger("conversation not available.");
2064                         return false;
2065                 }
2066
2067                 $message_uri = $author.":".$guid;
2068
2069                 $person = self::personByHandle($author);
2070                 if (!$person) {
2071                         logger("unable to find author details");
2072                         return false;
2073                 }
2074
2075                 $body = diaspora2bb($text);
2076
2077                 $body = self::replacePeopleGuid($body, $person["url"]);
2078
2079                 dba::lock('mail');
2080
2081                 $r = q(
2082                         "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2083                         dbesc($guid),
2084                         intval($importer["uid"])
2085                 );
2086                 if (DBM::is_result($r)) {
2087                         logger("duplicate message already delivered.", LOGGER_DEBUG);
2088                         return false;
2089                 }
2090
2091                 q(
2092                         "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2093                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2094                         intval($importer["uid"]),
2095                         dbesc($guid),
2096                         intval($conversation["id"]),
2097                         dbesc($person["name"]),
2098                         dbesc($person["photo"]),
2099                         dbesc($person["url"]),
2100                         intval($contact["id"]),
2101                         dbesc($conversation["subject"]),
2102                         dbesc($body),
2103                         0,
2104                         1,
2105                         dbesc($message_uri),
2106                         dbesc($author.":".$conversation["guid"]),
2107                         dbesc($created_at)
2108                 );
2109
2110                 dba::unlock();
2111
2112                 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
2113                 return true;
2114         }
2115
2116         /**
2117          * @brief Processes participations - unsupported by now
2118          *
2119          * @param array  $importer Array of the importer user
2120          * @param object $data     The message object
2121          *
2122          * @return bool always true
2123          */
2124         private static function receiveParticipation($importer, $data)
2125         {
2126                 // I'm not sure if we can fully support this message type
2127                 return true;
2128         }
2129
2130         /**
2131          * @brief Processes photos - unneeded
2132          *
2133          * @param array  $importer Array of the importer user
2134          * @param object $data     The message object
2135          *
2136          * @return bool always true
2137          */
2138         private static function receivePhoto($importer, $data)
2139         {
2140                 // There doesn't seem to be a reason for this function,
2141                 // since the photo data is transmitted in the status message as well
2142                 return true;
2143         }
2144
2145         /**
2146          * @brief Processes poll participations - unssupported
2147          *
2148          * @param array  $importer Array of the importer user
2149          * @param object $data     The message object
2150          *
2151          * @return bool always true
2152          */
2153         private static function receivePollParticipation($importer, $data)
2154         {
2155                 // We don't support polls by now
2156                 return true;
2157         }
2158
2159         /**
2160          * @brief Processes incoming profile updates
2161          *
2162          * @param array  $importer Array of the importer user
2163          * @param object $data     The message object
2164          *
2165          * @return bool Success
2166          */
2167         private static function receiveProfile($importer, $data)
2168         {
2169                 $author = strtolower(notags(unxmlify($data->author)));
2170
2171                 $contact = self::contactByHandle($importer["uid"], $author);
2172                 if (!$contact) {
2173                         return false;
2174                 }
2175
2176                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2177                 $image_url = unxmlify($data->image_url);
2178                 $birthday = unxmlify($data->birthday);
2179                 $gender = unxmlify($data->gender);
2180                 $about = diaspora2bb(unxmlify($data->bio));
2181                 $location = diaspora2bb(unxmlify($data->location));
2182                 $searchable = (unxmlify($data->searchable) == "true");
2183                 $nsfw = (unxmlify($data->nsfw) == "true");
2184                 $tags = unxmlify($data->tag_string);
2185
2186                 $tags = explode("#", $tags);
2187
2188                 $keywords = array();
2189                 foreach ($tags as $tag) {
2190                         $tag = trim(strtolower($tag));
2191                         if ($tag != "") {
2192                                 $keywords[] = $tag;
2193                         }
2194                 }
2195
2196                 $keywords = implode(", ", $keywords);
2197
2198                 $handle_parts = explode("@", $author);
2199                 $nick = $handle_parts[0];
2200
2201                 if ($name === "") {
2202                         $name = $handle_parts[0];
2203                 }
2204
2205                 if (preg_match("|^https?://|", $image_url) === 0) {
2206                         $image_url = "http://".$handle_parts[1].$image_url;
2207                 }
2208
2209                 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2210
2211                 // Generic birthday. We don't know the timezone. The year is irrelevant.
2212
2213                 $birthday = str_replace("1000", "1901", $birthday);
2214
2215                 if ($birthday != "") {
2216                         $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
2217                 }
2218
2219                 // this is to prevent multiple birthday notifications in a single year
2220                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2221
2222                 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2223                         $birthday = $contact["bd"];
2224                 }
2225
2226                 $r = q(
2227                         "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2228                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2229                         dbesc($name),
2230                         dbesc($nick),
2231                         dbesc($author),
2232                         dbesc(datetime_convert()),
2233                         dbesc($birthday),
2234                         dbesc($location),
2235                         dbesc($about),
2236                         dbesc($keywords),
2237                         dbesc($gender),
2238                         intval($contact["id"]),
2239                         intval($importer["uid"])
2240                 );
2241
2242                 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2243                                         "photo" => $image_url, "name" => $name, "location" => $location,
2244                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
2245                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2246                                         "hide" => !$searchable, "nsfw" => $nsfw);
2247
2248                 $gcid = GlobalContact::update($gcontact);
2249
2250                 GlobalContact::link($gcid, $importer["uid"], $contact["id"]);
2251
2252                 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2253
2254                 return true;
2255         }
2256
2257         /**
2258          * @brief Processes incoming friend requests
2259          *
2260          * @param array $importer Array of the importer user
2261          * @param array $contact  The contact that send the request
2262          * @return void
2263          */
2264         private static function receiveRequestMakeFriend($importer, $contact)
2265         {
2266                 $a = get_app();
2267
2268                 if ($contact["rel"] == CONTACT_IS_SHARING) {
2269                         dba::update(
2270                                 'contact',
2271                                 array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
2272                                 array('id' => $contact["id"], 'uid' => $importer["uid"])
2273                         );
2274                 }
2275                 // send notification
2276
2277                 $r = q(
2278                         "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2279                         intval($importer["uid"])
2280                 );
2281
2282                 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2283                         $self = q(
2284                                 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2285                                 intval($importer["uid"])
2286                         );
2287
2288                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2289
2290                         if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2291                                 $arr = array();
2292                                 $arr["protocol"] = PROTOCOL_DIASPORA;
2293                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2294                                 $arr["uid"] = $importer["uid"];
2295                                 $arr["contact-id"] = $self[0]["id"];
2296                                 $arr["wall"] = 1;
2297                                 $arr["type"] = 'wall';
2298                                 $arr["gravity"] = 0;
2299                                 $arr["origin"] = 1;
2300                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2301                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2302                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2303                                 $arr["verb"] = ACTIVITY_FRIEND;
2304                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2305
2306                                 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2307                                 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2308                                 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2309                                 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
2310
2311                                 $arr["object"] = self::constructNewFriendObject($contact);
2312
2313                                 $arr["last-child"] = 1;
2314
2315                                 $arr["allow_cid"] = $user[0]["allow_cid"];
2316                                 $arr["allow_gid"] = $user[0]["allow_gid"];
2317                                 $arr["deny_cid"]  = $user[0]["deny_cid"];
2318                                 $arr["deny_gid"]  = $user[0]["deny_gid"];
2319
2320                                 $i = item_store($arr);
2321                                 if ($i) {
2322                                         Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2323                                 }
2324                         }
2325                 }
2326         }
2327
2328         /**
2329          * @brief Creates a XML object for a "new friend" message
2330          *
2331          * @param array $contact Array of the contact
2332          *
2333          * @return string The XML
2334          */
2335         private static function constructNewFriendObject($contact)
2336         {
2337                 $objtype = ACTIVITY_OBJ_PERSON;
2338                 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2339                         '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2340
2341                 $xmldata = array("object" => array("type" => $objtype,
2342                                                 "title" => $contact["name"],
2343                                                 "id" => $contact["url"]."/".$contact["name"],
2344                                                 "link" => $link));
2345
2346                 return XML::fromArray($xmldata, $xml, true);
2347         }
2348
2349         /**
2350          * @brief Processes incoming sharing notification
2351          *
2352          * @param array  $importer Array of the importer user
2353          * @param object $data     The message object
2354          *
2355          * @return bool Success
2356          */
2357         private static function receiveContactRequest($importer, $data)
2358         {
2359                 $author = unxmlify($data->author);
2360                 $recipient = unxmlify($data->recipient);
2361
2362                 if (!$author || !$recipient) {
2363                         return false;
2364                 }
2365
2366                 // the current protocol version doesn't know these fields
2367                 // That means that we will assume their existance
2368                 if (isset($data->following)) {
2369                         $following = (unxmlify($data->following) == "true");
2370                 } else {
2371                         $following = true;
2372                 }
2373
2374                 if (isset($data->sharing)) {
2375                         $sharing = (unxmlify($data->sharing) == "true");
2376                 } else {
2377                         $sharing = true;
2378                 }
2379
2380                 $contact = self::contactByHandle($importer["uid"], $author);
2381
2382                 // perhaps we were already sharing with this person. Now they're sharing with us.
2383                 // That makes us friends.
2384                 if ($contact) {
2385                         if ($following) {
2386                                 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2387                                 self::receiveRequestMakeFriend($importer, $contact);
2388
2389                                 // refetch the contact array
2390                                 $contact = self::contactByHandle($importer["uid"], $author);
2391
2392                                 // If we are now friends, we are sending a share message.
2393                                 // Normally we needn't to do so, but the first message could have been vanished.
2394                                 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND))) {
2395                                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2396                                         if ($u) {
2397                                                 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2398                                                 $ret = self::sendShare($u[0], $contact);
2399                                         }
2400                                 }
2401                                 return true;
2402                         } else {
2403                                 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2404                                 lose_follower($importer, $contact);
2405                                 return true;
2406                         }
2407                 }
2408
2409                 if (!$following && $sharing && in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2410                         logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2411                         return false;
2412                 } elseif (!$following && !$sharing) {
2413                         logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2414                         return false;
2415                 } elseif (!$following && $sharing) {
2416                         logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2417                 } elseif ($following && $sharing) {
2418                         logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2419                 } elseif ($following && !$sharing) {
2420                         logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2421                 }
2422
2423                 $ret = self::personByHandle($author);
2424
2425                 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2426                         logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2427                         return false;
2428                 }
2429
2430                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2431
2432                 $r = q(
2433                         "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2434                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2435                         intval($importer["uid"]),
2436                         dbesc($ret["network"]),
2437                         dbesc($ret["addr"]),
2438                         datetime_convert(),
2439                         dbesc($ret["url"]),
2440                         dbesc(normalise_link($ret["url"])),
2441                         dbesc($batch),
2442                         dbesc($ret["name"]),
2443                         dbesc($ret["nick"]),
2444                         dbesc($ret["photo"]),
2445                         dbesc($ret["pubkey"]),
2446                         dbesc($ret["notify"]),
2447                         dbesc($ret["poll"]),
2448                         1,
2449                         2
2450                 );
2451
2452                 // find the contact record we just created
2453
2454                 $contact_record = self::contactByHandle($importer["uid"], $author);
2455
2456                 if (!$contact_record) {
2457                         logger("unable to locate newly created contact record.");
2458                         return;
2459                 }
2460
2461                 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2462
2463                 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2464
2465                 if (intval($def_gid)) {
2466                         group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2467                 }
2468
2469                 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2470
2471                 if ($importer["page-flags"] == PAGE_NORMAL) {
2472                         logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2473
2474                         $hash = random_string().(string)time();   // Generate a confirm_key
2475
2476                         $ret = q(
2477                                 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2478                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2479                                 intval($importer["uid"]),
2480                                 intval($contact_record["id"]),
2481                                 0,
2482                                 0,
2483                                 dbesc(t("Sharing notification from Diaspora network")),
2484                                 dbesc($hash),
2485                                 dbesc(datetime_convert())
2486                         );
2487                 } else {
2488                         // automatic friend approval
2489
2490                         logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2491
2492                         Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2493
2494                         // technically they are sharing with us (CONTACT_IS_SHARING),
2495                         // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2496                         // we are going to change the relationship and make them a follower.
2497
2498                         if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2499                                 $new_relation = CONTACT_IS_FRIEND;
2500                         } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2501                                 $new_relation = CONTACT_IS_SHARING;
2502                         } else {
2503                                 $new_relation = CONTACT_IS_FOLLOWER;
2504                         }
2505
2506                         $r = q(
2507                                 "UPDATE `contact` SET `rel` = %d,
2508                                 `name-date` = '%s',
2509                                 `uri-date` = '%s',
2510                                 `blocked` = 0,
2511                                 `pending` = 0,
2512                                 `writable` = 1
2513                                 WHERE `id` = %d
2514                                 ",
2515                                 intval($new_relation),
2516                                 dbesc(datetime_convert()),
2517                                 dbesc(datetime_convert()),
2518                                 intval($contact_record["id"])
2519                         );
2520
2521                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2522                         if ($u) {
2523                                 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2524                                 $ret = self::sendShare($u[0], $contact_record);
2525
2526                                 // Send the profile data, maybe it weren't transmitted before
2527                                 self::sendProfile($importer["uid"], array($contact_record));
2528                         }
2529                 }
2530
2531                 return true;
2532         }
2533
2534         /**
2535          * @brief Fetches a message with a given guid
2536          *
2537          * @param string $guid        message guid
2538          * @param string $orig_author handle of the original post
2539          * @param string $author      handle of the sharer
2540          *
2541          * @return array The fetched item
2542          */
2543         private static function originalItem($guid, $orig_author, $author)
2544         {
2545                 // Do we already have this item?
2546                 $r = q(
2547                         "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2548                                 `author-name`, `author-link`, `author-avatar`
2549                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2550                         dbesc($guid)
2551                 );
2552
2553                 if (DBM::is_result($r)) {
2554                         logger("reshared message ".$guid." already exists on system.");
2555
2556                         // Maybe it is already a reshared item?
2557                         // Then refetch the content, if it is a reshare from a reshare.
2558                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2559                         if (self::isReshare($r[0]["body"], true)) {
2560                                 $r = array();
2561                         } elseif (self::isReshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2562                                 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2563
2564                                 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2565
2566                                 // Add OEmbed and other information to the body
2567                                 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2568
2569                                 return $r[0];
2570                         } else {
2571                                 return $r[0];
2572                         }
2573                 }
2574
2575                 if (!DBM::is_result($r)) {
2576                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2577                         logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2578                         $item_id = self::storeByGuid($guid, $server);
2579
2580                         if (!$item_id) {
2581                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2582                                 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2583                                 $item_id = self::storeByGuid($guid, $server);
2584                         }
2585
2586                         if ($item_id) {
2587                                 $r = q(
2588                                         "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2589                                                 `author-name`, `author-link`, `author-avatar`
2590                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2591                                         intval($item_id)
2592                                 );
2593
2594                                 if (DBM::is_result($r)) {
2595                                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2596                                         if (self::isReshare($r[0]["body"], false)) {
2597                                                 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2598                                                 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2599                                         }
2600
2601                                         return $r[0];
2602                                 }
2603                         }
2604                 }
2605                 return false;
2606         }
2607
2608         /**
2609          * @brief Processes a reshare message
2610          *
2611          * @param array  $importer Array of the importer user
2612          * @param object $data     The message object
2613          * @param string $xml      The original XML of the message
2614          *
2615          * @return int the message id
2616          */
2617         private static function receiveReshare($importer, $data, $xml)
2618         {
2619                 $author = notags(unxmlify($data->author));
2620                 $guid = notags(unxmlify($data->guid));
2621                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2622                 $root_author = notags(unxmlify($data->root_author));
2623                 $root_guid = notags(unxmlify($data->root_guid));
2624                 /// @todo handle unprocessed property "provider_display_name"
2625                 $public = notags(unxmlify($data->public));
2626
2627                 $contact = self::allowedContactByHandle($importer, $author, false);
2628                 if (!$contact) {
2629                         return false;
2630                 }
2631
2632                 $message_id = self::messageExists($importer["uid"], $guid);
2633                 if ($message_id) {
2634                         return true;
2635                 }
2636
2637                 $original_item = self::originalItem($root_guid, $root_author, $author);
2638                 if (!$original_item) {
2639                         return false;
2640                 }
2641
2642                 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2643
2644                 $datarray = array();
2645
2646                 $datarray["uid"] = $importer["uid"];
2647                 $datarray["contact-id"] = $contact["id"];
2648                 $datarray["network"]  = NETWORK_DIASPORA;
2649
2650                 $datarray["author-name"] = $contact["name"];
2651                 $datarray["author-link"] = $contact["url"];
2652                 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2653
2654                 $datarray["owner-name"] = $datarray["author-name"];
2655                 $datarray["owner-link"] = $datarray["author-link"];
2656                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2657
2658                 $datarray["guid"] = $guid;
2659                 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2660
2661                 $datarray["verb"] = ACTIVITY_POST;
2662                 $datarray["gravity"] = GRAVITY_PARENT;
2663
2664                 $datarray["protocol"] = PROTOCOL_DIASPORA;
2665                 $datarray["source"] = $xml;
2666
2667                 $prefix = share_header(
2668                         $original_item["author-name"],
2669                         $original_item["author-link"],
2670                         $original_item["author-avatar"],
2671                         $original_item["guid"],
2672                         $original_item["created"],
2673                         $orig_url
2674                 );
2675                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2676
2677                 $datarray["tag"] = $original_item["tag"];
2678                 $datarray["app"]  = $original_item["app"];
2679
2680                 $datarray["plink"] = self::plink($author, $guid);
2681                 $datarray["private"] = (($public == "false") ? 1 : 0);
2682                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2683
2684                 $datarray["object-type"] = $original_item["object-type"];
2685
2686                 self::fetchGuid($datarray);
2687                 $message_id = item_store($datarray);
2688
2689                 if ($message_id) {
2690                         logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2691                         return true;
2692                 } else {
2693                         return false;
2694                 }
2695         }
2696
2697         /**
2698          * @brief Processes retractions
2699          *
2700          * @param array  $importer Array of the importer user
2701          * @param array  $contact  The contact of the item owner
2702          * @param object $data     The message object
2703          *
2704          * @return bool success
2705          */
2706         private static function itemRetraction($importer, $contact, $data)
2707         {
2708                 $author = notags(unxmlify($data->author));
2709                 $target_guid = notags(unxmlify($data->target_guid));
2710                 $target_type = notags(unxmlify($data->target_type));
2711
2712                 $person = self::personByHandle($author);
2713                 if (!is_array($person)) {
2714                         logger("unable to find author detail for ".$author);
2715                         return false;
2716                 }
2717
2718                 if (empty($contact["url"])) {
2719                         $contact["url"] = $person["url"];
2720                 }
2721
2722                 // Fetch items that are about to be deleted
2723                 $fields = array('uid', 'id', 'parent', 'parent-uri', 'author-link');
2724
2725                 // When we receive a public retraction, we delete every item that we find.
2726                 if ($importer['uid'] == 0) {
2727                         $condition = array("`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid);
2728                 } else {
2729                         $condition = array("`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']);
2730                 }
2731                 $r = dba::select('item', $fields, $condition);
2732                 if (!DBM::is_result($r)) {
2733                         logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2734                         return false;
2735                 }
2736
2737                 while ($item = dba::fetch($r)) {
2738                         // Fetch the parent item
2739                         $parent = dba::select('item', array('author-link', 'origin'), array('id' => $item["parent"]), array('limit' => 1));
2740
2741                         // Only delete it if the parent author really fits
2742                         if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2743                                 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2744                                 continue;
2745                         }
2746
2747                         // Currently we don't have a central deletion function that we could use in this case.
2748                         // The function "item_drop" doesn't work for that case
2749                         dba::update(
2750                                 'item',
2751                                 array(
2752                                         'deleted' => true,
2753                                         'title' => '',
2754                                         'body' => '',
2755                                         'edited' => datetime_convert(),
2756                                         'changed' => datetime_convert()),
2757                                 array('id' => $item["id"])
2758                         );
2759
2760                         // Delete the thread - if it is a starting post and not a comment
2761                         if ($target_type != 'Comment') {
2762                                 delete_thread($item["id"], $item["parent-uri"]);
2763                         }
2764
2765                         logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2766
2767                         // Now check if the retraction needs to be relayed by us
2768                         if ($parent["origin"]) {
2769                                 // notify others
2770                                 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2771                         }
2772                 }
2773
2774                 return true;
2775         }
2776
2777         /**
2778          * @brief Receives retraction messages
2779          *
2780          * @param array  $importer Array of the importer user
2781          * @param string $sender   The sender of the message
2782          * @param object $data     The message object
2783          *
2784          * @return bool Success
2785          */
2786         private static function receiveRetraction($importer, $sender, $data)
2787         {
2788                 $target_type = notags(unxmlify($data->target_type));
2789
2790                 $contact = self::contactByHandle($importer["uid"], $sender);
2791                 if (!$contact && (in_array($target_type, array("Contact", "Person")))) {
2792                         logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2793                         return false;
2794                 }
2795
2796                 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2797
2798                 switch ($target_type) {
2799                         case "Comment":
2800                         case "Like":
2801                         case "Post":
2802                         case "Reshare":
2803                         case "StatusMessage":
2804                                 return self::itemRetraction($importer, $contact, $data);
2805
2806                         case "Contact":
2807                         case "Person":
2808                                 /// @todo What should we do with an "unshare"?
2809                                 // Removing the contact isn't correct since we still can read the public items
2810                                 Contact::remove($contact["id"]);
2811                                 return true;
2812
2813                         default:
2814                                 logger("Unknown target type ".$target_type);
2815                                 return false;
2816                 }
2817                 return true;
2818         }
2819
2820         /**
2821          * @brief Receives status messages
2822          *
2823          * @param array  $importer Array of the importer user
2824          * @param object $data     The message object
2825          * @param string $xml      The original XML of the message
2826          *
2827          * @return int The message id of the newly created item
2828          */
2829         private static function receiveStatusMessage($importer, $data, $xml)
2830         {
2831                 $author = notags(unxmlify($data->author));
2832                 $guid = notags(unxmlify($data->guid));
2833                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2834                 $public = notags(unxmlify($data->public));
2835                 $text = unxmlify($data->text);
2836                 $provider_display_name = notags(unxmlify($data->provider_display_name));
2837
2838                 $contact = self::allowedContactByHandle($importer, $author, false);
2839                 if (!$contact) {
2840                         return false;
2841                 }
2842
2843                 $message_id = self::messageExists($importer["uid"], $guid);
2844                 if ($message_id) {
2845                         return true;
2846                 }
2847
2848                 $address = array();
2849                 if ($data->location) {
2850                         foreach ($data->location->children() as $fieldname => $data) {
2851                                 $address[$fieldname] = notags(unxmlify($data));
2852                         }
2853                 }
2854
2855                 $body = diaspora2bb($text);
2856
2857                 $datarray = array();
2858
2859                 // Attach embedded pictures to the body
2860                 if ($data->photo) {
2861                         foreach ($data->photo as $photo) {
2862                                 $body = "[img]".unxmlify($photo->remote_photo_path).
2863                                         unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2864                         }
2865
2866                         $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2867                 } else {
2868                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2869
2870                         // Add OEmbed and other information to the body
2871                         if (!self::isRedmatrix($contact["url"])) {
2872                                 $body = add_page_info_to_body($body, false, true);
2873                         }
2874                 }
2875
2876                 /// @todo enable support for polls
2877                 //if ($data->poll) {
2878                 //      foreach ($data->poll AS $poll)
2879                 //              print_r($poll);
2880                 //      die("poll!\n");
2881                 //}
2882
2883                 /// @todo enable support for events
2884
2885                 $datarray["uid"] = $importer["uid"];
2886                 $datarray["contact-id"] = $contact["id"];
2887                 $datarray["network"] = NETWORK_DIASPORA;
2888
2889                 $datarray["author-name"] = $contact["name"];
2890                 $datarray["author-link"] = $contact["url"];
2891                 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2892
2893                 $datarray["owner-name"] = $datarray["author-name"];
2894                 $datarray["owner-link"] = $datarray["author-link"];
2895                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2896
2897                 $datarray["guid"] = $guid;
2898                 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2899
2900                 $datarray["verb"] = ACTIVITY_POST;
2901                 $datarray["gravity"] = GRAVITY_PARENT;
2902
2903                 $datarray["protocol"] = PROTOCOL_DIASPORA;
2904                 $datarray["source"] = $xml;
2905
2906                 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2907
2908                 if ($provider_display_name != "") {
2909                         $datarray["app"] = $provider_display_name;
2910                 }
2911
2912                 $datarray["plink"] = self::plink($author, $guid);
2913                 $datarray["private"] = (($public == "false") ? 1 : 0);
2914                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2915
2916                 if (isset($address["address"])) {
2917                         $datarray["location"] = $address["address"];
2918                 }
2919
2920                 if (isset($address["lat"]) && isset($address["lng"])) {
2921                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
2922                 }
2923
2924                 self::fetchGuid($datarray);
2925                 $message_id = item_store($datarray);
2926
2927                 if ($message_id) {
2928                         logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2929                         return true;
2930                 } else {
2931                         return false;
2932                 }
2933         }
2934
2935         /* ************************************************************************************** *
2936          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2937          * ************************************************************************************** */
2938
2939         /**
2940          * @brief returnes the handle of a contact
2941          *
2942          * @param array $contact contact array
2943          *
2944          * @return string the handle in the format user@domain.tld
2945          */
2946         private static function myHandle($contact)
2947         {
2948                 if ($contact["addr"] != "") {
2949                         return $contact["addr"];
2950                 }
2951
2952                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2953                 // So - just in case - we build the the address here.
2954                 if ($contact["nickname"] != "") {
2955                         $nick = $contact["nickname"];
2956                 } else {
2957                         $nick = $contact["nick"];
2958                 }
2959
2960                 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
2961         }
2962
2963
2964         /**
2965          * @brief Creates the data for a private message in the new format
2966          *
2967          * @param string $msg     The message that is to be transmitted
2968          * @param array  $user    The record of the sender
2969          * @param array  $contact Target of the communication
2970          * @param string $prvkey  The private key of the sender
2971          * @param string $pubkey  The public key of the receiver
2972          *
2973          * @return string The encrypted data
2974          */
2975         public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
2976         {
2977                 logger("Message: ".$msg, LOGGER_DATA);
2978
2979                 // without a public key nothing will work
2980                 if (!$pubkey) {
2981                         logger("pubkey missing: contact id: ".$contact["id"]);
2982                         return false;
2983                 }
2984
2985                 $aes_key = openssl_random_pseudo_bytes(32);
2986                 $b_aes_key = base64_encode($aes_key);
2987                 $iv = openssl_random_pseudo_bytes(16);
2988                 $b_iv = base64_encode($iv);
2989
2990                 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
2991
2992                 $json = json_encode(array("iv" => $b_iv, "key" => $b_aes_key));
2993
2994                 $encrypted_key_bundle = "";
2995                 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
2996
2997                 $json_object = json_encode(
2998                         array("aes_key" => base64_encode($encrypted_key_bundle),
2999                                         "encrypted_magic_envelope" => base64_encode($ciphertext))
3000                 );
3001
3002                 return $json_object;
3003         }
3004
3005         /**
3006          * @brief Creates the envelope for the "fetch" endpoint and for the new format
3007          *
3008          * @param string $msg  The message that is to be transmitted
3009          * @param array  $user The record of the sender
3010          *
3011          * @return string The envelope
3012          */
3013         public static function buildMagicEnvelope($msg, $user)
3014         {
3015                 $b64url_data = base64url_encode($msg);
3016                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
3017
3018                 $key_id = base64url_encode(self::myHandle($user));
3019                 $type = "application/xml";
3020                 $encoding = "base64url";
3021                 $alg = "RSA-SHA256";
3022                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3023
3024                 // Fallback if the private key wasn't transmitted in the expected field
3025                 if ($user['uprvkey'] == "") {
3026                         $user['uprvkey'] = $user['prvkey'];
3027                 }
3028
3029                 $signature = rsa_sign($signable_data, $user["uprvkey"]);
3030                 $sig = base64url_encode($signature);
3031
3032                 $xmldata = array("me:env" => array("me:data" => $data,
3033                                                         "@attributes" => array("type" => $type),
3034                                                         "me:encoding" => $encoding,
3035                                                         "me:alg" => $alg,
3036                                                         "me:sig" => $sig,
3037                                                         "@attributes2" => array("key_id" => $key_id)));
3038
3039                 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
3040
3041                 return XML::fromArray($xmldata, $xml, false, $namespaces);
3042         }
3043
3044         /**
3045          * @brief Create the envelope for a message
3046          *
3047          * @param string $msg     The message that is to be transmitted
3048          * @param array  $user    The record of the sender
3049          * @param array  $contact Target of the communication
3050          * @param string $prvkey  The private key of the sender
3051          * @param string $pubkey  The public key of the receiver
3052          * @param bool   $public  Is the message public?
3053          *
3054          * @return string The message that will be transmitted to other servers
3055          */
3056         private static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3057         {
3058                 // The message is put into an envelope with the sender's signature
3059                 $envelope = self::buildMagicEnvelope($msg, $user);
3060
3061                 // Private messages are put into a second envelope, encrypted with the receivers public key
3062                 if (!$public) {
3063                         $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3064                 }
3065
3066                 return $envelope;
3067         }
3068
3069         /**
3070          * @brief Creates a signature for a message
3071          *
3072          * @param array $owner   the array of the owner of the message
3073          * @param array $message The message that is to be signed
3074          *
3075          * @return string The signature
3076          */
3077         private static function signature($owner, $message)
3078         {
3079                 $sigmsg = $message;
3080                 unset($sigmsg["author_signature"]);
3081                 unset($sigmsg["parent_author_signature"]);
3082
3083                 $signed_text = implode(";", $sigmsg);
3084
3085                 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3086         }
3087
3088         /**
3089          * @brief Transmit a message to a target server
3090          *
3091          * @param array  $owner        the array of the item owner
3092          * @param array  $contact      Target of the communication
3093          * @param string $envelope     The message that is to be transmitted
3094          * @param bool   $public_batch Is it a public post?
3095          * @param bool   $queue_run    Is the transmission called from the queue?
3096          * @param string $guid         message guid
3097          *
3098          * @return int Result of the transmission
3099          */
3100         public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "")
3101         {
3102                 $a = get_app();
3103
3104                 $enabled = intval(Config::get("system", "diaspora_enabled"));
3105                 if (!$enabled) {
3106                         return 200;
3107                 }
3108
3109                 $logid = random_string(4);
3110                 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
3111                 if (!$dest_url) {
3112                         logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3113                         return 0;
3114                 }
3115
3116                 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3117
3118                 if (!$queue_run && was_recently_delayed($contact["id"])) {
3119                         $return_code = 0;
3120                 } else {
3121                         if (!intval(Config::get("system", "diaspora_test"))) {
3122                                 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3123
3124                                 post_url($dest_url."/", $envelope, array("Content-Type: ".$content_type));
3125                                 $return_code = $a->get_curl_code();
3126                         } else {
3127                                 logger("test_mode");
3128                                 return 200;
3129                         }
3130                 }
3131
3132                 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
3133
3134                 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3135                         logger("queue message");
3136
3137                         $r = q(
3138                                 "SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
3139                                 intval($contact["id"]),
3140                                 dbesc(NETWORK_DIASPORA),
3141                                 dbesc($envelope),
3142                                 intval($public_batch)
3143                         );
3144                         if ($r) {
3145                                 logger("add_to_queue ignored - identical item already in queue");
3146                         } else {
3147                                 // queue message for redelivery
3148                                 add_to_queue($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch);
3149
3150                                 // The message could not be delivered. We mark the contact as "dead"
3151                                 Contact::markForArchival($contact);
3152                         }
3153                 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3154                         // We successfully delivered a message, the contact is alive
3155                         Contact::unmarkForArchival($contact);
3156                 }
3157
3158                 return(($return_code) ? $return_code : (-1));
3159         }
3160
3161
3162         /**
3163          * @brief Build the post xml
3164          *
3165          * @param string $type    The message type
3166          * @param array  $message The message data
3167          *
3168          * @return string The post XML
3169          */
3170         public static function buildPostXml($type, $message)
3171         {
3172                 $data = array($type => $message);
3173
3174                 return XML::fromArray($data, $xml);
3175         }
3176
3177         /**
3178          * @brief Builds and transmit messages
3179          *
3180          * @param array  $owner        the array of the item owner
3181          * @param array  $contact      Target of the communication
3182          * @param string $type         The message type
3183          * @param array  $message      The message data
3184          * @param bool   $public_batch Is it a public post?
3185          * @param string $guid         message guid
3186          * @param bool   $spool        Should the transmission be spooled or transmitted?
3187          *
3188          * @return int Result of the transmission
3189          */
3190         private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3191         {
3192                 $msg = self::buildPostXml($type, $message);
3193
3194                 logger('message: '.$msg, LOGGER_DATA);
3195                 logger('send guid '.$guid, LOGGER_DEBUG);
3196
3197                 // Fallback if the private key wasn't transmitted in the expected field
3198                 if ($owner['uprvkey'] == "") {
3199                         $owner['uprvkey'] = $owner['prvkey'];
3200                 }
3201
3202                 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3203
3204                 if ($spool) {
3205                         add_to_queue($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch);
3206                         return true;
3207                 } else {
3208                         $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3209                 }
3210
3211                 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
3212
3213                 return $return_code;
3214         }
3215
3216         /**
3217          * @brief sends an account migration
3218          *
3219          * @param array $owner   the array of the item owner
3220          * @param array $contact Target of the communication
3221          * @param int   $uid     User ID
3222          *
3223          * @return int The result of the transmission
3224          */
3225         public static function sendAccountMigration($owner, $contact, $uid)
3226         {
3227                 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3228                 $profile = self::createProfileData($uid);
3229
3230                 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3231                 $signature = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3232
3233                 $message = array("author" => $old_handle,
3234                                 "profile" => $profile,
3235                                 "signature" => $signature);
3236
3237                 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3238
3239                 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3240         }
3241
3242         /**
3243          * @brief Sends a "share" message
3244          *
3245          * @param array $owner   the array of the item owner
3246          * @param array $contact Target of the communication
3247          *
3248          * @return int The result of the transmission
3249          */
3250         public static function sendShare($owner, $contact)
3251         {
3252                 /**
3253                  * @todo support the different possible combinations of "following" and "sharing"
3254                  * Currently, Diaspora only interprets the "sharing" field
3255                  *
3256                  * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3257                  */
3258
3259                 /*
3260                 switch ($contact["rel"]) {
3261                         case CONTACT_IS_FRIEND:
3262                                 $following = true;
3263                                 $sharing = true;
3264                         case CONTACT_IS_SHARING:
3265                                 $following = false;
3266                                 $sharing = true;
3267                         case CONTACT_IS_FOLLOWER:
3268                                 $following = true;
3269                                 $sharing = false;
3270                 }
3271                 */
3272
3273                 $message = array("author" => self::myHandle($owner),
3274                                 "recipient" => $contact["addr"],
3275                                 "following" => "true",
3276                                 "sharing" => "true");
3277
3278                 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3279
3280                 return self::buildAndTransmit($owner, $contact, "contact", $message);
3281         }
3282
3283         /**
3284          * @brief sends an "unshare"
3285          *
3286          * @param array $owner   the array of the item owner
3287          * @param array $contact Target of the communication
3288          *
3289          * @return int The result of the transmission
3290          */
3291         public static function sendUnshare($owner, $contact)
3292         {
3293                 $message = array("author" => self::myHandle($owner),
3294                                 "recipient" => $contact["addr"],
3295                                 "following" => "false",
3296                                 "sharing" => "false");
3297
3298                 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3299
3300                 return self::buildAndTransmit($owner, $contact, "contact", $message);
3301         }
3302
3303         /**
3304          * @brief Checks a message body if it is a reshare
3305          *
3306          * @param string $body     The message body that is to be check
3307          * @param bool   $complete Should it be a complete check or a simple check?
3308          *
3309          * @return array|bool Reshare details or "false" if no reshare
3310          */
3311         public static function isReshare($body, $complete = true)
3312         {
3313                 $body = trim($body);
3314
3315                 // Skip if it isn't a pure repeated messages
3316                 // Does it start with a share?
3317                 if ((strpos($body, "[share") > 0) && $complete) {
3318                         return(false);
3319                 }
3320
3321                 // Does it end with a share?
3322                 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3323                         return(false);
3324                 }
3325
3326                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3327                 // Skip if there is no shared message in there
3328                 if ($body == $attributes) {
3329                         return(false);
3330                 }
3331
3332                 // If we don't do the complete check we quit here
3333                 if (!$complete) {
3334                         return true;
3335                 }
3336
3337                 $guid = "";
3338                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3339                 if ($matches[1] != "") {
3340                         $guid = $matches[1];
3341                 }
3342
3343                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3344                 if ($matches[1] != "") {
3345                         $guid = $matches[1];
3346                 }
3347
3348                 if ($guid != "") {
3349                         $r = q(
3350                                 "SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3351                                 dbesc($guid),
3352                                 NETWORK_DFRN,
3353                                 NETWORK_DIASPORA
3354                         );
3355                         if ($r) {
3356                                 $ret= array();
3357                                 $ret["root_handle"] = self::handleFromContact($r[0]["contact-id"]);
3358                                 $ret["root_guid"] = $guid;
3359                                 return($ret);
3360                         }
3361                 }
3362
3363                 $profile = "";
3364                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3365                 if ($matches[1] != "") {
3366                         $profile = $matches[1];
3367                 }
3368
3369                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3370                 if ($matches[1] != "") {
3371                         $profile = $matches[1];
3372                 }
3373
3374                 $ret= array();
3375
3376                 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3377                 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == "")) {
3378                         return(false);
3379                 }
3380
3381                 $link = "";
3382                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3383                 if ($matches[1] != "") {
3384                         $link = $matches[1];
3385                 }
3386
3387                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3388                 if ($matches[1] != "") {
3389                         $link = $matches[1];
3390                 }
3391
3392                 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3393                 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == "")) {
3394                         return(false);
3395                 }
3396
3397                 return($ret);
3398         }
3399
3400         /**
3401          * @brief Create an event array
3402          *
3403          * @param integer $event_id The id of the event
3404          *
3405          * @return array with event data
3406          */
3407         private static function buildEvent($event_id)
3408         {
3409                 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3410                 if (!DBM::is_result($r)) {
3411                         return array();
3412                 }
3413
3414                 $event = $r[0];
3415
3416                 $eventdata = array();
3417
3418                 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3419                 if (!DBM::is_result($r)) {
3420                         return array();
3421                 }
3422
3423                 $user = $r[0];
3424
3425                 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3426                 if (!DBM::is_result($r)) {
3427                         return array();
3428                 }
3429
3430                 $owner = $r[0];
3431
3432                 $eventdata['author'] = self::myHandle($owner);
3433
3434                 if ($event['guid']) {
3435                         $eventdata['guid'] = $event['guid'];
3436                 }
3437
3438                 $mask = 'Y-m-d\TH:i:s\Z';
3439
3440                 /// @todo - establish "all day" events in Friendica
3441                 $eventdata["all_day"] = "false";
3442
3443                 if (!$event['adjust']) {
3444                         $eventdata['timezone'] = $user['timezone'];
3445
3446                         if ($eventdata['timezone'] == "") {
3447                                 $eventdata['timezone'] = 'UTC';
3448                         }
3449                 }
3450
3451                 if ($event['start']) {
3452                         $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3453                 }
3454                 if ($event['finish'] && !$event['nofinish']) {
3455                         $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3456                 }
3457                 if ($event['summary']) {
3458                         $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3459                 }
3460                 if ($event['desc']) {
3461                         $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3462                 }
3463                 if ($event['location']) {
3464                         $location = array();
3465                         $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3466                         $location["lat"] = 0;
3467                         $location["lng"] = 0;
3468                         $eventdata['location'] = $location;
3469                 }
3470
3471                 return $eventdata;
3472         }
3473
3474         /**
3475          * @brief Create a post (status message or reshare)
3476          *
3477          * @param array $item  The item that will be exported
3478          * @param array $owner the array of the item owner
3479          *
3480          * @return array
3481          * 'type' -> Message type ("status_message" or "reshare")
3482          * 'message' -> Array of XML elements of the status
3483          */
3484         public static function buildStatus($item, $owner)
3485         {
3486                 $cachekey = "diaspora:buildStatus:".$item['guid'];
3487
3488                 $result = Cache::get($cachekey);
3489                 if (!is_null($result)) {
3490                         return $result;
3491                 }
3492
3493                 $myaddr = self::myHandle($owner);
3494
3495                 $public = (($item["private"]) ? "false" : "true");
3496
3497                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3498
3499                 // Detect a share element and do a reshare
3500                 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3501                         $message = array("author" => $myaddr,
3502                                         "guid" => $item["guid"],
3503                                         "created_at" => $created,
3504                                         "root_author" => $ret["root_handle"],
3505                                         "root_guid" => $ret["root_guid"],
3506                                         "provider_display_name" => $item["app"],
3507                                         "public" => $public);
3508
3509                         $type = "reshare";
3510                 } else {
3511                         $title = $item["title"];
3512                         $body = $item["body"];
3513
3514                         // convert to markdown
3515                         $body = html_entity_decode(bb2diaspora($body));
3516
3517                         // Adding the title
3518                         if (strlen($title)) {
3519                                 $body = "## ".html_entity_decode($title)."\n\n".$body;
3520                         }
3521
3522                         if ($item["attach"]) {
3523                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3524                                 if (cnt) {
3525                                         $body .= "\n".t("Attachments:")."\n";
3526                                         foreach ($matches as $mtch) {
3527                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3528                                         }
3529                                 }
3530                         }
3531
3532                         $location = array();
3533
3534                         if ($item["location"] != "")
3535                                 $location["address"] = $item["location"];
3536
3537                         if ($item["coord"] != "") {
3538                                 $coord = explode(" ", $item["coord"]);
3539                                 $location["lat"] = $coord[0];
3540                                 $location["lng"] = $coord[1];
3541                         }
3542
3543                         $message = array("author" => $myaddr,
3544                                         "guid" => $item["guid"],
3545                                         "created_at" => $created,
3546                                         "public" => $public,
3547                                         "text" => $body,
3548                                         "provider_display_name" => $item["app"],
3549                                         "location" => $location);
3550
3551                         // Diaspora rejects messages when they contain a location without "lat" or "lng"
3552                         if (!isset($location["lat"]) || !isset($location["lng"])) {
3553                                 unset($message["location"]);
3554                         }
3555
3556                         if ($item['event-id'] > 0) {
3557                                 $event = self::buildEvent($item['event-id']);
3558                                 if (count($event)) {
3559                                         $message['event'] = $event;
3560
3561                                         /// @todo Once Diaspora supports it, we will remove the body
3562                                         // $message['text'] = '';
3563                                 }
3564                         }
3565
3566                         $type = "status_message";
3567                 }
3568
3569                 $msg = array("type" => $type, "message" => $message);
3570
3571                 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3572
3573                 return $msg;
3574         }
3575
3576         /**
3577          * @brief Sends a post
3578          *
3579          * @param array $item         The item that will be exported
3580          * @param array $owner        the array of the item owner
3581          * @param array $contact      Target of the communication
3582          * @param bool  $public_batch Is it a public post?
3583          *
3584          * @return int The result of the transmission
3585          */
3586         public static function sendStatus($item, $owner, $contact, $public_batch = false)
3587         {
3588                 $status = self::buildStatus($item, $owner);
3589
3590                 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3591         }
3592
3593         /**
3594          * @brief Creates a "like" object
3595          *
3596          * @param array $item  The item that will be exported
3597          * @param array $owner the array of the item owner
3598          *
3599          * @return array The data for a "like"
3600          */
3601         private static function constructLike($item, $owner)
3602         {
3603                 $p = q(
3604                         "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3605                         dbesc($item["thr-parent"])
3606                 );
3607                 if (!DBM::is_result($p)) {
3608                         return false;
3609                 }
3610
3611                 $parent = $p[0];
3612
3613                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3614                 if ($item['verb'] === ACTIVITY_LIKE) {
3615                         $positive = "true";
3616                 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3617                         $positive = "false";
3618                 }
3619
3620                 return(array("author" => self::myHandle($owner),
3621                                 "guid" => $item["guid"],
3622                                 "parent_guid" => $parent["guid"],
3623                                 "parent_type" => $target_type,
3624                                 "positive" => $positive,
3625                                 "author_signature" => ""));
3626         }
3627
3628         /**
3629          * @brief Creates an "EventParticipation" object
3630          *
3631          * @param array $item  The item that will be exported
3632          * @param array $owner the array of the item owner
3633          *
3634          * @return array The data for an "EventParticipation"
3635          */
3636         private static function constructAttend($item, $owner)
3637         {
3638                 $p = q(
3639                         "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3640                         dbesc($item["thr-parent"])
3641                 );
3642                 if (!DBM::is_result($p)) {
3643                         return false;
3644                 }
3645
3646                 $parent = $p[0];
3647
3648                 switch ($item['verb']) {
3649                         case ACTIVITY_ATTEND:
3650                                 $attend_answer = 'accepted';
3651                                 break;
3652                         case ACTIVITY_ATTENDNO:
3653                                 $attend_answer = 'declined';
3654                                 break;
3655                         case ACTIVITY_ATTENDMAYBE:
3656                                 $attend_answer = 'tentative';
3657                                 break;
3658                         default:
3659                                 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3660                                 return false;
3661                 }
3662
3663                 return(array("author" => self::myHandle($owner),
3664                                 "guid" => $item["guid"],
3665                                 "parent_guid" => $parent["guid"],
3666                                 "status" => $attend_answer,
3667                                 "author_signature" => ""));
3668         }
3669
3670         /**
3671          * @brief Creates the object for a comment
3672          *
3673          * @param array $item  The item that will be exported
3674          * @param array $owner the array of the item owner
3675          *
3676          * @return array The data for a comment
3677          */
3678         private static function constructComment($item, $owner)
3679         {
3680                 $cachekey = "diaspora:constructComment:".$item['guid'];
3681
3682                 $result = Cache::get($cachekey);
3683                 if (!is_null($result)) {
3684                         return $result;
3685                 }
3686
3687                 $p = q(
3688                         "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3689                         intval($item["parent"]),
3690                         intval($item["parent"])
3691                 );
3692
3693                 if (!DBM::is_result($p)) {
3694                         return false;
3695                 }
3696
3697                 $parent = $p[0];
3698
3699                 $text = html_entity_decode(bb2diaspora($item["body"]));
3700                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3701
3702                 $comment = array("author" => self::myHandle($owner),
3703                                 "guid" => $item["guid"],
3704                                 "created_at" => $created,
3705                                 "parent_guid" => $parent["guid"],
3706                                 "text" => $text,
3707                                 "author_signature" => "");
3708
3709                 // Send the thread parent guid only if it is a threaded comment
3710                 if ($item['thr-parent'] != $item['parent-uri']) {
3711                         $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3712                 }
3713
3714                 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3715
3716                 return($comment);
3717         }
3718
3719         /**
3720          * @brief Send a like or a comment
3721          *
3722          * @param array $item         The item that will be exported
3723          * @param array $owner        the array of the item owner
3724          * @param array $contact      Target of the communication
3725          * @param bool  $public_batch Is it a public post?
3726          *
3727          * @return int The result of the transmission
3728          */
3729         public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3730         {
3731                 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3732                         $message = self::constructAttend($item, $owner);
3733                         $type = "event_participation";
3734                 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3735                         $message = self::constructLike($item, $owner);
3736                         $type = "like";
3737                 } else {
3738                         $message = self::constructComment($item, $owner);
3739                         $type = "comment";
3740                 }
3741
3742                 if (!$message) {
3743                         return false;
3744                 }
3745
3746                 $message["author_signature"] = self::signature($owner, $message);
3747
3748                 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3749         }
3750
3751         /**
3752          * @brief Creates a message from a signature record entry
3753          *
3754          * @param array $item      The item that will be exported
3755          * @param array $signature The entry of the "sign" record
3756          *
3757          * @return string The message
3758          */
3759         private static function messageFromSignature($item, $signature)
3760         {
3761                 // Split the signed text
3762                 $signed_parts = explode(";", $signature['signed_text']);
3763
3764                 if ($item["deleted"]) {
3765                         $message = array("author" => $signature['signer'],
3766                                         "target_guid" => $signed_parts[0],
3767                                         "target_type" => $signed_parts[1]);
3768                 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3769                         $message = array("author" => $signed_parts[4],
3770                                         "guid" => $signed_parts[1],
3771                                         "parent_guid" => $signed_parts[3],
3772                                         "parent_type" => $signed_parts[2],
3773                                         "positive" => $signed_parts[0],
3774                                         "author_signature" => $signature['signature'],
3775                                         "parent_author_signature" => "");
3776                 } else {
3777                         // Remove the comment guid
3778                         $guid = array_shift($signed_parts);
3779
3780                         // Remove the parent guid
3781                         $parent_guid = array_shift($signed_parts);
3782
3783                         // Remove the handle
3784                         $handle = array_pop($signed_parts);
3785
3786                         // Glue the parts together
3787                         $text = implode(";", $signed_parts);
3788
3789                         $message = array("author" => $handle,
3790                                         "guid" => $guid,
3791                                         "parent_guid" => $parent_guid,
3792                                         "text" => implode(";", $signed_parts),
3793                                         "author_signature" => $signature['signature'],
3794                                         "parent_author_signature" => "");
3795                 }
3796                 return $message;
3797         }
3798
3799         /**
3800          * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3801          *
3802          * @param array $item         The item that will be exported
3803          * @param array $owner        the array of the item owner
3804          * @param array $contact      Target of the communication
3805          * @param bool  $public_batch Is it a public post?
3806          *
3807          * @return int The result of the transmission
3808          */
3809         public static function sendRelay($item, $owner, $contact, $public_batch = false)
3810         {
3811                 if ($item["deleted"]) {
3812                         return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3813                 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3814                         $type = "like";
3815                 } else {
3816                         $type = "comment";
3817                 }
3818
3819                 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3820
3821                 // fetch the original signature
3822
3823                 $r = q(
3824                         "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3825                         intval($item["id"])
3826                 );
3827
3828                 if (!$r) {
3829                         logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3830                         return false;
3831                 }
3832
3833                 $signature = $r[0];
3834
3835                 // Old way - is used by the internal Friendica functions
3836                 /// @todo Change all signatur storing functions to the new format
3837                 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
3838                         $message = self::messageFromSignature($item, $signature);
3839                 } else {// New way
3840                         $msg = json_decode($signature['signed_text'], true);
3841
3842                         $message = array();
3843                         if (is_array($msg)) {
3844                                 foreach ($msg as $field => $data) {
3845                                         if (!$item["deleted"]) {
3846                                                 if ($field == "diaspora_handle") {
3847                                                         $field = "author";
3848                                                 }
3849                                                 if ($field == "target_type") {
3850                                                         $field = "parent_type";
3851                                                 }
3852                                         }
3853
3854                                         $message[$field] = $data;
3855                                 }
3856                         } else {
3857                                 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3858                         }
3859                 }
3860
3861                 $message["parent_author_signature"] = self::signature($owner, $message);
3862
3863                 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3864
3865                 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3866         }
3867
3868         /**
3869          * @brief Sends a retraction (deletion) of a message, like or comment
3870          *
3871          * @param array $item         The item that will be exported
3872          * @param array $owner        the array of the item owner
3873          * @param array $contact      Target of the communication
3874          * @param bool  $public_batch Is it a public post?
3875          * @param bool  $relay        Is the retraction transmitted from a relay?
3876          *
3877          * @return int The result of the transmission
3878          */
3879         public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
3880         {
3881                 $itemaddr = self::handleFromContact($item["contact-id"], $item["gcontact-id"]);
3882
3883                 $msg_type = "retraction";
3884
3885                 if ($item['id'] == $item['parent']) {
3886                         $target_type = "Post";
3887                 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3888                         $target_type = "Like";
3889                 } else {
3890                         $target_type = "Comment";
3891                 }
3892
3893                 $message = array("author" => $itemaddr,
3894                                 "target_guid" => $item['guid'],
3895                                 "target_type" => $target_type);
3896
3897                 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3898
3899                 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3900         }
3901
3902         /**
3903          * @brief Sends a mail
3904          *
3905          * @param array $item    The item that will be exported
3906          * @param array $owner   The owner
3907          * @param array $contact Target of the communication
3908          *
3909          * @return int The result of the transmission
3910          */
3911         public static function sendMail($item, $owner, $contact)
3912         {
3913                 $myaddr = self::myHandle($owner);
3914
3915                 $r = q(
3916                         "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3917                         intval($item["convid"]),
3918                         intval($item["uid"])
3919                 );
3920
3921                 if (!DBM::is_result($r)) {
3922                         logger("conversation not found.");
3923                         return;
3924                 }
3925                 $cnv = $r[0];
3926
3927                 $conv = array(
3928                         "author" => $cnv["creator"],
3929                         "guid" => $cnv["guid"],
3930                         "subject" => $cnv["subject"],
3931                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3932                         "participants" => $cnv["recips"]
3933                 );
3934
3935                 $body = bb2diaspora($item["body"]);
3936                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3937
3938                 $msg = array(
3939                         "author" => $myaddr,
3940                         "guid" => $item["guid"],
3941                         "conversation_guid" => $cnv["guid"],
3942                         "text" => $body,
3943                         "created_at" => $created,
3944                 );
3945
3946                 if ($item["reply"]) {
3947                         $message = $msg;
3948                         $type = "message";
3949                 } else {
3950                         $message = array(
3951                                         "author" => $cnv["creator"],
3952                                         "guid" => $cnv["guid"],
3953                                         "subject" => $cnv["subject"],
3954                                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3955                                         "participants" => $cnv["recips"],
3956                                         "message" => $msg);
3957
3958                         $type = "conversation";
3959                 }
3960
3961                 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
3962         }
3963
3964         /**
3965          * @brief Create profile data
3966          *
3967          * @param int $uid The user id
3968          *
3969          * @return array The profile data
3970          */
3971         private static function createProfileData($uid)
3972         {
3973                 $r = q(
3974                         "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3975                         FROM `profile`
3976                         INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3977                         INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3978                         WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3979                         intval($uid)
3980                 );
3981
3982                 if (!$r) {
3983                         return array();
3984                 }
3985
3986                 $profile = $r[0];
3987
3988                 $handle = $profile["addr"];
3989                 $first = ((strpos($profile['name'], ' ')
3990                         ? trim(substr($profile['name'], 0, strpos($profile['name'], ' '))) : $profile['name']));
3991                 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3992                 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3993                 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3994                 $small = System::baseUrl().'/photo/custom/50/'  .$profile['uid'].'.jpg';
3995                 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3996
3997                 if ($searchable === 'true') {
3998                         $dob = '1000-00-00';
3999
4000                         if (($profile['dob']) && ($profile['dob'] > '0001-01-01')) {
4001                                 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC', 'UTC', $profile['dob'],'m-d');
4002                         }
4003
4004                         $about = $profile['about'];
4005                         $about = strip_tags(bbcode($about));
4006
4007                         $location = Profile::formatLocation($profile);
4008                         $tags = '';
4009                         if ($profile['pub_keywords']) {
4010                                 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4011                                 $kw = str_replace('  ', ' ', $kw);
4012                                 $arr = explode(' ', $profile['pub_keywords']);
4013                                 if (count($arr)) {
4014                                         for ($x = 0; $x < 5; $x ++) {
4015                                                 if (trim($arr[$x])) {
4016                                                         $tags .= '#'. trim($arr[$x]) .' ';
4017                                                 }
4018                                         }
4019                                 }
4020                         }
4021                         $tags = trim($tags);
4022                 }
4023
4024                 return array("author" => $handle,
4025                                 "first_name" => $first,
4026                                 "last_name" => $last,
4027                                 "image_url" => $large,
4028                                 "image_url_medium" => $medium,
4029                                 "image_url_small" => $small,
4030                                 "birthday" => $dob,
4031                                 "gender" => $profile['gender'],
4032                                 "bio" => $about,
4033                                 "location" => $location,
4034                                 "searchable" => $searchable,
4035                                 "nsfw" => "false",
4036                                 "tag_string" => $tags);
4037         }
4038
4039         /**
4040          * @brief Sends profile data
4041          *
4042          * @param int  $uid    The user id
4043          * @param bool $recips optional, default false
4044          * @return void
4045          */
4046         public static function sendProfile($uid, $recips = false)
4047         {
4048                 if (!$uid) {
4049                         return;
4050                 }
4051
4052                 if (!$recips) {
4053                         $recips = q(
4054                                 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4055                                 AND `uid` = %d AND `rel` != %d",
4056                                 dbesc(NETWORK_DIASPORA),
4057                                 intval($uid),
4058                                 intval(CONTACT_IS_SHARING)
4059                         );
4060                 }
4061
4062                 if (!$recips) {
4063                         return;
4064                 }
4065
4066                 $message = self::createProfileData($uid);
4067
4068                 foreach ($recips as $recip) {
4069                         logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4070                         self::buildAndTransmit($profile, $recip, "profile", $message, false, "", true);
4071                 }
4072         }
4073
4074         /**
4075          * @brief Stores the signature for likes that are created on our system
4076          *
4077          * @param array $contact The contact array of the "like"
4078          * @param int   $post_id The post id of the "like"
4079          *
4080          * @return bool Success
4081          */
4082         public static function storeLikeSignature($contact, $post_id)
4083         {
4084                 // Is the contact the owner? Then fetch the private key
4085                 if (!$contact['self'] || ($contact['uid'] == 0)) {
4086                         logger("No owner post, so not storing signature", LOGGER_DEBUG);
4087                         return false;
4088                 }
4089
4090                 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4091                 if (!DBM::is_result($r)) {
4092                         return false;
4093                 }
4094
4095                 $contact["uprvkey"] = $r[0]['prvkey'];
4096
4097                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4098                 if (!DBM::is_result($r)) {
4099                         return false;
4100                 }
4101
4102                 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
4103                         return false;
4104                 }
4105
4106                 $message = self::constructLike($r[0], $contact);
4107                 $message["author_signature"] = self::signature($contact, $message);
4108
4109                 /*
4110                  * Now store the signature more flexible to dynamically support new fields.
4111                  * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4112                  */
4113                 dba::insert('sign', array('iid' => $post_id, 'signed_text' => json_encode($message)));
4114
4115                 logger('Stored diaspora like signature');
4116                 return true;
4117         }
4118
4119         /**
4120          * @brief Stores the signature for comments that are created on our system
4121          *
4122          * @param array  $item       The item array of the comment
4123          * @param array  $contact    The contact array of the item owner
4124          * @param string $uprvkey    The private key of the sender
4125          * @param int    $message_id The message id of the comment
4126          *
4127          * @return bool Success
4128          */
4129         public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4130         {
4131                 if ($uprvkey == "") {
4132                         logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4133                         return false;
4134                 }
4135
4136                 $contact["uprvkey"] = $uprvkey;
4137
4138                 $message = self::constructComment($item, $contact);
4139                 $message["author_signature"] = self::signature($contact, $message);
4140
4141                 /*
4142                  * Now store the signature more flexible to dynamically support new fields.
4143                  * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4144                  */
4145                 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($message)));
4146
4147                 logger('Stored diaspora comment signature');
4148                 return true;
4149         }
4150 }