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