]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
fix several probe related issues
[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                 $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
283                         dbesc(NETWORK_DIASPORA),
284                         dbesc($handle)
285                 );
286                 if(count($r))
287                         return $r[0];
288
289                 // we don't care about the uid, we just want to save an expensive webfinger probe
290                 $r = q("select * from contact where network = '%s' and addr = '%s' LIMIT 1",
291                         dbesc(NETWORK_DIASPORA),
292                         dbesc($handle)
293                 );
294                 if(count($r))
295                         return $r[0];
296                 $r = probe_url($handle);
297                 // need to cached this, perhaps in fcontact
298                 if(count($r))
299                         return ($r);
300                 return false;
301 }
302
303 function diaspora_request($importer,$xml) {
304
305         $sender_handle = unxmlify($xml->sender_handle);
306         $recipient_handle = unxmlify($xml->recipient_handle);
307
308         if(! $sender_handle || ! $recipient_handle)
309                 return;
310          
311         $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
312
313
314         if($contact) {
315
316                 // perhaps we were already sharing with this person. Now they're sharing with us.
317                 // That makes us friends.
318
319                 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
320                         q("UPDATE `contact` SET `rel` = %d WHERE `id` = %d AND `uid` = %d LIMIT 1",
321                                 intval(CONTACT_IS_FRIEND),
322                                 intval($contact['id']),
323                                 intval($importer['uid'])
324                         );
325                 }
326                 // send notification?
327                 return;
328         }
329         
330         require_once('include/Scrape.php');
331         $ret = probe_url($sender_handle);
332
333         if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
334                 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
335                 return;
336         }
337
338         $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
339                 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
340                 intval($importer['uid']),
341                 dbesc($ret['network']),
342                 dbesc($ret['addr']),
343                 datetime_convert(),
344                 dbesc($ret['url']),
345                 dbesc($ret['name']),
346                 dbesc($ret['nick']),
347                 dbesc($ret['photo']),
348                 dbesc($ret['pubkey']),
349                 dbesc($ret['notify']),
350                 dbesc($ret['poll']),
351                 1,
352                 2
353         );
354                  
355         // find the contact record we just created
356
357         $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
358
359         $hash = random_string() . (string) time();   // Generate a confirm_key
360         
361         if($contact_record) {
362                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`,`blocked`)
363                         VALUES ( %d, %d, 1, %d, '%s', '%s', '%s', 0 )",
364                         intval($importer['uid']),
365                         intval($contact_record['id']),
366                         0,
367                         dbesc( t('Sharing notification from Diaspora network')),
368                         dbesc($hash),
369                         dbesc(datetime_convert())
370                 );
371         }
372
373         return;
374 }
375
376 function diaspora_post($importer,$xml) {
377
378         $guid = notags(unxmlify($xml->guid));
379         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
380
381         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
382         if(! $contact)
383                 return;
384
385         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
386                 logger('diaspora_post: Ignoring this author.');
387                 http_status_exit(202);
388                 // NOTREACHED
389         }
390
391         $message_id = $diaspora_handle . ':' . $guid;
392         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
393                 intval($importer['uid']),
394                 dbesc($message_id),
395                 dbesc($guid)
396         );
397         if(count($r))
398                 return;
399
400     // allocate a guid on our system - we aren't fixing any collisions.
401         // we're ignoring them
402
403         $g = q("select * from guid where guid = '%s' limit 1",
404                 dbesc($guid)
405         );
406         if(! count($g)) {
407                 q("insert into guid ( guid ) values ( '%s' )",
408                         dbesc($guid)
409                 );
410         }
411
412         $created = unxmlify($xml->created_at);
413         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
414
415         $body = unxmlify($xml->raw_message);
416
417         require_once('library/HTMLPurifier.auto.php');
418         require_once('include/html2bbcode.php');
419
420         $maxlen = get_max_import_size();
421         if($maxlen && (strlen($body) > $maxlen))
422                 $body = substr($body,0, $maxlen);
423
424         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
425
426                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
427                         '[youtube]$1[/youtube]', $body);
428
429                 $body = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
430                         '[youtube]$1[/youtube]', $body);
431
432                 $body = oembed_html2bbcode($body);
433
434                 $config = HTMLPurifier_Config::createDefault();
435                 $config->set('Cache.DefinitionImpl', null);
436                 $purifier = new HTMLPurifier($config);
437                 $body = $purifier->purify($body);
438
439                 $body = html2bbcode($body);
440         }
441
442         $datarray = array();
443         $datarray['uid'] = $importer['uid'];
444         $datarray['contact-id'] = $contact['id'];
445         $datarray['wall'] = 0;
446         $datarray['guid'] = $guid;
447         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
448         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
449         $datarray['private'] = $private;
450         $datarray['parent'] = 0;
451         $datarray['owner-name'] = $contact['name'];
452         $datarray['owner-link'] = $contact['url'];
453         $datarray['owner-avatar'] = $contact['thumb'];
454         $datarray['author-name'] = $contact['name'];
455         $datarray['author-link'] = $contact['url'];
456         $datarray['author-avatar'] = $contact['thumb'];
457         $datarray['body'] = $body;
458
459         item_store($datarray);
460
461         return;
462
463 }
464
465 function diaspora_comment($importer,$xml,$msg) {
466
467         $guid = notags(unxmlify($xml->guid));
468         $parent_guid = notags(unxmlify($xml->parent_guid));
469         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
470         $target_type = notags(unxmlify($xml->target_type));
471         $text = unxmlify($xml->text);
472         $author_signature = notags(unxmlify($xml->author_signature));
473
474         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
475
476         $text = $xml->text;
477
478         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
479         if(! $contact)
480                 return;
481
482         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
483                 logger('diaspora_comment: Ignoring this author.');
484                 http_status_exit(202);
485                 // NOTREACHED
486         }
487
488         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
489                 intval($importer['uid']),
490                 dbesc($parent_guid)
491         );
492         if(! count($r)) {
493                 logger('diaspora_comment: parent item not found: ' . $guid);
494                 return;
495         }
496         $parent_item = $r[0];
497
498         $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
499
500         $author_signature = base64_decode($author_signature);
501
502         if(stricmp($diaspora_handle,$msg['author']) == 0) {
503                 $person = $contact;
504                 $key = $msg['key'];
505         }
506         else {
507                 $person = find_person_by_handle($diaspora_handle);      
508
509                 if(is_array($person) && x($person,'pubkey'))
510                         $key = $person['pubkey'];
511                 else {
512                         logger('diaspora_comment: unable to find author details');
513                         return;
514                 }
515         }
516
517         if(! rsa_verify($author_signed_data,$author_signature,$key)) {
518                 logger('diaspora_comment: verification failed.');
519                 return;
520         }
521
522         if($parent_author_signature) {
523                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $msg['author'];
524
525                 $parent_author_signature = base64_decode($parent_author_signature);
526
527                 $key = $msg['key'];
528
529                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key)) {
530                         logger('diaspora_comment: owner verification failed.');
531                         return;
532                 }
533         }
534
535         // Phew! Everything checks out. Now create an item.
536
537         require_once('library/HTMLPurifier.auto.php');
538         require_once('include/html2bbcode.php');
539
540         $body = $text;
541
542         $maxlen = get_max_import_size();
543         if($maxlen && (strlen($body) > $maxlen))
544                 $body = substr($body,0, $maxlen);
545
546         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
547
548                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
549                         '[youtube]$1[/youtube]', $body);
550
551                 $body = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
552                         '[youtube]$1[/youtube]', $body);
553
554                 $body = oembed_html2bbcode($body);
555
556                 $config = HTMLPurifier_Config::createDefault();
557                 $config->set('Cache.DefinitionImpl', null);
558                 $purifier = new HTMLPurifier($config);
559                 $body = $purifier->purify($body);
560
561                 $body = html2bbcode($body);
562         }
563
564         $message_id = $diaspora_handle . ':' . $guid;
565
566         $datarray = array();
567         $datarray['uid'] = $importer['uid'];
568         $datarray['contact-id'] = $contact['id'];
569         $datarray['wall'] = $parent_item['wall'];
570         $datarray['gravity'] = GRAVITY_COMMENT;
571         $datarray['guid'] = $guid;
572         $datarray['uri'] = $message_id;
573         $datarray['parent-uri'] = $parent_item['uri'];
574
575         // No timestamps for comments? OK, we'll the use current time.
576         $datarray['created'] = $datarray['edited'] = datetime_convert();
577         $datarray['private'] = $parent_item['private'];
578
579         $datarray['owner-name'] = $contact['name'];
580         $datarray['owner-link'] = $contact['url'];
581         $datarray['owner-avatar'] = $contact['thumb'];
582
583         $datarray['author-name'] = $person['name'];
584         $datarray['author-link'] = $person['url'];
585         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
586         $datarray['body'] = $body;
587
588         item_store($datarray);
589
590         return;
591
592 }
593
594 function diaspora_like($importer,$xml,$msg) {
595
596         $guid = notags(unxmlify($xml->guid));
597         $parent_guid = notags(unxmlify($xml->parent_guid));
598         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
599         $target_type = notags(unxmlify($xml->target_type));
600         $positive = notags(unxmlify($xml->positive));
601         $author_signature = notags(unxmlify($xml->author_signature));
602
603         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
604
605         // likes on comments not supported here and likes on photos not supported by Diaspora
606
607         if($target_type !== 'Post')
608                 return;
609
610         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
611         if(! $contact)
612                 return;
613
614         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
615                 logger('diaspora_like: Ignoring this author.');
616                 http_status_exit(202);
617                 // NOTREACHED
618         }
619
620         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
621                 intval($importer['uid']),
622                 dbesc($parent_guid)
623         );
624         if(! count($r)) {
625                 logger('diaspora_like: parent item not found: ' . $guid);
626                 return;
627         }
628
629         $parent_item = $r[0];
630
631         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '$s' LIMIT 1",
632                 intval($importer['uid']),
633                 dbesc($guid)
634         );
635         if(count($r)) {
636                 if($positive === 'true') {
637                         logger('diaspora_like: duplicate like: ' . $guid);
638                         return;
639                 } 
640                 if($positive === 'false') {
641                         q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
642                                 intval($r[0]['id']),
643                                 intval($importer['uid'])
644                         );
645                         // FIXME
646                         //  send notification via proc_run()
647                         return;
648                 }
649         }
650         if($positive === 'false') {
651                 logger('diaspora_like: unlike received with no corresponding like');
652                 return; 
653         }
654
655         $author_signed_data = $guid . ';' . $parent_guid . ';' . $target_type . ';' . $positive . ';' . $diaspora_handle;
656
657         $author_signature = base64_decode($author_signature);
658
659         if(stricmp($diaspora_handle,$msg['author']) == 0) {
660                 $person = $contact;
661                 $key = $msg['key'];
662         }
663         else {
664                 $person = find_person_by_handle($diaspora_handle);      
665                 if(is_array($person) && x($person,'pubkey'))
666                         $key = $person['pubkey'];
667                 else {
668                         logger('diaspora_comment: unable to find author details');
669                         return;
670                 }
671         }
672
673         if(! rsa_verify($author_signed_data,$author_signature,$key)) {
674                 logger('diaspora_like: verification failed.');
675                 return;
676         }
677
678         if($parent_author_signature) {
679                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $target_type . ';' . $positive . ';' . $msg['author'];
680
681                 $parent_author_signature = base64_decode($parent_author_signature);
682
683                 $key = $msg['key'];
684
685                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key)) {
686                         logger('diaspora_like: owner verification failed.');
687                         return;
688                 }
689         }
690
691         // Phew! Everything checks out. Now create an item.
692
693         $uri = $diaspora_handle . ':' . $guid;
694
695         $activity = ACTIVITY_LIKE;
696         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
697         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
698         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
699         $body = $parent_item['body'];
700
701         $obj = <<< EOT
702
703         <object>
704                 <type>$objtype</type>
705                 <local>1</local>
706                 <id>{$parent_item['uri']}</id>
707                 <link>$link</link>
708                 <title></title>
709                 <content>$body</content>
710         </object>
711 EOT;
712         $bodyverb = t('%1$s likes %2$s\'s %3$s');
713
714         $arr = array();
715
716         $arr['uri'] = $uri;
717         $arr['uid'] = $importer['uid'];
718         $arr['contact-id'] = $contact['id'];
719         $arr['type'] = 'activity';
720         $arr['wall'] = $parent_item['wall'];
721         $arr['gravity'] = GRAVITY_LIKE;
722         $arr['parent'] = $parent_item['id'];
723         $arr['parent-uri'] = $parent_item['uri'];
724
725         $datarray['owner-name'] = $contact['name'];
726         $datarray['owner-link'] = $contact['url'];
727         $datarray['owner-avatar'] = $contact['thumb'];
728
729         $datarray['author-name'] = $person['name'];
730         $datarray['author-link'] = $person['url'];
731         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
732         
733         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
734         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
735         $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
736         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
737
738         $arr['private'] = $parent_item['private'];
739         $arr['verb'] = $activity;
740         $arr['object-type'] = $objtype;
741         $arr['object'] = $obj;
742         $arr['visible'] = 1;
743         $arr['unseen'] = 1;
744         $arr['last-child'] = 0;
745
746         $post_id = item_store($arr);    
747
748
749         // FIXME send notification
750
751
752 }
753
754 function diaspora_retraction($importer,$xml) {
755
756         $guid = notags(unxmlify($xml->guid));
757         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
758
759         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
760         if(! $contact)
761                 return;
762
763 //      if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
764 //              logger('diaspora_retraction: Ignoring this author.');
765 //              http_status_exit(202);
766 //              // NOTREACHED
767 //      }
768
769
770
771 }
772
773 function diaspora_share($me,$contact) {
774         $a = get_app();
775         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
776         $theiraddr = $contact['addr'];
777
778         $tpl = get_markup_template('diaspora_share.tpl');
779         $msg = replace_macros($tpl, array(
780                 '$sender' => myaddr,
781                 '$recipient' => $theiraddr
782         ));
783
784         $slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
785
786         post_url($contact['notify'],$slap);
787         $return_code = $a->get_curl_code();
788         return $return_code;
789 }
790
791 function diaspora_send_status($item,$owner,$contact) {
792
793         $a = get_app();
794         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
795         $theiraddr = $contact['addr'];
796         require_once('include/bbcode.php');
797
798         $body = xmlify(bbcode($item['body']));
799         $public = (($item['private']) ? 'false' : 'true');
800
801         require_once('include/datetime.php');
802         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d h:i:s \U\T\C');
803
804         $tpl = get_markup_template('diaspora_post.tpl');
805         $msg = replace_macros($tpl, array(
806                 '$body' => $body,
807                 '$guid' => $item['guid'],
808                 '$handle' => xmlify($myaddr),
809                 '$public' => $public,
810                 '$created' => $created
811         ));
812
813         logger('diaspora_send_status: base message: ' . $msg, LOGGER_DATA);
814
815         $slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey']));
816
817         post_url($contact['notify'],$slap);
818         $return_code = $a->get_curl_code();
819         logger('diaspora_send_status: returns: ' . $return_code);
820         return $return_code;
821 }
822