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