]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
diaspora continued...
[friendica.git] / include / diaspora.php
1 <?php
2
3 require_once('include/crypto.php');
4 require_once('include/items.php');
5
6 function get_diaspora_key($uri) {
7         $key = '';
8
9         logger('Fetching diaspora key for: ' . $uri);
10
11         $arr = lrdd($uri);
12
13         if(is_array($arr)) {
14                 foreach($arr as $a) {
15                         if($a['@attributes']['rel'] === 'diaspora-public-key') {
16                                 $key = base64_decode($a['@attributes']['href']);
17                         }
18                 }
19         }
20         else {
21                 return '';
22         }
23
24         if($key)
25                 return rsatopem($key);
26         return '';
27 }
28
29
30 function diaspora_base_message($type,$data) {
31
32         $tpl = get_markup_template('diaspora_' . $type . '.tpl');
33         if(! $tpl) 
34                 return '';
35         return replace_macros($tpl,$data);
36
37 }
38
39
40 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey) {
41         $a = get_app();
42
43         $inner_aes_key = random_string(32);
44         $b_inner_aes_key = base64_encode($inner_aes_key);
45         $inner_iv = random_string(32);
46         $b_inner_iv = base64_encode($inner_iv);
47
48         $outer_aes_key = random_string(32);
49         $b_outer_aes_key = base64_encode($outer_aes_key);
50         $outer_iv = random_string(32);
51         $b_outer_iv = base64_encode($outer_iv);
52         
53         $handle = 'acct:' . $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
54
55         $padded_data = pkcs5_pad($msg,16);
56         $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
57
58         $b64_data = base64_encode($inner_encrypted);
59
60
61         $b64url_data = base64url_encode($b64_data);
62         $b64url_stripped = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
63     $lines = str_split($b64url_stripped,60);
64     $data = implode("\n",$lines);
65         $data = $data . (($data[-1] != "\n") ? "\n" : '') ;
66         $type = 'application/atom+xml';
67         $encoding = 'base64url';
68         $alg = 'RSA-SHA256';
69
70         $signable_data = $data  . '.' . base64url_encode($type) . "\n" . '.' 
71                 . base64url_encode($encoding) . "\n" . '.' . base64url_encode($alg) . "\n";
72
73         $signature = rsa_sign($signable_data,$prvkey);
74         $sig = base64url_encode($signature);
75
76 $decrypted_header = <<< EOT
77 <decrypted_header>
78   <iv>$b_inner_iv</iv>
79   <aes_key>$b_inner_aes_key</aes_key>
80   <author>
81     <name>{$user['username']}</name>
82     <uri>$handle</uri>
83   </author>
84 </decrypted_header>
85 EOT;
86
87         $decrypted_header = pkcs5_pad($decrypted_header,16);
88
89         $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
90
91         $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
92         $encrypted_outer_key_bundle = '';
93         openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
94         
95         $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
96         $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle), 
97                 'ciphertext' => base64_encode($ciphertext)));
98         $encrypted_header = '<encrypted_header>' . base64_encode($encrypted_header_json_object) . '</encrypted_header>';
99
100 $magic_env = <<< EOT
101 <?xml version='1.0' encoding='UTF-8'?>
102 <entry xmlns='http://www.w3.org/2005/Atom'>
103   $encrypted_header
104   <me:env xmlns:me="http://salmon-protocol.org/ns/magic-env">
105     <me:encoding>base64url</me:encoding>
106     <me:alg>RSA-SHA256</me:alg>
107     <me:data type="application/atom+xml">$data</me:data>
108     <me:sig>$sig</me:sig>
109   </me:env>
110 </entry>
111 EOT;
112
113         return $magic_env;
114
115 }
116
117 /**
118  *
119  * diaspora_decode($importer,$xml)
120  *   array $importer -> from user table
121  *   string $xml -> urldecoded Diaspora salmon 
122  *
123  * Returns array
124  * 'message' -> decoded Diaspora XML message
125  * 'author' -> author diaspora handle
126  * 'key' -> author public key (converted to pkcs#8)
127  *
128  * Author and key are used elsewhere to save a lookup for verifying replies and likes
129  */
130
131
132 function diaspora_decode($importer,$xml) {
133
134         $basedom = parse_xml_string($xml);
135
136         $atom = $basedom->children(NAMESPACE_ATOM1);
137
138         // Diaspora devs: This is kind of sucky - 'encrypted_header' does not belong in the atom namespace
139
140         $encrypted_header = json_decode(base64_decode($atom->encrypted_header));
141         
142         $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
143         $ciphertext = base64_decode($encrypted_header->ciphertext);
144
145         $outer_key_bundle = '';
146         openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
147
148         $j_outer_key_bundle = json_decode($outer_key_bundle);
149
150         $outer_iv = base64_decode($j_outer_key_bundle->iv);
151         $outer_key = base64_decode($j_outer_key_bundle->key);
152
153         $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
154
155         $decrypted = pkcs5_unpad($decrypted);
156
157         /**
158          * $decrypted now contains something like
159          *
160          *  <decrypted_header>
161          *     <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
162          *     <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
163          *     <author>
164          *       <name>Ryan Hughes</name>
165          *       <uri>acct:galaxor@diaspora.pirateship.org</uri>
166          *     </author>
167          *  </decrypted_header>
168          */
169
170         logger('decrypted: ' . $decrypted);
171         $idom = parse_xml_string($decrypted,false);
172
173         $inner_iv = base64_decode($idom->iv);
174         $inner_aes_key = base64_decode($idom->aes_key);
175
176         $author_link = str_replace('acct:','',$idom->author->uri);
177
178         $dom = $basedom->children(NAMESPACE_SALMON_ME);
179
180         // figure out where in the DOM tree our data is hiding
181
182         if($dom->provenance->data)
183                 $base = $dom->provenance;
184         elseif($dom->env->data)
185                 $base = $dom->env;
186         elseif($dom->data)
187                 $base = $dom;
188         
189         if(! $base) {
190                 logger('mod-diaspora: unable to locate salmon data in xml ');
191                 http_status_exit(400);
192         }
193
194
195         // Stash the signature away for now. We have to find their key or it won't be good for anything.
196         $signature = base64url_decode($base->sig);
197
198         // unpack the  data
199
200         // strip whitespace so our data element will return to one big base64 blob
201         $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
202
203         // Add back the 60 char linefeeds
204
205         // Diaspora devs: This completely violates the entire principle of salmon magic signatures,
206         // which was to have a message signing format that was completely ambivalent to linefeeds 
207         // and transport whitespace mangling, and base64 wrapping rules. Guess what? PHP and Ruby 
208         // use different linelengths for base64 output. 
209
210     $lines = str_split($data,60);
211     $data = implode("\n",$lines);
212
213
214         // stash away some other stuff for later
215
216         $type = $base->data[0]->attributes()->type[0];
217         $keyhash = $base->sig[0]->attributes()->keyhash[0];
218         $encoding = $base->encoding;
219         $alg = $base->alg;
220
221         // Diaspora devs: I can't even begin to tell you how sucky this is. Read the freaking spec.
222
223         $signed_data = $data  . (($data[-1] != "\n") ? "\n" : '') . '.' . base64url_encode($type) . "\n" . '.' . base64url_encode($encoding) . "\n" . '.' . base64url_encode($alg) . "\n";
224
225
226         // decode the data
227         $data = base64url_decode($data);
228
229         // Now pull out the inner encrypted blob
230
231         $inner_encrypted = base64_decode($data);
232
233         $inner_decrypted = 
234         $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
235
236         $inner_decrypted = pkcs5_unpad($inner_decrypted);
237
238         if(! $author_link) {
239                 logger('mod-diaspora: Could not retrieve author URI.');
240                 http_status_exit(400);
241         }
242
243         // Once we have the author URI, go to the web and try to find their public key
244         // *** or look it up locally ***
245
246         logger('mod-diaspora: Fetching key for ' . $author_link );
247
248         // Get diaspora public key (pkcs#1) and convert to pkcs#8
249
250         $key = get_diaspora_key($author_link);
251
252         if(! $key) {
253                 logger('mod-diaspora: Could not retrieve author key.');
254                 http_status_exit(400);
255         }
256
257         $verify = rsa_verify($signed_data,$signature,$key);
258
259         if(! $verify) {
260                 logger('mod-diaspora: Message did not verify. Discarding.');
261                 http_status_exit(400);
262         }
263
264         logger('mod-diaspora: Message verified.');
265
266         return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
267
268 }
269
270 function diaspora_get_contact_by_handle($uid,$handle) {
271         $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
272                 dbesc(NETWORK_DIASPORA),
273                 intval($uid),
274                 dbesc($handle)
275         );
276         if($r && count($r))
277                 return $r[0];
278         return false;
279 }
280
281 function find_person_by_handle($handle) {
282                 // we don't care about the uid, we just want to save an expensive webfinger probe
283                 $r = q("select * from contact where network = '%s' and addr = '%s' LIMIT 1",
284                         dbesc(NETWORK_DIASPORA),
285                         dbesc($handle)
286                 );
287                 if(count($r))
288                         return $r[0];
289                 $r = probe_url($handle);
290                 // need to cached this, perhaps in fcontact
291                 if(count($r))
292                         return ($r);
293                 return false;
294 }
295
296 function diaspora_request($importer,$xml) {
297
298         $sender_handle = unxmlify($xml->sender_handle);
299         $recipient_handle = unxmlify($xml->recipient_handle);
300
301         if(! $sender_handle || ! $recipient_handle)
302                 return;
303          
304         $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
305
306
307         if($contact) {
308
309                 // perhaps we were already sharing with this person. Now they're sharing with us.
310                 // That makes us friends.
311
312                 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
313                         q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
314                                 intval(CONTACT_IS_FRIEND),
315                                 intval($contact['id']),
316                                 intval($importer['uid'])
317                         );
318                 }
319                 // send notification?
320                 return;
321         }
322         
323         require_once('include/Scrape.php');
324         $ret = probe_url($sender_handle);
325
326         if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
327                 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
328                 return;
329         }
330
331         $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
332                 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
333                 intval($importer['uid']),
334                 dbesc($ret['network']),
335                 dbesc($ret['addr']),
336                 datetime_convert(),
337                 dbesc($ret['url']),
338                 dbesc($ret['name']),
339                 dbesc($ret['nick']),
340                 dbesc($ret['photo']),
341                 dbesc($ret['pubkey']),
342                 dbesc($ret['notify']),
343                 dbesc($ret['poll']),
344                 1,
345                 2
346         );
347                  
348         // find the contact record we just created
349
350         $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
351
352         $hash = random_string() . (string) time();   // Generate a confirm_key
353         
354         if($contact_record) {
355                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`,`blocked`)
356                         VALUES ( %d, %d, 1, %d, '%s', '%s', '%s', 0 )",
357                         intval($importer['uid']),
358                         intval($contact_record['id']),
359                         0,
360                         dbesc( t('Sharing notification from Diaspora network')),
361                         dbesc($hash),
362                         dbesc(datetime_convert())
363                 );
364         }
365
366         return;
367 }
368
369 function diaspora_post($importer,$xml) {
370
371         $guid = notags(unxmlify($xml->guid));
372         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
373
374         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
375         if(! $contact)
376                 return;
377
378         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
379                 logger('diaspora_post: Ignoring this author.');
380                 http_status_exit(202);
381                 // NOTREACHED
382         }
383
384         $message_id = $diaspora_handle . ':' . $guid;
385         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
386                 intval($importer['uid']),
387                 dbesc($message_id),
388                 dbesc($guid)
389         );
390         if(count($r))
391                 return;
392
393     // allocate a guid on our system - we aren't fixing any collisions.
394         // we're ignoring them
395
396         $g = q("select * from guid where guid = '%s' limit 1",
397                 dbesc($guid)
398         );
399         if(! count($g)) {
400                 q("insert into guid ( guid ) values ( '%s' )",
401                         dbesc($guid)
402                 );
403         }
404
405         $created = unxmlify($xml->created_at);
406         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
407
408         $body = unxmlify($xml->raw_message);
409
410         require_once('library/HTMLPurifier.auto.php');
411         require_once('include/html2bbcode.php');
412
413         $maxlen = get_max_import_size();
414         if($maxlen && (strlen($body) > $maxlen))
415                 $body = substr($body,0, $maxlen);
416
417         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
418
419                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
420                         '[youtube]$1[/youtube]', $body);
421
422                 $body = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
423                         '[youtube]$1[/youtube]', $body);
424
425                 $body = oembed_html2bbcode($body);
426
427                 $config = HTMLPurifier_Config::createDefault();
428                 $config->set('Cache.DefinitionImpl', null);
429                 $purifier = new HTMLPurifier($config);
430                 $body = $purifier->purify($body);
431
432                 $body = html2bbcode($body);
433         }
434
435         $datarray = array();
436         $datarray['uid'] = $importer['uid'];
437         $datarray['contact-id'] = $contact['id'];
438         $datarray['wall'] = 0;
439         $datarray['guid'] = $guid;
440         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
441         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
442         $datarray['private'] = $private;
443         $datarray['parent'] = 0;
444         $datarray['owner-name'] = $contact['name'];
445         $datarray['owner-link'] = $contact['url'];
446         $datarray['owner-avatar'] = $contact['thumb'];
447         $datarray['author-name'] = $contact['name'];
448         $datarray['author-link'] = $contact['url'];
449         $datarray['author-avatar'] = $contact['thumb'];
450         $datarray['body'] = $body;
451
452         item_store($datarray);
453
454         return;
455
456 }
457
458 function diaspora_comment($importer,$xml,$msg) {
459
460         $guid = notags(unxmlify($xml->guid));
461         $parent_guid = notags(unxmlify($xml->parent_guid));
462         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
463         $target_type = notags(unxmlify($xml->target_type));
464         $text = unxmlify($xml->text);
465         $author_signature = notags(unxmlify($xml->author_signature));
466
467         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
468
469         $text = $xml->text;
470
471         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
472         if(! $contact)
473                 return;
474
475         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
476                 logger('diaspora_comment: Ignoring this author.');
477                 http_status_exit(202);
478                 // NOTREACHED
479         }
480
481         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
482                 intval($importer['uid']),
483                 dbesc($parent_guid)
484         );
485         if(! count($r)) {
486                 logger('diaspora_comment: parent item not found: ' . $guid);
487                 return;
488         }
489         $parent_item = $r[0];
490
491         $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
492
493         $author_signature = base64_decode($author_signature);
494
495         if(stricmp($diaspora_handle,$msg['author']) == 0) {
496                 $person = $contact;
497                 $key = $msg['key'];
498         }
499         else {
500                 $person = find_person_by_handle($diaspora_handle);      
501
502                 if(is_array($person) && x($person,'pubkey'))
503                         $key = $person['pubkey'];
504                 else {
505                         logger('diaspora_comment: unable to find author details');
506                         return;
507                 }
508         }
509
510         if(! rsa_verify($author_signed_data,$author_signature,$key)) {
511                 logger('diaspora_comment: verification failed.');
512                 return;
513         }
514
515         if($parent_author_signature) {
516                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $msg['author'];
517
518                 $parent_author_signature = base64_decode($parent_author_signature);
519
520                 $key = $msg['key'];
521
522                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key)) {
523                         logger('diaspora_comment: owner verification failed.');
524                         return;
525                 }
526         }
527
528         // Phew! Everything checks out. Now create an item.
529
530         require_once('library/HTMLPurifier.auto.php');
531         require_once('include/html2bbcode.php');
532
533         $body = $text;
534
535         $maxlen = get_max_import_size();
536         if($maxlen && (strlen($body) > $maxlen))
537                 $body = substr($body,0, $maxlen);
538
539         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
540
541                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
542                         '[youtube]$1[/youtube]', $body);
543
544                 $body = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
545                         '[youtube]$1[/youtube]', $body);
546
547                 $body = oembed_html2bbcode($body);
548
549                 $config = HTMLPurifier_Config::createDefault();
550                 $config->set('Cache.DefinitionImpl', null);
551                 $purifier = new HTMLPurifier($config);
552                 $body = $purifier->purify($body);
553
554                 $body = html2bbcode($body);
555         }
556
557         $message_id = $diaspora_handle . ':' . $guid;
558
559         $datarray = array();
560         $datarray['uid'] = $importer['uid'];
561         $datarray['contact-id'] = $contact['id'];
562         $datarray['wall'] = $parent_item['wall'];
563         $datarray['gravity'] = GRAVITY_COMMENT;
564         $datarray['guid'] = $guid;
565         $datarray['uri'] = $message_id;
566         $datarray['parent-uri'] = $parent_item['uri'];
567
568         // No timestamps for comments? OK, we'll the use current time.
569         $datarray['created'] = $datarray['edited'] = datetime_convert();
570         $datarray['private'] = $parent_item['private'];
571
572         $datarray['owner-name'] = $contact['name'];
573         $datarray['owner-link'] = $contact['url'];
574         $datarray['owner-avatar'] = $contact['thumb'];
575
576         $datarray['author-name'] = $person['name'];
577         $datarray['author-link'] = $person['url'];
578         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
579         $datarray['body'] = $body;
580
581         item_store($datarray);
582
583         return;
584
585 }
586
587 function diaspora_like($importer,$xml,$msg) {
588
589         $guid = notags(unxmlify($xml->guid));
590         $parent_guid = notags(unxmlify($xml->parent_guid));
591         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
592         $target_type = notags(unxmlify($xml->target_type));
593         $positive = notags(unxmlify($xml->positive));
594         $author_signature = notags(unxmlify($xml->author_signature));
595
596         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
597
598         // likes on comments not supported here and likes on photos not supported by Diaspora
599
600         if($target_type !== 'Post')
601                 return;
602
603         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
604         if(! $contact)
605                 return;
606
607         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
608                 logger('diaspora_like: Ignoring this author.');
609                 http_status_exit(202);
610                 // NOTREACHED
611         }
612
613         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
614                 intval($importer['uid']),
615                 dbesc($parent_guid)
616         );
617         if(! count($r)) {
618                 logger('diaspora_like: parent item not found: ' . $guid);
619                 return;
620         }
621
622         $parent_item = $r[0];
623
624         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '$s' LIMIT 1",
625                 intval($importer['uid']),
626                 dbesc($guid)
627         );
628         if(count($r)) {
629                 if($positive === 'true') {
630                         logger('diaspora_like: duplicate like: ' . $guid);
631                         return;
632                 } 
633                 if($positive === 'false') {
634                         q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
635                                 intval($r[0]['id']),
636                                 intval($importer['uid'])
637                         );
638                         // FIXME
639                         //  send notification via proc_run()
640                         return;
641                 }
642         }
643         if($positive === 'false') {
644                 logger('diaspora_like: unlike received with no corresponding like');
645                 return; 
646         }
647
648         $author_signed_data = $guid . ';' . $parent_guid . ';' . $target_type . ';' . $positive . ';' . $diaspora_handle;
649
650         $author_signature = base64_decode($author_signature);
651
652         if(stricmp($diaspora_handle,$msg['author']) == 0) {
653                 $person = $contact;
654                 $key = $msg['key'];
655         }
656         else {
657                 $person = find_person_by_handle($diaspora_handle);      
658                 if(is_array($person) && x($person,'pubkey'))
659                         $key = $person['pubkey'];
660                 else {
661                         logger('diaspora_comment: unable to find author details');
662                         return;
663                 }
664         }
665
666         if(! rsa_verify($author_signed_data,$author_signature,$key)) {
667                 logger('diaspora_like: verification failed.');
668                 return;
669         }
670
671         if($parent_author_signature) {
672                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $target_type . ';' . $positive . ';' . $msg['author'];
673
674                 $parent_author_signature = base64_decode($parent_author_signature);
675
676                 $key = $msg['key'];
677
678                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key)) {
679                         logger('diaspora_like: owner verification failed.');
680                         return;
681                 }
682         }
683
684         // Phew! Everything checks out. Now create an item.
685
686         $uri = $diaspora_handle . ':' . $guid;
687
688         $activity = ACTIVITY_LIKE;
689         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
690         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
691         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
692         $body = $parent_item['body'];
693
694         $obj = <<< EOT
695
696         <object>
697                 <type>$objtype</type>
698                 <local>1</local>
699                 <id>{$parent_item['uri']}</id>
700                 <link>$link</link>
701                 <title></title>
702                 <content>$body</content>
703         </object>
704 EOT;
705         $bodyverb = t('%1$s likes %2$s\'s %3$s');
706
707         $arr = array();
708
709         $arr['uri'] = $uri;
710         $arr['uid'] = $importer['uid'];
711         $arr['contact-id'] = $contact['id'];
712         $arr['type'] = 'activity';
713         $arr['wall'] = $parent_item['wall'];
714         $arr['gravity'] = GRAVITY_LIKE;
715         $arr['parent'] = $parent_item['id'];
716         $arr['parent-uri'] = $parent_item['uri'];
717
718         $datarray['owner-name'] = $contact['name'];
719         $datarray['owner-link'] = $contact['url'];
720         $datarray['owner-avatar'] = $contact['thumb'];
721
722         $datarray['author-name'] = $person['name'];
723         $datarray['author-link'] = $person['url'];
724         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
725         
726         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
727         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
728         $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
729         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
730
731         $arr['private'] = $parent_item['private'];
732         $arr['verb'] = $activity;
733         $arr['object-type'] = $objtype;
734         $arr['object'] = $obj;
735         $arr['visible'] = 1;
736         $arr['unseen'] = 1;
737         $arr['last-child'] = 0;
738
739         $post_id = item_store($arr);    
740
741
742         // FIXME send notification
743
744
745 }
746
747 function diaspora_retraction($importer,$xml) {
748
749         $guid = notags(unxmlify($xml->guid));
750         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
751
752         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
753         if(! $contact)
754                 return;
755
756 //      if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
757 //              logger('diaspora_retraction: Ignoring this author.');
758 //              http_status_exit(202);
759 //              // NOTREACHED
760 //      }
761
762
763
764 }
765
766 function diaspora_share($me,$contact) {
767         $a = get_app();
768         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
769         $theiraddr = $contact['addr'];
770
771         $tpl = get_markup_template('diaspora_share.tpl');
772         $msg = replace_macros($tpl, array(
773                 '$sender' => myaddr,
774                 '$recipient' => $theiraddr
775         ));
776
777         $slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
778
779         post_url($contact['notify'],$slap);
780         $return_code = $a->get_curl_code();
781         return $return_code;
782 }
783
784 function diaspora_send_status($item,$owner,$contact) {
785
786         $a = get_app();
787         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
788         $theiraddr = $contact['addr'];
789         require_once('include/bbcode.php');
790
791         $body = xmlify(bbcode($item['body']));
792         $public = (($item['private']) ? 'false' : 'true');
793
794         require_once('include/datetime.php');
795         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d h:i:s \U\T\C');
796
797         $tpl = get_markup_template('diaspora_post.tpl');
798         $msg = replace_macros($tpl, array(
799                 '$body' => $body,
800                 '$guid' => $item['guid'],
801                 '$handle' => xmlify($myaddr),
802                 '$public' => $public,
803                 '$created' => $created
804         ));
805
806         logger('diaspora_send_status: base message: ' . $msg, LOGGER_DATA);
807
808         $slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey']));
809
810         post_url($contact['notify'],$slap);
811         $return_code = $a->get_curl_code();
812         logger('diaspora_send_status: returns: ' . $return_code);
813         return $return_code;
814 }
815