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