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