]> git.mxchange.org Git - friendica.git/blob - include/diaspora2.php
Decode function is now there as well.
[friendica.git] / include / diaspora2.php
1 <?php
2 /**
3  * @file include/diaspora.php
4  * @brief The implementation of the diaspora protocol
5  */
6
7 require_once("include/items.php");
8 require_once("include/bb2diaspora.php");
9 require_once("include/Scrape.php");
10 require_once("include/Contact.php");
11 require_once("include/Photo.php");
12 require_once("include/socgraph.php");
13 require_once("include/group.php");
14 require_once("include/xml.php");
15 require_once("include/datetime.php");
16
17 /**
18  * @brief This class contain functions to create and send Diaspora XML files
19  *
20  */
21 class diaspora {
22
23         public static function relay_list() {
24
25                 $serverdata = get_config("system", "relay_server");
26                 if ($serverdata == "")
27                         return array();
28
29                 $relay = array();
30
31                 $servers = explode(",", $serverdata);
32
33                 foreach($servers AS $server) {
34                         $server = trim($server);
35                         $batch = $server."/receive/public";
36
37                         $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
38
39                         if (!$relais) {
40                                 $addr = "relay@".str_replace("http://", "", normalise_link($server));
41
42                                 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
43                                         VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
44                                         datetime_convert(),
45                                         dbesc($addr),
46                                         dbesc($addr),
47                                         dbesc($server),
48                                         dbesc(normalise_link($server)),
49                                         dbesc($batch),
50                                         dbesc(NETWORK_DIASPORA),
51                                         intval(CONTACT_IS_FOLLOWER),
52                                         dbesc(datetime_convert()),
53                                         dbesc(datetime_convert()),
54                                         dbesc(datetime_convert())
55                                 );
56
57                                 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
58                                 if ($relais)
59                                         $relay[] = $relais[0];
60                         } else
61                                 $relay[] = $relais[0];
62                 }
63
64                 return $relay;
65         }
66
67         function repair_signature($signature, $handle = "", $level = 1) {
68
69                 if ($signature == "")
70                         return ($signature);
71
72                 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
73                         $signature = base64_decode($signature);
74                         logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
75
76                         // Do a recursive call to be able to fix even multiple levels
77                         if ($level < 10)
78                                 $signature = self::repair_signature($signature, $handle, ++$level);
79                 }
80
81                 return($signature);
82         }
83
84         /**
85          * @brief: Decodes incoming Diaspora message
86          *
87          * @param array $importer from user table
88          * @param string $xml urldecoded Diaspora salmon
89          *
90          * @return array
91          * 'message' -> decoded Diaspora XML message
92          * 'author' -> author diaspora handle
93          * 'key' -> author public key (converted to pkcs#8)
94          */
95         function decode($importer, $xml) {
96
97                 $public = false;
98                 $basedom = parse_xml_string($xml);
99
100                 if (!is_object($basedom))
101                         return false;
102
103                 $children = $basedom->children('https://joindiaspora.com/protocol');
104
105                 if($children->header) {
106                         $public = true;
107                         $author_link = str_replace('acct:','',$children->header->author_id);
108                 } else {
109
110                         $encrypted_header = json_decode(base64_decode($children->encrypted_header));
111
112                         $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
113                         $ciphertext = base64_decode($encrypted_header->ciphertext);
114
115                         $outer_key_bundle = '';
116                         openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
117
118                         $j_outer_key_bundle = json_decode($outer_key_bundle);
119
120                         $outer_iv = base64_decode($j_outer_key_bundle->iv);
121                         $outer_key = base64_decode($j_outer_key_bundle->key);
122
123                         $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
124
125
126                         $decrypted = pkcs5_unpad($decrypted);
127
128                         /**
129                          * $decrypted now contains something like
130                          *
131                          *  <decrypted_header>
132                          *     <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
133                          *     <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
134                          *     <author_id>galaxor@diaspora.priateship.org</author_id>
135                          *  </decrypted_header>
136                          */
137
138                         logger('decrypted: '.$decrypted, LOGGER_DEBUG);
139                         $idom = parse_xml_string($decrypted,false);
140
141                         $inner_iv = base64_decode($idom->iv);
142                         $inner_aes_key = base64_decode($idom->aes_key);
143
144                         $author_link = str_replace('acct:','',$idom->author_id);
145                 }
146
147                 $dom = $basedom->children(NAMESPACE_SALMON_ME);
148
149                 // figure out where in the DOM tree our data is hiding
150
151                 if($dom->provenance->data)
152                         $base = $dom->provenance;
153                 elseif($dom->env->data)
154                         $base = $dom->env;
155                 elseif($dom->data)
156                         $base = $dom;
157
158                 if (!$base) {
159                         logger('unable to locate salmon data in xml');
160                         http_status_exit(400);
161                 }
162
163
164                 // Stash the signature away for now. We have to find their key or it won't be good for anything.
165                 $signature = base64url_decode($base->sig);
166
167                 // unpack the  data
168
169                 // strip whitespace so our data element will return to one big base64 blob
170                 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
171
172
173                 // stash away some other stuff for later
174
175                 $type = $base->data[0]->attributes()->type[0];
176                 $keyhash = $base->sig[0]->attributes()->keyhash[0];
177                 $encoding = $base->encoding;
178                 $alg = $base->alg;
179
180
181                 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
182
183
184                 // decode the data
185                 $data = base64url_decode($data);
186
187
188                 if($public)
189                         $inner_decrypted = $data;
190                 else {
191
192                         // Decode the encrypted blob
193
194                         $inner_encrypted = base64_decode($data);
195                         $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
196                         $inner_decrypted = pkcs5_unpad($inner_decrypted);
197                 }
198
199                 if (!$author_link) {
200                         logger('Could not retrieve author URI.');
201                         http_status_exit(400);
202                 }
203                 // Once we have the author URI, go to the web and try to find their public key
204                 // (first this will look it up locally if it is in the fcontact cache)
205                 // This will also convert diaspora public key from pkcs#1 to pkcs#8
206
207                 logger('Fetching key for '.$author_link);
208                 $key = self::key($author_link);
209
210                 if (!$key) {
211                         logger('Could not retrieve author key.');
212                         http_status_exit(400);
213                 }
214
215                 $verify = rsa_verify($signed_data,$signature,$key);
216
217                 if (!$verify) {
218                         logger('Message did not verify. Discarding.');
219                         http_status_exit(400);
220                 }
221
222                 logger('Message verified.');
223
224                 return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
225
226         }
227
228
229         /**
230          * @brief Dispatches public messages and find the fitting receivers
231          *
232          * @param array $msg The post that will be dispatched
233          *
234          * @return bool Was the message accepted?
235          */
236         public static function dispatch_public($msg) {
237
238                 $enabled = intval(get_config("system", "diaspora_enabled"));
239                 if (!$enabled) {
240                         logger("diaspora is disabled");
241                         return false;
242                 }
243
244                 // Use a dummy importer to import the data for the public copy
245                 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
246                 $item_id = self::dispatch($importer,$msg);
247
248                 // Now distribute it to the followers
249                 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
250                         (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
251                         AND NOT `account_expired` AND NOT `account_removed`",
252                         dbesc(NETWORK_DIASPORA),
253                         dbesc($msg["author"])
254                 );
255                 if($r) {
256                         foreach($r as $rr) {
257                                 logger("delivering to: ".$rr["username"]);
258                                 self::dispatch($rr,$msg);
259                         }
260                 } else
261                         logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
262
263                 return $item_id;
264         }
265
266         /**
267          * @brief Dispatches the different message types to the different functions
268          *
269          * @param array $importer Array of the importer user
270          * @param array $msg The post that will be dispatched
271          *
272          * @return bool Was the message accepted?
273          */
274         public static function dispatch($importer, $msg) {
275
276                 // The sender is the handle of the contact that sent the message.
277                 // This will often be different with relayed messages (for example "like" and "comment")
278                 $sender = $msg["author"];
279
280                 if (!diaspora::valid_posting($msg, $fields)) {
281                         logger("Invalid posting");
282                         return false;
283                 }
284
285                 $type = $fields->getName();
286
287                 switch ($type) {
288                         case "account_deletion":
289                                 return self::receive_account_deletion($importer, $fields);
290
291                         case "comment":
292                                 return self::receive_comment($importer, $sender, $fields);
293
294                         case "conversation":
295                                 return self::receive_conversation($importer, $msg, $fields);
296
297                         case "like":
298                                 return self::receive_like($importer, $sender, $fields);
299
300                         case "message":
301                                 return self::receive_message($importer, $fields);
302
303                         case "participation": // Not implemented
304                                 return self::receive_participation($importer, $fields);
305
306                         case "photo": // Not implemented
307                                 return self::receive_photo($importer, $fields);
308
309                         case "poll_participation": // Not implemented
310                                 return self::receive_poll_participation($importer, $fields);
311
312                         case "profile":
313                                 return self::receive_profile($importer, $fields);
314
315                         case "request":
316                                 return self::receive_request($importer, $fields);
317
318                         case "reshare":
319                                 return self::receive_reshare($importer, $fields);
320
321                         case "retraction":
322                                 return self::receive_retraction($importer, $sender, $fields);
323
324                         case "status_message":
325                                 return self::receive_status_message($importer, $fields);
326
327                         default:
328                                 logger("Unknown message type ".$type);
329                                 return false;
330                 }
331
332                 return true;
333         }
334
335         /**
336          * @brief Checks if a posting is valid and fetches the data fields.
337          *
338          * This function does not only check the signature.
339          * It also does the conversion between the old and the new diaspora format.
340          *
341          * @param array $msg Array with the XML, the sender handle and the sender signature
342          * @param object $fields SimpleXML object that contains the posting when it is valid
343          *
344          * @return bool Is the posting valid?
345          */
346         private function valid_posting($msg, &$fields) {
347
348                 $data = parse_xml_string($msg["message"], false);
349
350                 if (!is_object($data))
351                         return false;
352
353                 $first_child = $data->getName();
354
355                 // Is this the new or the old version?
356                 if ($data->getName() == "XML") {
357                         $oldXML = true;
358                         foreach ($data->post->children() as $child)
359                                 $element = $child;
360                 } else {
361                         $oldXML = false;
362                         $element = $data;
363                 }
364
365                 $type = $element->getName();
366                 $orig_type = $type;
367
368                 // All retractions are handled identically from now on.
369                 // In the new version there will only be "retraction".
370                 if (in_array($type, array("signed_retraction", "relayable_retraction")))
371                         $type = "retraction";
372
373                 $fields = new SimpleXMLElement("<".$type."/>");
374
375                 $signed_data = "";
376
377                 foreach ($element->children() AS $fieldname => $entry) {
378                         if ($oldXML) {
379                                 // Translation for the old XML structure
380                                 if ($fieldname == "diaspora_handle")
381                                         $fieldname = "author";
382
383                                 if ($fieldname == "participant_handles")
384                                         $fieldname = "participants";
385
386                                 if (in_array($type, array("like", "participation"))) {
387                                         if ($fieldname == "target_type")
388                                                 $fieldname = "parent_type";
389                                 }
390
391                                 if ($fieldname == "sender_handle")
392                                         $fieldname = "author";
393
394                                 if ($fieldname == "recipient_handle")
395                                         $fieldname = "recipient";
396
397                                 if ($fieldname == "root_diaspora_id")
398                                         $fieldname = "root_author";
399
400                                 if ($type == "retraction") {
401                                         if ($fieldname == "post_guid")
402                                                 $fieldname = "target_guid";
403
404                                         if ($fieldname == "type")
405                                                 $fieldname = "target_type";
406                                 }
407                         }
408
409                         if ($fieldname == "author_signature")
410                                 $author_signature = base64_decode($entry);
411                         elseif ($fieldname == "parent_author_signature")
412                                 $parent_author_signature = base64_decode($entry);
413                         elseif ($fieldname != "target_author_signature") {
414                                 if ($signed_data != "") {
415                                         $signed_data .= ";";
416                                         $signed_data_parent .= ";";
417                                 }
418
419                                 $signed_data .= $entry;
420                         }
421                         if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
422                                 ($orig_type == "relayable_retraction"))
423                                 xml::copy($entry, $fields, $fieldname);
424                 }
425
426                 // This is something that shouldn't happen at all.
427                 if (in_array($type, array("status_message", "reshare", "profile")))
428                         if ($msg["author"] != $fields->author) {
429                                 logger("Message handle is not the same as envelope sender. Quitting this message.");
430                                 return false;
431                         }
432
433                 // Only some message types have signatures. So we quit here for the other types.
434                 if (!in_array($type, array("comment", "message", "like")))
435                         return true;
436
437                 // No author_signature? This is a must, so we quit.
438                 if (!isset($author_signature))
439                         return false;
440
441                 if (isset($parent_author_signature)) {
442                         $key = self::key($msg["author"]);
443
444                         if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
445                                 return false;
446                 }
447
448                 $key = self::key($fields->author);
449
450                 return rsa_verify($signed_data, $author_signature, $key, "sha256");
451         }
452
453         /**
454          * @brief Fetches the public key for a given handle
455          *
456          * @param string $handle The handle
457          *
458          * @return string The public key
459          */
460         private function key($handle) {
461                 logger("Fetching diaspora key for: ".$handle);
462
463                 $r = self::person_by_handle($handle);
464                 if($r)
465                         return $r["pubkey"];
466
467                 return "";
468         }
469
470         /**
471          * @brief Fetches data for a given handle
472          *
473          * @param string $handle The handle
474          *
475          * @return array the queried data
476          */
477         private function person_by_handle($handle) {
478
479                 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
480                         dbesc(NETWORK_DIASPORA),
481                         dbesc($handle)
482                 );
483                 if ($r) {
484                         $person = $r[0];
485                         logger("In cache ".print_r($r,true), LOGGER_DEBUG);
486
487                         // update record occasionally so it doesn't get stale
488                         $d = strtotime($person["updated"]." +00:00");
489                         if ($d < strtotime("now - 14 days"))
490                                 $update = true;
491                 }
492
493                 if (!$person OR $update) {
494                         logger("create or refresh", LOGGER_DEBUG);
495                         $r = probe_url($handle, PROBE_DIASPORA);
496
497                         // Note that Friendica contacts will return a "Diaspora person"
498                         // if Diaspora connectivity is enabled on their server
499                         if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
500                                 self::add_fcontact($r, $update);
501                                 $person = $r;
502                         }
503                 }
504                 return $person;
505         }
506
507         /**
508          * @brief Updates the fcontact table
509          *
510          * @param array $arr The fcontact data
511          * @param bool $update Update or insert?
512          *
513          * @return string The id of the fcontact entry
514          */
515         private function add_fcontact($arr, $update = false) {
516                 /// @todo Remove this function from include/network.php
517
518                 if($update) {
519                         $r = q("UPDATE `fcontact` SET
520                                         `name` = '%s',
521                                         `photo` = '%s',
522                                         `request` = '%s',
523                                         `nick` = '%s',
524                                         `addr` = '%s',
525                                         `batch` = '%s',
526                                         `notify` = '%s',
527                                         `poll` = '%s',
528                                         `confirm` = '%s',
529                                         `alias` = '%s',
530                                         `pubkey` = '%s',
531                                         `updated` = '%s'
532                                 WHERE `url` = '%s' AND `network` = '%s'",
533                                         dbesc($arr["name"]),
534                                         dbesc($arr["photo"]),
535                                         dbesc($arr["request"]),
536                                         dbesc($arr["nick"]),
537                                         dbesc($arr["addr"]),
538                                         dbesc($arr["batch"]),
539                                         dbesc($arr["notify"]),
540                                         dbesc($arr["poll"]),
541                                         dbesc($arr["confirm"]),
542                                         dbesc($arr["alias"]),
543                                         dbesc($arr["pubkey"]),
544                                         dbesc(datetime_convert()),
545                                         dbesc($arr["url"]),
546                                         dbesc($arr["network"])
547                                 );
548                 } else {
549                         $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
550                                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
551                                 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
552                                         dbesc($arr["url"]),
553                                         dbesc($arr["name"]),
554                                         dbesc($arr["photo"]),
555                                         dbesc($arr["request"]),
556                                         dbesc($arr["nick"]),
557                                         dbesc($arr["addr"]),
558                                         dbesc($arr["batch"]),
559                                         dbesc($arr["notify"]),
560                                         dbesc($arr["poll"]),
561                                         dbesc($arr["confirm"]),
562                                         dbesc($arr["network"]),
563                                         dbesc($arr["alias"]),
564                                         dbesc($arr["pubkey"]),
565                                         dbesc(datetime_convert())
566                                 );
567                 }
568
569                 return $r;
570         }
571
572         public static function handle_from_contact($contact_id) {
573                 $handle = False;
574
575                 logger("contact id is ".$contact_id, LOGGER_DEBUG);
576
577                 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
578                        intval($contact_id)
579                 );
580                 if($r) {
581                         $contact = $r[0];
582
583                         logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
584
585                         if($contact['addr'] != "")
586                                 $handle = $contact['addr'];
587                         elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
588                                 $baseurl_start = strpos($contact['url'],'://') + 3;
589                                 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
590                                 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
591                                 $handle = $contact['nick'].'@'.$baseurl;
592                         }
593                 }
594
595                 return $handle;
596         }
597
598         private function contact_by_handle($uid, $handle) {
599                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
600                         intval($uid),
601                         dbesc($handle)
602                 );
603
604                 if ($r)
605                         return $r[0];
606
607                 $handle_parts = explode("@", $handle);
608                 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
609                 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
610                         dbesc(NETWORK_DFRN),
611                         intval($uid),
612                         dbesc($nurl_sql)
613                 );
614                 if($r)
615                         return $r[0];
616
617                 return false;
618         }
619
620         private function post_allow($importer, $contact, $is_comment = false) {
621
622                 // perhaps we were already sharing with this person. Now they're sharing with us.
623                 // That makes us friends.
624                 // Normally this should have handled by getting a request - but this could get lost
625                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
626                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
627                                 intval(CONTACT_IS_FRIEND),
628                                 intval($contact["id"]),
629                                 intval($importer["uid"])
630                         );
631                         $contact["rel"] = CONTACT_IS_FRIEND;
632                         logger("defining user ".$contact["nick"]." as friend");
633                 }
634
635                 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
636                         return false;
637                 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
638                         return true;
639                 if($contact["rel"] == CONTACT_IS_FOLLOWER)
640                         if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
641                                 return true;
642
643                 // Messages for the global users are always accepted
644                 if ($importer["uid"] == 0)
645                         return true;
646
647                 return false;
648         }
649
650         private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
651                 $contact = self::contact_by_handle($importer["uid"], $handle);
652                 if (!$contact) {
653                         logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
654                         return false;
655                 }
656
657                 if (!self::post_allow($importer, $contact, false)) {
658                         logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
659                         return false;
660                 }
661                 return $contact;
662         }
663
664         private function message_exists($uid, $guid) {
665                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
666                         intval($uid),
667                         dbesc($guid)
668                 );
669
670                 if($r) {
671                         logger("message ".$guid." already exists for user ".$uid);
672                         return false;
673                 }
674
675                 return true;
676         }
677
678         private function fetch_guid($item) {
679                 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
680                         function ($match) use ($item){
681                                 return(self::fetch_guid_sub($match, $item));
682                         },$item["body"]);
683         }
684
685         private function fetch_guid_sub($match, $item) {
686                 if (!self::store_by_guid($match[1], $item["author-link"]))
687                         self::store_by_guid($match[1], $item["owner-link"]);
688         }
689
690         private function store_by_guid($guid, $server, $uid = 0) {
691                 $serverparts = parse_url($server);
692                 $server = $serverparts["scheme"]."://".$serverparts["host"];
693
694                 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
695
696                 $msg = self::message($guid, $server);
697
698                 if (!$msg)
699                         return false;
700
701                 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
702
703                 // Now call the dispatcher
704                 return self::dispatch_public($msg);
705         }
706
707         private function message($guid, $server, $level = 0) {
708
709                 if ($level > 5)
710                         return false;
711
712                 // This will work for Diaspora and newer Friendica servers
713                 $source_url = $server."/p/".$guid.".xml";
714                 $x = fetch_url($source_url);
715                 if(!$x)
716                         return false;
717
718                 $source_xml = parse_xml_string($x, false);
719
720                 if (!is_object($source_xml))
721                         return false;
722
723                 if ($source_xml->post->reshare) {
724                         // Reshare of a reshare - old Diaspora version
725                         return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
726                 } elseif ($source_xml->getName() == "reshare") {
727                         // Reshare of a reshare - new Diaspora version
728                         return self::message($source_xml->root_guid, $server, ++$level);
729                 }
730
731                 $author = "";
732
733                 // Fetch the author - for the old and the new Diaspora version
734                 if ($source_xml->post->status_message->diaspora_handle)
735                         $author = (string)$source_xml->post->status_message->diaspora_handle;
736                 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
737                         $author = (string)$source_xml->author;
738
739                 // If this isn't a "status_message" then quit
740                 if (!$author)
741                         return false;
742
743                 $msg = array("message" => $x, "author" => $author);
744
745                 $msg["key"] = self::key($msg["author"]);
746
747                 return $msg;
748         }
749
750         private function parent_item($uid, $guid, $author, $contact) {
751                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
752                                 `author-name`, `author-link`, `author-avatar`,
753                                 `owner-name`, `owner-link`, `owner-avatar`
754                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
755                         intval($uid), dbesc($guid));
756
757                 if(!$r) {
758                         $result = self::store_by_guid($guid, $contact["url"], $uid);
759
760                         if (!$result) {
761                                 $person = self::person_by_handle($author);
762                                 $result = self::store_by_guid($guid, $person["url"], $uid);
763                         }
764
765                         if ($result) {
766                                 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
767
768                                 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
769                                                 `author-name`, `author-link`, `author-avatar`,
770                                                 `owner-name`, `owner-link`, `owner-avatar`
771                                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
772                                         intval($uid), dbesc($guid));
773                         }
774                 }
775
776                 if (!$r) {
777                         logger("parent item not found: parent: ".$guid." item: ".$guid);
778                         return false;
779                 } else
780                         return $r[0];
781         }
782
783         private function author_contact_by_url($contact, $person, $uid) {
784
785                 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
786                         dbesc(normalise_link($person["url"])), intval($uid));
787                 if ($r) {
788                         $cid = $r[0]["id"];
789                         $network = $r[0]["network"];
790                 } else {
791                         $cid = $contact["id"];
792                         $network = NETWORK_DIASPORA;
793                 }
794
795                 return (array("cid" => $cid, "network" => $network));
796         }
797
798         public static function is_redmatrix($url) {
799                 return(strstr($url, "/channel/"));
800         }
801
802         private function plink($addr, $guid) {
803                 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
804
805                 // Fallback
806                 if (!$r)
807                         return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
808
809                 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
810                 // So we try another way as well.
811                 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
812                 if ($s)
813                         $r[0]["network"] = $s[0]["network"];
814
815                 if ($r[0]["network"] == NETWORK_DFRN)
816                         return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
817
818                 if (self::is_redmatrix($r[0]["url"]))
819                         return $r[0]["url"]."/?f=&mid=".$guid;
820
821                 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
822         }
823
824         private function receive_account_deletion($importer, $data) {
825                 $author = notags(unxmlify($data->author));
826
827                 $contact = self::contact_by_handle($importer["uid"], $author);
828                 if (!$contact) {
829                         logger("cannot find contact for author: ".$author);
830                         return false;
831                 }
832
833                 // We now remove the contact
834                 contact_remove($contact["id"]);
835                 return true;
836         }
837
838         private function receive_comment($importer, $sender, $data) {
839                 $guid = notags(unxmlify($data->guid));
840                 $parent_guid = notags(unxmlify($data->parent_guid));
841                 $text = unxmlify($data->text);
842                 $author = notags(unxmlify($data->author));
843
844                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
845                 if (!$contact)
846                         return false;
847
848                 if (self::message_exists($importer["uid"], $guid))
849                         return false;
850
851                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
852                 if (!$parent_item)
853                         return false;
854
855                 $person = self::person_by_handle($author);
856                 if (!is_array($person)) {
857                         logger("unable to find author details");
858                         return false;
859                 }
860
861                 // Fetch the contact id - if we know this contact
862                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
863
864                 $datarray = array();
865
866                 $datarray["uid"] = $importer["uid"];
867                 $datarray["contact-id"] = $author_contact["cid"];
868                 $datarray["network"]  = $author_contact["network"];
869
870                 $datarray["author-name"] = $person["name"];
871                 $datarray["author-link"] = $person["url"];
872                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
873
874                 $datarray["owner-name"] = $contact["name"];
875                 $datarray["owner-link"] = $contact["url"];
876                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
877
878                 $datarray["guid"] = $guid;
879                 $datarray["uri"] = $author.":".$guid;
880
881                 $datarray["type"] = "remote-comment";
882                 $datarray["verb"] = ACTIVITY_POST;
883                 $datarray["gravity"] = GRAVITY_COMMENT;
884                 $datarray["parent-uri"] = $parent_item["uri"];
885
886                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
887                 $datarray["object"] = json_encode($data);
888
889                 $datarray["body"] = diaspora2bb($text);
890
891                 self::fetch_guid($datarray);
892
893                 $message_id = item_store($datarray);
894
895                 // If we are the origin of the parent we store the original data and notify our followers
896                 if($message_id AND $parent_item["origin"]) {
897
898                         // Formerly we stored the signed text, the signature and the author in different fields.
899                         // We now store the raw data so that we are more flexible.
900                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
901                                 intval($message_id),
902                                 dbesc(json_encode($data))
903                         );
904
905                         // notify others
906                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
907                 }
908
909                 return $message_id;
910         }
911
912         private function receive_conversation_message($importer, $contact, $data, $msg, $mesg) {
913                 $guid = notags(unxmlify($data->guid));
914                 $subject = notags(unxmlify($data->subject));
915                 $author = notags(unxmlify($data->author));
916
917                 $reply = 0;
918
919                 $msg_guid = notags(unxmlify($mesg->guid));
920                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
921                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
922                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
923                 $msg_text = unxmlify($mesg->text);
924                 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
925
926                 // "diaspora_handle" is the element name from the old version
927                 // "author" is the element name from the new version
928                 if ($mesg->author)
929                         $msg_author = notags(unxmlify($mesg->author));
930                 elseif ($mesg->diaspora_handle)
931                         $msg_author = notags(unxmlify($mesg->diaspora_handle));
932                 else
933                         return false;
934
935                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
936
937                 if($msg_conversation_guid != $guid) {
938                         logger("message conversation guid does not belong to the current conversation.");
939                         return false;
940                 }
941
942                 $body = diaspora2bb($msg_text);
943                 $message_uri = $msg_author.":".$msg_guid;
944
945                 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
946
947                 $author_signature = base64_decode($msg_author_signature);
948
949                 if(strcasecmp($msg_author,$msg["author"]) == 0) {
950                         $person = $contact;
951                         $key = $msg["key"];
952                 } else {
953                         $person = self::person_by_handle($msg_author);
954
955                         if (is_array($person) && x($person, "pubkey"))
956                                 $key = $person["pubkey"];
957                         else {
958                                 logger("unable to find author details");
959                                         return false;
960                         }
961                 }
962
963                 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
964                         logger("verification failed.");
965                         return false;
966                 }
967
968                 if($msg_parent_author_signature) {
969                         $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
970
971                         $parent_author_signature = base64_decode($msg_parent_author_signature);
972
973                         $key = $msg["key"];
974
975                         if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
976                                 logger("owner verification failed.");
977                                 return false;
978                         }
979                 }
980
981                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
982                         dbesc($message_uri)
983                 );
984                 if($r) {
985                         logger("duplicate message already delivered.", LOGGER_DEBUG);
986                         return false;
987                 }
988
989                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
990                         VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
991                         intval($importer["uid"]),
992                         dbesc($msg_guid),
993                         intval($conversation["id"]),
994                         dbesc($person["name"]),
995                         dbesc($person["photo"]),
996                         dbesc($person["url"]),
997                         intval($contact["id"]),
998                         dbesc($subject),
999                         dbesc($body),
1000                         0,
1001                         0,
1002                         dbesc($message_uri),
1003                         dbesc($author.":".$guid),
1004                         dbesc($msg_created_at)
1005                 );
1006
1007                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1008                         dbesc(datetime_convert()),
1009                         intval($conversation["id"])
1010                 );
1011
1012                 notification(array(
1013                         "type" => NOTIFY_MAIL,
1014                         "notify_flags" => $importer["notify-flags"],
1015                         "language" => $importer["language"],
1016                         "to_name" => $importer["username"],
1017                         "to_email" => $importer["email"],
1018                         "uid" =>$importer["uid"],
1019                         "item" => array("subject" => $subject, "body" => $body),
1020                         "source_name" => $person["name"],
1021                         "source_link" => $person["url"],
1022                         "source_photo" => $person["thumb"],
1023                         "verb" => ACTIVITY_POST,
1024                         "otype" => "mail"
1025                 ));
1026         }
1027
1028         private function receive_conversation($importer, $msg, $data) {
1029                 $guid = notags(unxmlify($data->guid));
1030                 $subject = notags(unxmlify($data->subject));
1031                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1032                 $author = notags(unxmlify($data->author));
1033                 $participants = notags(unxmlify($data->participants));
1034
1035                 $messages = $data->message;
1036
1037                 if (!count($messages)) {
1038                         logger("empty conversation");
1039                         return false;
1040                 }
1041
1042                 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1043                 if (!$contact)
1044                         return false;
1045
1046                 $conversation = null;
1047
1048                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1049                         intval($importer["uid"]),
1050                         dbesc($guid)
1051                 );
1052                 if($c)
1053                         $conversation = $c[0];
1054                 else {
1055                         $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1056                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1057                                 intval($importer["uid"]),
1058                                 dbesc($guid),
1059                                 dbesc($author),
1060                                 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1061                                 dbesc(datetime_convert()),
1062                                 dbesc($subject),
1063                                 dbesc($participants)
1064                         );
1065                         if($r)
1066                                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1067                                         intval($importer["uid"]),
1068                                         dbesc($guid)
1069                                 );
1070
1071                         if($c)
1072                                 $conversation = $c[0];
1073                 }
1074                 if (!$conversation) {
1075                         logger("unable to create conversation.");
1076                         return;
1077                 }
1078
1079                 foreach($messages as $mesg)
1080                         self::receive_conversation_message($importer, $contact, $data, $msg, $mesg);
1081
1082                 return true;
1083         }
1084
1085         private function construct_like_body($contact, $parent_item, $guid) {
1086                 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1087
1088                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1089                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1090                 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1091
1092                 return sprintf($bodyverb, $ulink, $alink, $plink);
1093         }
1094
1095         private function construct_like_object($importer, $parent_item) {
1096                 $objtype = ACTIVITY_OBJ_NOTE;
1097                 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1098                 $parent_body = $parent_item["body"];
1099
1100                 $xmldata = array("object" => array("type" => $objtype,
1101                                                 "local" => "1",
1102                                                 "id" => $parent_item["uri"],
1103                                                 "link" => $link,
1104                                                 "title" => "",
1105                                                 "content" => $parent_body));
1106
1107                 return xml::from_array($xmldata, $xml, true);
1108         }
1109
1110         private function receive_like($importer, $sender, $data) {
1111                 $positive = notags(unxmlify($data->positive));
1112                 $guid = notags(unxmlify($data->guid));
1113                 $parent_type = notags(unxmlify($data->parent_type));
1114                 $parent_guid = notags(unxmlify($data->parent_guid));
1115                 $author = notags(unxmlify($data->author));
1116
1117                 // likes on comments aren't supported by Diaspora - only on posts
1118                 // But maybe this will be supported in the future, so we will accept it.
1119                 if (!in_array($parent_type, array("Post", "Comment")))
1120                         return false;
1121
1122                 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1123                 if (!$contact)
1124                         return false;
1125
1126                 if (self::message_exists($importer["uid"], $guid))
1127                         return false;
1128
1129                 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1130                 if (!$parent_item)
1131                         return false;
1132
1133                 $person = self::person_by_handle($author);
1134                 if (!is_array($person)) {
1135                         logger("unable to find author details");
1136                         return false;
1137                 }
1138
1139                 // Fetch the contact id - if we know this contact
1140                 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1141
1142                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1143                 // We would accept this anyhow.
1144                 if ($positive === "true")
1145                         $verb = ACTIVITY_LIKE;
1146                 else
1147                         $verb = ACTIVITY_DISLIKE;
1148
1149                 $datarray = array();
1150
1151                 $datarray["uid"] = $importer["uid"];
1152                 $datarray["contact-id"] = $author_contact["cid"];
1153                 $datarray["network"]  = $author_contact["network"];
1154
1155                 $datarray["author-name"] = $person["name"];
1156                 $datarray["author-link"] = $person["url"];
1157                 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1158
1159                 $datarray["owner-name"] = $contact["name"];
1160                 $datarray["owner-link"] = $contact["url"];
1161                 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1162
1163                 $datarray["guid"] = $guid;
1164                 $datarray["uri"] = $author.":".$guid;
1165
1166                 $datarray["type"] = "activity";
1167                 $datarray["verb"] = $verb;
1168                 $datarray["gravity"] = GRAVITY_LIKE;
1169                 $datarray["parent-uri"] = $parent_item["uri"];
1170
1171                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1172                 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1173
1174                 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1175
1176                 $message_id = item_store($datarray);
1177
1178                 // If we are the origin of the parent we store the original data and notify our followers
1179                 if($message_id AND $parent_item["origin"]) {
1180
1181                         // Formerly we stored the signed text, the signature and the author in different fields.
1182                         // We now store the raw data so that we are more flexible.
1183                         q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1184                                 intval($message_id),
1185                                 dbesc(json_encode($data))
1186                         );
1187
1188                         // notify others
1189                         proc_run("php", "include/notifier.php", "comment-import", $message_id);
1190                 }
1191
1192                 return $message_id;
1193         }
1194
1195         private function receive_message($importer, $data) {
1196                 $guid = notags(unxmlify($data->guid));
1197                 $parent_guid = notags(unxmlify($data->parent_guid));
1198                 $text = unxmlify($data->text);
1199                 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1200                 $author = notags(unxmlify($data->author));
1201                 $conversation_guid = notags(unxmlify($data->conversation_guid));
1202
1203                 $contact = self::allowed_contact_by_handle($importer, $author, true);
1204                 if (!$contact)
1205                         return false;
1206
1207                 $conversation = null;
1208
1209                 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1210                         intval($importer["uid"]),
1211                         dbesc($conversation_guid)
1212                 );
1213                 if($c)
1214                         $conversation = $c[0];
1215                 else {
1216                         logger("conversation not available.");
1217                         return false;
1218                 }
1219
1220                 $reply = 0;
1221
1222                 $body = diaspora2bb($text);
1223                 $message_uri = $author.":".$guid;
1224
1225                 $person = self::person_by_handle($author);
1226                 if (!$person) {
1227                         logger("unable to find author details");
1228                         return false;
1229                 }
1230
1231                 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1232                         dbesc($message_uri),
1233                         intval($importer["uid"])
1234                 );
1235                 if($r) {
1236                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1237                         return false;
1238                 }
1239
1240                 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1241                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1242                         intval($importer["uid"]),
1243                         dbesc($guid),
1244                         intval($conversation["id"]),
1245                         dbesc($person["name"]),
1246                         dbesc($person["photo"]),
1247                         dbesc($person["url"]),
1248                         intval($contact["id"]),
1249                         dbesc($conversation["subject"]),
1250                         dbesc($body),
1251                         0,
1252                         1,
1253                         dbesc($message_uri),
1254                         dbesc($author.":".$parent_guid),
1255                         dbesc($created_at)
1256                 );
1257
1258                 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1259                         dbesc(datetime_convert()),
1260                         intval($conversation["id"])
1261                 );
1262
1263                 return true;
1264         }
1265
1266         private function receive_participation($importer, $data) {
1267                 // I'm not sure if we can fully support this message type
1268                 return true;
1269         }
1270
1271         private function receive_photo($importer, $data) {
1272                 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1273                 return true;
1274         }
1275
1276         private function receive_poll_participation($importer, $data) {
1277                 // We don't support polls by now
1278                 return true;
1279         }
1280
1281         private function receive_profile($importer, $data) {
1282                 $author = notags(unxmlify($data->author));
1283
1284                 $contact = self::contact_by_handle($importer["uid"], $author);
1285                 if (!$contact)
1286                         return;
1287
1288                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1289                 $image_url = unxmlify($data->image_url);
1290                 $birthday = unxmlify($data->birthday);
1291                 $location = diaspora2bb(unxmlify($data->location));
1292                 $about = diaspora2bb(unxmlify($data->bio));
1293                 $gender = unxmlify($data->gender);
1294                 $searchable = (unxmlify($data->searchable) == "true");
1295                 $nsfw = (unxmlify($data->nsfw) == "true");
1296                 $tags = unxmlify($data->tag_string);
1297
1298                 $tags = explode("#", $tags);
1299
1300                 $keywords = array();
1301                 foreach ($tags as $tag) {
1302                         $tag = trim(strtolower($tag));
1303                         if ($tag != "")
1304                                 $keywords[] = $tag;
1305                 }
1306
1307                 $keywords = implode(", ", $keywords);
1308
1309                 $handle_parts = explode("@", $author);
1310                 $nick = $handle_parts[0];
1311
1312                 if($name === "")
1313                         $name = $handle_parts[0];
1314
1315                 if( preg_match("|^https?://|", $image_url) === 0)
1316                         $image_url = "http://".$handle_parts[1].$image_url;
1317
1318                 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1319
1320                 // Generic birthday. We don't know the timezone. The year is irrelevant.
1321
1322                 $birthday = str_replace("1000", "1901", $birthday);
1323
1324                 if ($birthday != "")
1325                         $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1326
1327                 // this is to prevent multiple birthday notifications in a single year
1328                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1329
1330                 if(substr($birthday,5) === substr($contact["bd"],5))
1331                         $birthday = $contact["bd"];
1332
1333                 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1334                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1335                         dbesc($name),
1336                         dbesc($nick),
1337                         dbesc($author),
1338                         dbesc(datetime_convert()),
1339                         dbesc($birthday),
1340                         dbesc($location),
1341                         dbesc($about),
1342                         dbesc($keywords),
1343                         dbesc($gender),
1344                         intval($contact["id"]),
1345                         intval($importer["uid"])
1346                 );
1347
1348                 if ($searchable) {
1349                         poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1350                                 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1351                 }
1352
1353                 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1354                                         "photo" => $image_url, "name" => $name, "location" => $location,
1355                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
1356                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1357                                         "hide" => !$searchable, "nsfw" => $nsfw);
1358
1359                 update_gcontact($gcontact);
1360
1361                 return true;
1362         }
1363
1364         private function receive_request_make_friend($importer, $contact) {
1365
1366                 $a = get_app();
1367
1368                 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1369                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1370                                 intval(CONTACT_IS_FRIEND),
1371                                 intval($contact["id"]),
1372                                 intval($importer["uid"])
1373                         );
1374                 }
1375                 // send notification
1376
1377                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1378                         intval($importer["uid"])
1379                 );
1380
1381                 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1382
1383                         $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1384                                 intval($importer["uid"])
1385                         );
1386
1387                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1388
1389                         if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1390
1391                                 $arr = array();
1392                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1393                                 $arr["uid"] = $importer["uid"];
1394                                 $arr["contact-id"] = $self[0]["id"];
1395                                 $arr["wall"] = 1;
1396                                 $arr["type"] = 'wall';
1397                                 $arr["gravity"] = 0;
1398                                 $arr["origin"] = 1;
1399                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1400                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1401                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1402                                 $arr["verb"] = ACTIVITY_FRIEND;
1403                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1404
1405                                 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1406                                 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1407                                 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1408                                 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1409
1410                                 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1411                                         ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1412                                 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1413                                 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1414                                 $arr["object"] .= "</link></object>\n";
1415                                 $arr["last-child"] = 1;
1416
1417                                 $arr["allow_cid"] = $user[0]["allow_cid"];
1418                                 $arr["allow_gid"] = $user[0]["allow_gid"];
1419                                 $arr["deny_cid"]  = $user[0]["deny_cid"];
1420                                 $arr["deny_gid"]  = $user[0]["deny_gid"];
1421
1422                                 $i = item_store($arr);
1423                                 if($i)
1424                                         proc_run("php", "include/notifier.php", "activity", $i);
1425
1426                         }
1427
1428                 }
1429         }
1430
1431         private function receive_request($importer, $data) {
1432                 $author = unxmlify($data->author);
1433                 $recipient = unxmlify($data->recipient);
1434
1435                 if (!$author || !$recipient)
1436                         return;
1437
1438                 $contact = self::contact_by_handle($importer["uid"],$author);
1439
1440                 if($contact) {
1441
1442                         // perhaps we were already sharing with this person. Now they're sharing with us.
1443                         // That makes us friends.
1444
1445                         self::receive_request_make_friend($importer, $contact);
1446                         return true;
1447                 }
1448
1449                 $ret = self::person_by_handle($author);
1450
1451                 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1452                         logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1453                         return false;
1454                 }
1455
1456                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1457
1458                 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1459                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1460                         intval($importer["uid"]),
1461                         dbesc($ret["network"]),
1462                         dbesc($ret["addr"]),
1463                         datetime_convert(),
1464                         dbesc($ret["url"]),
1465                         dbesc(normalise_link($ret["url"])),
1466                         dbesc($batch),
1467                         dbesc($ret["name"]),
1468                         dbesc($ret["nick"]),
1469                         dbesc($ret["photo"]),
1470                         dbesc($ret["pubkey"]),
1471                         dbesc($ret["notify"]),
1472                         dbesc($ret["poll"]),
1473                         1,
1474                         2
1475                 );
1476
1477                 // find the contact record we just created
1478
1479                 $contact_record = self::contact_by_handle($importer["uid"],$author);
1480
1481                 if (!$contact_record) {
1482                         logger("unable to locate newly created contact record.");
1483                         return;
1484                 }
1485
1486                 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1487                         intval($importer["uid"])
1488                 );
1489
1490                 if($g && intval($g[0]["def_gid"]))
1491                         group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1492
1493                 if($importer["page-flags"] == PAGE_NORMAL) {
1494
1495                         $hash = random_string().(string)time();   // Generate a confirm_key
1496
1497                         $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1498                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1499                                 intval($importer["uid"]),
1500                                 intval($contact_record["id"]),
1501                                 0,
1502                                 0,
1503                                 dbesc(t("Sharing notification from Diaspora network")),
1504                                 dbesc($hash),
1505                                 dbesc(datetime_convert())
1506                         );
1507                 } else {
1508
1509                         // automatic friend approval
1510
1511                         update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1512
1513                         // technically they are sharing with us (CONTACT_IS_SHARING),
1514                         // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1515                         // we are going to change the relationship and make them a follower.
1516
1517                         if($importer["page-flags"] == PAGE_FREELOVE)
1518                                 $new_relation = CONTACT_IS_FRIEND;
1519                         else
1520                                 $new_relation = CONTACT_IS_FOLLOWER;
1521
1522                         $r = q("UPDATE `contact` SET `rel` = %d,
1523                                 `name-date` = '%s',
1524                                 `uri-date` = '%s',
1525                                 `blocked` = 0,
1526                                 `pending` = 0,
1527                                 `writable` = 1
1528                                 WHERE `id` = %d
1529                                 ",
1530                                 intval($new_relation),
1531                                 dbesc(datetime_convert()),
1532                                 dbesc(datetime_convert()),
1533                                 intval($contact_record["id"])
1534                         );
1535
1536                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1537                         if($u)
1538                                 $ret = self::send_share($u[0], $contact_record);
1539                 }
1540
1541                 return true;
1542         }
1543
1544         private function original_item($guid, $orig_author, $author) {
1545
1546                 // Do we already have this item?
1547                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1548                                 `author-name`, `author-link`, `author-avatar`
1549                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1550                         dbesc($guid));
1551
1552                 if($r) {
1553                         logger("reshared message ".$guid." already exists on system.");
1554
1555                         // Maybe it is already a reshared item?
1556                         // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1557                         if (self::is_reshare($r[0]["body"]))
1558                                 $r = array();
1559                         else
1560                                 return $r[0];
1561                 }
1562
1563                 if (!$r) {
1564                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1565                         logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1566                         $item_id = self::store_by_guid($guid, $server);
1567
1568                         if (!$item_id) {
1569                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1570                                 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1571                                 $item_id = self::store_by_guid($guid, $server);
1572                         }
1573
1574                         // Deactivated by now since there is a risk that someone could manipulate postings through this method
1575 /*                      if (!$item_id) {
1576                                 $server = "https://".substr($author, strpos($author, "@") + 1);
1577                                 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1578                                 $item_id = self::store_by_guid($guid, $server);
1579                         }
1580                         if (!$item_id) {
1581                                 $server = "http://".substr($author, strpos($author, "@") + 1);
1582                                 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1583                                 $item_id = self::store_by_guid($guid, $server);
1584                         }
1585 */
1586                         if ($item_id) {
1587                                 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1588                                                 `author-name`, `author-link`, `author-avatar`
1589                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1590                                         intval($item_id));
1591
1592                                 if ($r)
1593                                         return $r[0];
1594
1595                         }
1596                 }
1597                 return false;
1598         }
1599
1600         private function receive_reshare($importer, $data) {
1601                 $root_author = notags(unxmlify($data->root_author));
1602                 $root_guid = notags(unxmlify($data->root_guid));
1603                 $guid = notags(unxmlify($data->guid));
1604                 $author = notags(unxmlify($data->author));
1605                 $public = notags(unxmlify($data->public));
1606                 $created_at = notags(unxmlify($data->created_at));
1607
1608                 $contact = self::allowed_contact_by_handle($importer, $author, false);
1609                 if (!$contact)
1610                         return false;
1611
1612                 if (self::message_exists($importer["uid"], $guid))
1613                         return false;
1614
1615                 $original_item = self::original_item($root_guid, $root_author, $author);
1616                 if (!$original_item)
1617                         return false;
1618
1619                 $datarray = array();
1620
1621                 $datarray["uid"] = $importer["uid"];
1622                 $datarray["contact-id"] = $contact["id"];
1623                 $datarray["network"]  = NETWORK_DIASPORA;
1624
1625                 $datarray["author-name"] = $contact["name"];
1626                 $datarray["author-link"] = $contact["url"];
1627                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1628
1629                 $datarray["owner-name"] = $datarray["author-name"];
1630                 $datarray["owner-link"] = $datarray["author-link"];
1631                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1632
1633                 $datarray["guid"] = $guid;
1634                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1635
1636                 $datarray["verb"] = ACTIVITY_POST;
1637                 $datarray["gravity"] = GRAVITY_PARENT;
1638
1639                 $datarray["object"] = json_encode($data);
1640
1641                 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1642                                         $original_item["guid"], $original_item["created"], $original_item["uri"]);
1643                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1644
1645                 $datarray["tag"] = $original_item["tag"];
1646                 $datarray["app"]  = $original_item["app"];
1647
1648                 $datarray["plink"] = self::plink($author, $guid);
1649                 $datarray["private"] = (($public == "false") ? 1 : 0);
1650                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1651
1652                 $datarray["object-type"] = $original_item["object-type"];
1653
1654                 self::fetch_guid($datarray);
1655                 $message_id = item_store($datarray);
1656
1657                 return $message_id;
1658         }
1659
1660         private function item_retraction($importer, $contact, $data) {
1661                 $target_type = notags(unxmlify($data->target_type));
1662                 $target_guid = notags(unxmlify($data->target_guid));
1663                 $author = notags(unxmlify($data->author));
1664
1665                 $person = self::person_by_handle($author);
1666                 if (!is_array($person)) {
1667                         logger("unable to find author detail for ".$author);
1668                         return false;
1669                 }
1670
1671                 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
1672                         dbesc($target_guid),
1673                         intval($importer["uid"])
1674                 );
1675                 if (!$r)
1676                         return false;
1677
1678                 // Only delete it if the author really fits
1679                 if (!link_compare($r[0]["author-link"],$person["url"]))
1680                         return false;
1681
1682                 // Check if the sender is the thread owner
1683                 $p = q("SELECT `author-link`, `origin` FROM `item` WHERE `id` = %d",
1684                         intval($r[0]["parent"]));
1685
1686                 // Only delete it if the parent author really fits
1687                 if (!link_compare($p[0]["author-link"], $contact["url"]))
1688                         return false;
1689
1690                 // 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
1691                 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
1692                         dbesc(datetime_convert()),
1693                         dbesc(datetime_convert()),
1694                         intval($r[0]["id"])
1695                 );
1696                 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
1697
1698                 // Now check if the retraction needs to be relayed by us
1699                 if($p[0]["origin"]) {
1700
1701                         // Formerly we stored the signed text, the signature and the author in different fields.
1702                         // We now store the raw data so that we are more flexible.
1703                         q("INSERT INTO `sign` (`retract_iid`,`signed_text`) VALUES (%d,'%s')",
1704                                 intval($r[0]["id"]),
1705                                 dbesc(json_encode($data))
1706                         );
1707
1708                         // notify others
1709                         proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
1710                 }
1711         }
1712
1713         private function receive_retraction($importer, $sender, $data) {
1714                 $target_type = notags(unxmlify($data->target_type));
1715
1716                 $contact = self::contact_by_handle($importer["uid"], $sender);
1717                 if (!$contact) {
1718                         logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
1719                         return false;
1720                 }
1721
1722                 switch ($target_type) {
1723                         case "Comment":
1724                         case "Like":
1725                         case "Post": // "Post" will be supported in a future version
1726                         case "Reshare":
1727                         case "StatusMessage":
1728                                 return self::item_retraction($importer, $contact, $data);;
1729
1730                         case "Person":
1731                                 /// @todo What should we do with an "unshare"?
1732                                 // Removing the contact isn't correct since we still can read the public items
1733                                 //contact_remove($contact["id"]);
1734                                 return true;
1735
1736                         default:
1737                                 logger("Unknown target type ".$target_type);
1738                                 return false;
1739                 }
1740                 return true;
1741         }
1742
1743         private function receive_status_message($importer, $data) {
1744
1745                 $raw_message = unxmlify($data->raw_message);
1746                 $guid = notags(unxmlify($data->guid));
1747                 $author = notags(unxmlify($data->author));
1748                 $public = notags(unxmlify($data->public));
1749                 $created_at = notags(unxmlify($data->created_at));
1750                 $provider_display_name = notags(unxmlify($data->provider_display_name));
1751
1752                 /// @todo enable support for polls
1753                 //if ($data->poll) {
1754                 //      foreach ($data->poll AS $poll)
1755                 //              print_r($poll);
1756                 //      die("poll!\n");
1757                 //}
1758                 $contact = self::allowed_contact_by_handle($importer, $author, false);
1759                 if (!$contact)
1760                         return false;
1761
1762                 if (self::message_exists($importer["uid"], $guid))
1763                         return false;
1764
1765                 $address = array();
1766                 if ($data->location)
1767                         foreach ($data->location->children() AS $fieldname => $data)
1768                                 $address[$fieldname] = notags(unxmlify($data));
1769
1770                 $body = diaspora2bb($raw_message);
1771
1772                 $datarray = array();
1773
1774                 if ($data->photo) {
1775                         foreach ($data->photo AS $photo)
1776                                 $body = "[img]".$photo->remote_photo_path.$photo->remote_photo_name."[/img]\n".$body;
1777
1778                         $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
1779                 } else {
1780                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1781
1782                         // Add OEmbed and other information to the body
1783                         if (!self::is_redmatrix($contact["url"]))
1784                                 $body = add_page_info_to_body($body, false, true);
1785                 }
1786
1787                 $datarray["uid"] = $importer["uid"];
1788                 $datarray["contact-id"] = $contact["id"];
1789                 $datarray["network"] = NETWORK_DIASPORA;
1790
1791                 $datarray["author-name"] = $contact["name"];
1792                 $datarray["author-link"] = $contact["url"];
1793                 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1794
1795                 $datarray["owner-name"] = $datarray["author-name"];
1796                 $datarray["owner-link"] = $datarray["author-link"];
1797                 $datarray["owner-avatar"] = $datarray["author-avatar"];
1798
1799                 $datarray["guid"] = $guid;
1800                 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1801
1802                 $datarray["verb"] = ACTIVITY_POST;
1803                 $datarray["gravity"] = GRAVITY_PARENT;
1804
1805                 $datarray["object"] = json_encode($data);
1806
1807                 $datarray["body"] = $body;
1808
1809                 if ($provider_display_name != "")
1810                         $datarray["app"] = $provider_display_name;
1811
1812                 $datarray["plink"] = self::plink($author, $guid);
1813                 $datarray["private"] = (($public == "false") ? 1 : 0);
1814                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1815
1816                 if (isset($address["address"]))
1817                         $datarray["location"] = $address["address"];
1818
1819                 if (isset($address["lat"]) AND isset($address["lng"]))
1820                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
1821
1822                 self::fetch_guid($datarray);
1823                 $message_id = item_store($datarray);
1824
1825                 logger("Stored item with message id ".$message_id, LOGGER_DEBUG);
1826
1827                 return $message_id;
1828         }
1829
1830         /******************************************************************************************
1831          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
1832          ******************************************************************************************/
1833
1834         private function my_handle($me) {
1835                 if ($contact["addr"] != "")
1836                         return $contact["addr"];
1837
1838                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
1839                 // So - just in case - we build the the address here.
1840                 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
1841         }
1842
1843         private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
1844
1845                 logger("Message: ".$msg, LOGGER_DATA);
1846
1847                 $handle = self::my_handle($user);
1848
1849                 $b64url_data = base64url_encode($msg);
1850
1851                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1852
1853                 $type = "application/xml";
1854                 $encoding = "base64url";
1855                 $alg = "RSA-SHA256";
1856
1857                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1858
1859                 $signature = rsa_sign($signable_data,$prvkey);
1860                 $sig = base64url_encode($signature);
1861
1862                 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
1863                                                 "me:env" => array("me:encoding" => "base64url",
1864                                                                 "me:alg" => "RSA-SHA256",
1865                                                                 "me:data" => $data,
1866                                                                 "@attributes" => array("type" => "application/xml"),
1867                                                                 "me:sig" => $sig)));
1868
1869                 $namespaces = array("" => "https://joindiaspora.com/protocol",
1870                                 "me" => "http://salmon-protocol.org/ns/magic-env");
1871
1872                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1873
1874                 logger("magic_env: ".$magic_env, LOGGER_DATA);
1875                 return $magic_env;
1876         }
1877
1878         private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
1879
1880                 logger("Message: ".$msg, LOGGER_DATA);
1881
1882                 // without a public key nothing will work
1883
1884                 if (!$pubkey) {
1885                         logger("pubkey missing: contact id: ".$contact["id"]);
1886                         return false;
1887                 }
1888
1889                 $inner_aes_key = random_string(32);
1890                 $b_inner_aes_key = base64_encode($inner_aes_key);
1891                 $inner_iv = random_string(16);
1892                 $b_inner_iv = base64_encode($inner_iv);
1893
1894                 $outer_aes_key = random_string(32);
1895                 $b_outer_aes_key = base64_encode($outer_aes_key);
1896                 $outer_iv = random_string(16);
1897                 $b_outer_iv = base64_encode($outer_iv);
1898
1899                 $handle = self::my_handle($user);
1900
1901                 $padded_data = pkcs5_pad($msg,16);
1902                 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
1903
1904                 $b64_data = base64_encode($inner_encrypted);
1905
1906
1907                 $b64url_data = base64url_encode($b64_data);
1908                 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
1909
1910                 $type = "application/xml";
1911                 $encoding = "base64url";
1912                 $alg = "RSA-SHA256";
1913
1914                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
1915
1916                 $signature = rsa_sign($signable_data,$prvkey);
1917                 $sig = base64url_encode($signature);
1918
1919                 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
1920                                                         "aes_key" => $b_inner_aes_key,
1921                                                         "author_id" => $handle));
1922
1923                 $decrypted_header = xml::from_array($xmldata, $xml, true);
1924                 $decrypted_header = pkcs5_pad($decrypted_header,16);
1925
1926                 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
1927
1928                 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
1929
1930                 $encrypted_outer_key_bundle = "";
1931                 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
1932
1933                 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
1934
1935                 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
1936
1937                 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
1938                                                                 "ciphertext" => base64_encode($ciphertext)));
1939                 $cipher_json = base64_encode($encrypted_header_json_object);
1940
1941                 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
1942                                                 "me:env" => array("me:encoding" => "base64url",
1943                                                                 "me:alg" => "RSA-SHA256",
1944                                                                 "me:data" => $data,
1945                                                                 "@attributes" => array("type" => "application/xml"),
1946                                                                 "me:sig" => $sig)));
1947
1948                 $namespaces = array("" => "https://joindiaspora.com/protocol",
1949                                 "me" => "http://salmon-protocol.org/ns/magic-env");
1950
1951                 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
1952
1953                 logger("magic_env: ".$magic_env, LOGGER_DATA);
1954                 return $magic_env;
1955         }
1956
1957         private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
1958
1959                 if ($public)
1960                         $magic_env =  self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
1961                 else
1962                         $magic_env =  self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
1963
1964                 // The data that will be transmitted is double encoded via "urlencode", strange ...
1965                 $slap = "xml=".urlencode(urlencode($magic_env));
1966                 return $slap;
1967         }
1968
1969         private function signature($owner, $message) {
1970                 $sigmsg = $message;
1971                 unset($sigmsg["author_signature"]);
1972                 unset($sigmsg["parent_author_signature"]);
1973
1974                 $signed_text = implode(";", $sigmsg);
1975
1976                 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
1977         }
1978
1979         public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
1980
1981                 $a = get_app();
1982
1983                 $enabled = intval(get_config("system", "diaspora_enabled"));
1984                 if(!$enabled)
1985                         return 200;
1986
1987                 $logid = random_string(4);
1988                 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
1989                 if (!$dest_url) {
1990                         logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
1991                         return 0;
1992                 }
1993
1994                 logger("transmit: ".$logid."-".$guid." ".$dest_url);
1995
1996                 if (!$queue_run && was_recently_delayed($contact["id"])) {
1997                         $return_code = 0;
1998                 } else {
1999                         if (!intval(get_config("system", "diaspora_test"))) {
2000                                 post_url($dest_url."/", $slap);
2001                                 $return_code = $a->get_curl_code();
2002                         } else {
2003                                 logger("test_mode");
2004                                 return 200;
2005                         }
2006                 }
2007
2008                 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2009
2010                 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2011                         logger("queue message");
2012
2013                         $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2014                                 intval($contact["id"]),
2015                                 dbesc(NETWORK_DIASPORA),
2016                                 dbesc($slap),
2017                                 intval($public_batch)
2018                         );
2019                         if($r) {
2020                                 logger("add_to_queue ignored - identical item already in queue");
2021                         } else {
2022                                 // queue message for redelivery
2023                                 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2024                         }
2025                 }
2026
2027                 return(($return_code) ? $return_code : (-1));
2028         }
2029
2030
2031         private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "") {
2032
2033                 $data = array("XML" => array("post" => array($type => $message)));
2034
2035                 $msg = xml::from_array($data, $xml);
2036
2037                 logger('message: '.$msg, LOGGER_DATA);
2038                 logger('send guid '.$guid, LOGGER_DEBUG);
2039
2040                 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2041
2042                 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2043
2044                 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2045
2046                 return $return_code;
2047         }
2048
2049         public static function send_share($owner,$contact) {
2050
2051                 $message = array("sender_handle" => self::my_handle($owner),
2052                                 "recipient_handle" => $contact["addr"]);
2053
2054                 return self::build_and_transmit($owner, $contact, "request", $message);
2055         }
2056
2057         public static function send_unshare($owner,$contact) {
2058
2059                 $message = array("post_guid" => $owner["guid"],
2060                                 "diaspora_handle" => self::my_handle($owner),
2061                                 "type" => "Person");
2062
2063                 return self::build_and_transmit($owner, $contact, "retraction", $message);
2064         }
2065
2066         private function is_reshare($body) {
2067                 $body = trim($body);
2068
2069                 // Skip if it isn't a pure repeated messages
2070                 // Does it start with a share?
2071                 if (strpos($body, "[share") > 0)
2072                         return(false);
2073
2074                 // Does it end with a share?
2075                 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2076                         return(false);
2077
2078                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2079                 // Skip if there is no shared message in there
2080                 if ($body == $attributes)
2081                         return(false);
2082
2083                 $guid = "";
2084                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2085                 if ($matches[1] != "")
2086                         $guid = $matches[1];
2087
2088                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2089                 if ($matches[1] != "")
2090                         $guid = $matches[1];
2091
2092                 if ($guid != "") {
2093                         $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2094                                 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2095                         if ($r) {
2096                                 $ret= array();
2097                                 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2098                                 $ret["root_guid"] = $guid;
2099                                 return($ret);
2100                         }
2101                 }
2102
2103                 $profile = "";
2104                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2105                 if ($matches[1] != "")
2106                         $profile = $matches[1];
2107
2108                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2109                 if ($matches[1] != "")
2110                         $profile = $matches[1];
2111
2112                 $ret= array();
2113
2114                 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2115                 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2116                         return(false);
2117
2118                 $link = "";
2119                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2120                 if ($matches[1] != "")
2121                         $link = $matches[1];
2122
2123                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2124                 if ($matches[1] != "")
2125                         $link = $matches[1];
2126
2127                 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2128                 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2129                         return(false);
2130                 return($ret);
2131         }
2132
2133         public static function send_status($item, $owner, $contact, $public_batch = false) {
2134
2135                 $myaddr = self::my_handle($owner);
2136
2137                 $public = (($item["private"]) ? "false" : "true");
2138
2139                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2140
2141                 // Detect a share element and do a reshare
2142                 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2143                         $message = array("root_diaspora_id" => $ret["root_handle"],
2144                                         "root_guid" => $ret["root_guid"],
2145                                         "guid" => $item["guid"],
2146                                         "diaspora_handle" => $myaddr,
2147                                         "public" => $public,
2148                                         "created_at" => $created,
2149                                         "provider_display_name" => $item["app"]);
2150
2151                         $type = "reshare";
2152                 } else {
2153                         $title = $item["title"];
2154                         $body = $item["body"];
2155
2156                         // convert to markdown
2157                         $body = html_entity_decode(bb2diaspora($body));
2158
2159                         // Adding the title
2160                         if(strlen($title))
2161                                 $body = "## ".html_entity_decode($title)."\n\n".$body;
2162
2163                         if ($item["attach"]) {
2164                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2165                                 if(cnt) {
2166                                         $body .= "\n".t("Attachments:")."\n";
2167                                         foreach($matches as $mtch)
2168                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2169                                 }
2170                         }
2171
2172                         $location = array();
2173
2174                         if ($item["location"] != "")
2175                                 $location["address"] = $item["location"];
2176
2177                         if ($item["coord"] != "") {
2178                                 $coord = explode(" ", $item["coord"]);
2179                                 $location["lat"] = $coord[0];
2180                                 $location["lng"] = $coord[1];
2181                         }
2182
2183                         $message = array("raw_message" => $body,
2184                                         "location" => $location,
2185                                         "guid" => $item["guid"],
2186                                         "diaspora_handle" => $myaddr,
2187                                         "public" => $public,
2188                                         "created_at" => $created,
2189                                         "provider_display_name" => $item["app"]);
2190
2191                         if (count($location) == 0)
2192                                 unset($message["location"]);
2193
2194                         $type = "status_message";
2195                 }
2196
2197                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2198         }
2199
2200         private function construct_like($item, $owner) {
2201
2202                 $myaddr = self::my_handle($owner);
2203
2204                 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2205                         dbesc($item["thr-parent"]));
2206                 if(!$p)
2207                         return false;
2208
2209                 $parent = $p[0];
2210
2211                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2212                 $positive = "true";
2213
2214                 return(array("positive" => $positive,
2215                                 "guid" => $item["guid"],
2216                                 "target_type" => $target_type,
2217                                 "parent_guid" => $parent["guid"],
2218                                 "author_signature" => $authorsig,
2219                                 "diaspora_handle" => $myaddr));
2220         }
2221
2222         private function construct_comment($item, $owner) {
2223
2224                 $myaddr = self::my_handle($owner);
2225
2226                 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2227                         intval($item["parent"]),
2228                         intval($item["parent"])
2229                 );
2230
2231                 if (!$p)
2232                         return false;
2233
2234                 $parent = $p[0];
2235
2236                 $text = html_entity_decode(bb2diaspora($item["body"]));
2237
2238                 return(array("guid" => $item["guid"],
2239                                 "parent_guid" => $parent["guid"],
2240                                 "author_signature" => "",
2241                                 "text" => $text,
2242                                 "diaspora_handle" => $myaddr));
2243         }
2244
2245         public static function send_followup($item,$owner,$contact,$public_batch = false) {
2246
2247                 if($item['verb'] === ACTIVITY_LIKE) {
2248                         $message = self::construct_like($item, $owner);
2249                         $type = "like";
2250                 } else {
2251                         $message = self::construct_comment($item, $owner);
2252                         $type = "comment";
2253                 }
2254
2255                 if (!$message)
2256                         return false;
2257
2258                 $message["author_signature"] = self::signature($owner, $message);
2259
2260                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2261         }
2262
2263         private function message_from_signatur($item, $signature) {
2264
2265                 // Split the signed text
2266                 $signed_parts = explode(";", $signature['signed_text']);
2267
2268                 if ($item["deleted"])
2269                         $message = array("parent_author_signature" => "",
2270                                         "target_guid" => $signed_parts[0],
2271                                         "target_type" => $signed_parts[1],
2272                                         "sender_handle" => $signature['signer'],
2273                                         "target_author_signature" => $signature['signature']);
2274                 elseif ($item['verb'] === ACTIVITY_LIKE)
2275                         $message = array("positive" => $signed_parts[0],
2276                                         "guid" => $signed_parts[1],
2277                                         "target_type" => $signed_parts[2],
2278                                         "parent_guid" => $signed_parts[3],
2279                                         "parent_author_signature" => "",
2280                                         "author_signature" => $signature['signature'],
2281                                         "diaspora_handle" => $signed_parts[4]);
2282                 else {
2283                         // Remove the comment guid
2284                         $guid = array_shift($signed_parts);
2285
2286                         // Remove the parent guid
2287                         $parent_guid = array_shift($signed_parts);
2288
2289                         // Remove the handle
2290                         $handle = array_pop($signed_parts);
2291
2292                         // Glue the parts together
2293                         $text = implode(";", $signed_parts);
2294
2295                         $message = array("guid" => $guid,
2296                                         "parent_guid" => $parent_guid,
2297                                         "parent_author_signature" => "",
2298                                         "author_signature" => $signature['signature'],
2299                                         "text" => implode(";", $signed_parts),
2300                                         "diaspora_handle" => $handle);
2301                 }
2302                 return $message;
2303         }
2304
2305         public static function send_relay($item, $owner, $contact, $public_batch = false) {
2306
2307                 if ($item["deleted"]) {
2308                         $sql_sign_id = "retract_iid";
2309                         $type = "relayable_retraction";
2310                 } elseif ($item['verb'] === ACTIVITY_LIKE) {
2311                         $sql_sign_id = "iid";
2312                         $type = "like";
2313                 } else {
2314                         $sql_sign_id = "iid";
2315                         $type = "comment";
2316                 }
2317
2318                 // fetch the original signature
2319
2320                 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `".$sql_sign_id."` = %d LIMIT 1",
2321                         intval($item["id"]));
2322
2323                 if (!$r)
2324                         return self::send_followup($item, $owner, $contact, $public_batch);
2325
2326                 $signature = $r[0];
2327
2328                 // Old way - is used by the internal Friendica functions
2329                 /// @todo Change all signatur storing functions to the new format
2330                 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2331                         $message = self::message_from_signatur($item, $signature);
2332                 else // New way
2333                         $message = json_decode($signature['signed_text']);
2334
2335                 if ($item["deleted"]) {
2336                         $signed_text = $message["target_guid"].';'.$message["target_type"];
2337                         $message["parent_author_signature"] = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2338                 } else
2339                         $message["parent_author_signature"] = self::signature($owner, $message);
2340
2341                 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2342         }
2343
2344         public static function send_retraction($item, $owner, $contact, $public_batch = false) {
2345
2346                 $myaddr = self::my_handle($owner);
2347
2348                 // Check whether the retraction is for a top-level post or whether it's a relayable
2349                 if ($item["uri"] !== $item["parent-uri"]) {
2350                         $msg_type = "relayable_retraction";
2351                         $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2352                 } else {
2353                         $msg_type = "signed_retraction";
2354                         $target_type = "StatusMessage";
2355                 }
2356
2357                 $signed_text = $item["guid"].";".$target_type;
2358
2359                 $message = array("target_guid" => $item['guid'],
2360                                 "target_type" => $target_type,
2361                                 "sender_handle" => $myaddr,
2362                                 "target_author_signature" => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2363
2364                 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2365         }
2366
2367         public static function send_mail($item, $owner, $contact) {
2368
2369                 $myaddr = self::my_handle($owner);
2370
2371                 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2372                         intval($item["convid"]),
2373                         intval($item["uid"])
2374                 );
2375
2376                 if (!$r) {
2377                         logger("conversation not found.");
2378                         return;
2379                 }
2380                 $cnv = $r[0];
2381
2382                 $conv = array(
2383                         "guid" => $cnv["guid"],
2384                         "subject" => $cnv["subject"],
2385                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2386                         "diaspora_handle" => $cnv["creator"],
2387                         "participant_handles" => $cnv["recips"]
2388                 );
2389
2390                 $body = bb2diaspora($item["body"]);
2391                 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2392
2393                 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2394                 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2395
2396                 $msg = array(
2397                         "guid" => $item["guid"],
2398                         "parent_guid" => $cnv["guid"],
2399                         "parent_author_signature" => $sig,
2400                         "author_signature" => $sig,
2401                         "text" => $body,
2402                         "created_at" => $created,
2403                         "diaspora_handle" => $myaddr,
2404                         "conversation_guid" => $cnv["guid"]
2405                 );
2406
2407                 if ($item["reply"]) {
2408                         $message = $msg;
2409                         $type = "message";
2410                 } else {
2411                         $message = array("guid" => $cnv["guid"],
2412                                         "subject" => $cnv["subject"],
2413                                         "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2414                                         "message" => $msg,
2415                                         "diaspora_handle" => $cnv["creator"],
2416                                         "participant_handles" => $cnv["recips"]);
2417
2418                         $type = "conversation";
2419                 }
2420
2421                 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
2422         }
2423 }
2424 ?>