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