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