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