]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
08dcee138bd22212df4829d9fd962206c62cc2a1
[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
145         $decrypted = pkcs5_unpad($decrypted);
146
147         /**
148          * $decrypted now contains something like
149          *
150          *  <decrypted_header>
151          *     <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
152          *     <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
153          *     <author>
154          *       <name>Ryan Hughes</name>
155          *       <uri>acct:galaxor@diaspora.pirateship.org</uri>
156          *     </author>
157          *  </decrypted_header>
158          */
159
160         logger('decrypted: ' . $decrypted);
161         $idom = parse_xml_string($decrypted,false);
162
163         $inner_iv = base64_decode($idom->iv);
164         $inner_aes_key = base64_decode($idom->aes_key);
165
166         $author_link = str_replace('acct:','',$idom->author->uri);
167
168         $dom = $basedom->children(NAMESPACE_SALMON_ME);
169
170         // figure out where in the DOM tree our data is hiding
171
172         if($dom->provenance->data)
173                 $base = $dom->provenance;
174         elseif($dom->env->data)
175                 $base = $dom->env;
176         elseif($dom->data)
177                 $base = $dom;
178         
179         if(! $base) {
180                 logger('mod-diaspora: unable to locate salmon data in xml ');
181                 http_status_exit(400);
182         }
183
184
185         // Stash the signature away for now. We have to find their key or it won't be good for anything.
186         $signature = base64url_decode($base->sig);
187
188         // unpack the  data
189
190         // strip whitespace so our data element will return to one big base64 blob
191         $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
192
193         // Add back the 60 char linefeeds
194
195         // This completely violates the entire principle of salmon magic signatures,
196         // which was to have a message signing format that was completely ambivalent to linefeeds 
197         // and transport whitespace mangling, and base64 wrapping rules. Guess what? PHP and Ruby 
198         // use different linelengths for base64 output. 
199
200     $lines = str_split($data,60);
201     $data = implode("\n",$lines);
202
203
204         // stash away some other stuff for later
205
206         $type = $base->data[0]->attributes()->type[0];
207         $keyhash = $base->sig[0]->attributes()->keyhash[0];
208         $encoding = $base->encoding;
209         $alg = $base->alg;
210
211         // I can't even begin to tell you how sucky this is. Please read the spec.
212
213         $signed_data = $data  . (($data[-1] != "\n") ? "\n" : '') . '.' . base64url_encode($type) . "\n" . '.' . base64url_encode($encoding) . "\n" . '.' . base64url_encode($alg) . "\n";
214
215
216         // decode the data
217         $data = base64url_decode($data);
218
219         // Now pull out the inner encrypted blob
220
221         $inner_encrypted = base64_decode($data);
222
223         $inner_decrypted = 
224         $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
225
226         $inner_decrypted = pkcs5_unpad($inner_decrypted);
227
228         if(! $author_link) {
229                 logger('mod-diaspora: Could not retrieve author URI.');
230                 http_status_exit(400);
231         }
232
233         // Once we have the author URI, go to the web and try to find their public key
234         // (first this will look it up locally if it is in the fcontact cache)
235         // This will also convert diaspora public key from pkcs#1 to pkcs#8
236
237         logger('mod-diaspora: Fetching key for ' . $author_link );
238         $key = get_diaspora_key($author_link);
239
240         if(! $key) {
241                 logger('mod-diaspora: Could not retrieve author key.');
242                 http_status_exit(400);
243         }
244
245         $verify = rsa_verify($signed_data,$signature,$key);
246
247         if(! $verify) {
248                 logger('mod-diaspora: Message did not verify. Discarding.');
249                 http_status_exit(400);
250         }
251
252         logger('mod-diaspora: Message verified.');
253
254         return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
255
256 }
257
258 function diaspora_get_contact_by_handle($uid,$handle) {
259         $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
260                 dbesc(NETWORK_DIASPORA),
261                 intval($uid),
262                 dbesc($handle)
263         );
264         if($r && count($r))
265                 return $r[0];
266         return false;
267 }
268
269 function find_diaspora_person_by_handle($handle) {
270         $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
271                 dbesc(NETWORK_DIASPORA),
272                 dbesc($handle)
273         );
274         if(count($r)) {
275                 // update record occasionally so it doesn't get stale
276                 $d = strtotime($r[0]['updated'] . ' +00:00');
277                 if($d < strtotime('now - 14 days')) {
278                         q("delete from fcontact where id = %d limit 1",
279                                 intval($r[0]['id'])
280                         );
281                 }
282                 else
283                         return $r[0];
284         }
285         require_once('include/Scrape.php');
286         $r = probe_url($handle, PROBE_DIASPORA);
287         if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
288                 add_fcontact($r);
289                 return ($r);
290         }
291         return false;
292 }
293
294         
295
296 function diaspora_request($importer,$xml) {
297
298         $sender_handle = unxmlify($xml->sender_handle);
299         $recipient_handle = unxmlify($xml->recipient_handle);
300
301         if(! $sender_handle || ! $recipient_handle)
302                 return;
303          
304         $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
305
306
307         if($contact) {
308
309                 // perhaps we were already sharing with this person. Now they're sharing with us.
310                 // That makes us friends.
311
312                 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
313                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
314                                 intval(CONTACT_IS_FRIEND),
315                                 intval($contact['id']),
316                                 intval($importer['uid'])
317                         );
318                 }
319                 // send notification?
320                 return;
321         }
322         
323         $ret = find_diaspora_person_by_handle($sender_handle);
324
325
326         if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
327                 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
328                 return;
329         }
330
331         $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
332                 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
333                 intval($importer['uid']),
334                 dbesc($ret['network']),
335                 dbesc($ret['addr']),
336                 datetime_convert(),
337                 dbesc($ret['url']),
338                 dbesc($ret['name']),
339                 dbesc($ret['nick']),
340                 dbesc($ret['photo']),
341                 dbesc($ret['pubkey']),
342                 dbesc($ret['notify']),
343                 dbesc($ret['poll']),
344                 1,
345                 2
346         );
347                  
348         // find the contact record we just created
349
350         $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
351
352         $hash = random_string() . (string) time();   // Generate a confirm_key
353         
354         if($contact_record) {
355                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
356                         VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
357                         intval($importer['uid']),
358                         intval($contact_record['id']),
359                         0,
360                         0,
361                         dbesc( t('Sharing notification from Diaspora network')),
362                         dbesc($hash),
363                         dbesc(datetime_convert())
364                 );
365         }
366
367         return;
368 }
369
370 function diaspora_post($importer,$xml) {
371
372         $guid = notags(unxmlify($xml->guid));
373         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
374
375         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
376         if(! $contact)
377                 return;
378
379         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
380                 logger('diaspora_post: Ignoring this author.');
381                 http_status_exit(202);
382                 // NOTREACHED
383         }
384
385         $message_id = $diaspora_handle . ':' . $guid;
386         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
387                 intval($importer['uid']),
388                 dbesc($message_id),
389                 dbesc($guid)
390         );
391         if(count($r))
392                 return;
393
394     // allocate a guid on our system - we aren't fixing any collisions.
395         // we're ignoring them
396
397         $g = q("select * from guid where guid = '%s' limit 1",
398                 dbesc($guid)
399         );
400         if(! count($g)) {
401                 q("insert into guid ( guid ) values ( '%s' )",
402                         dbesc($guid)
403                 );
404         }
405
406         $created = unxmlify($xml->created_at);
407         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
408
409         $body = unxmlify($xml->raw_message);
410
411         require_once('library/HTMLPurifier.auto.php');
412         require_once('include/html2bbcode.php');
413
414         $maxlen = get_max_import_size();
415         if($maxlen && (strlen($body) > $maxlen))
416                 $body = substr($body,0, $maxlen);
417
418         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
419
420                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
421                         '[youtube]$1[/youtube]', $body);
422
423                 $body = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
424                         '[youtube]$1[/youtube]', $body);
425
426                 $body = oembed_html2bbcode($body);
427
428                 $config = HTMLPurifier_Config::createDefault();
429                 $config->set('Cache.DefinitionImpl', null);
430                 $purifier = new HTMLPurifier($config);
431                 $body = $purifier->purify($body);
432
433                 $body = html2bbcode($body);
434         }
435
436         $datarray = array();
437         $datarray['uid'] = $importer['uid'];
438         $datarray['contact-id'] = $contact['id'];
439         $datarray['wall'] = 0;
440         $datarray['guid'] = $guid;
441         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
442         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
443         $datarray['private'] = $private;
444         $datarray['parent'] = 0;
445         $datarray['owner-name'] = $contact['name'];
446         $datarray['owner-link'] = $contact['url'];
447         $datarray['owner-avatar'] = $contact['thumb'];
448         $datarray['author-name'] = $contact['name'];
449         $datarray['author-link'] = $contact['url'];
450         $datarray['author-avatar'] = $contact['thumb'];
451         $datarray['body'] = $body;
452
453         item_store($datarray);
454
455         return;
456
457 }
458
459 function diaspora_comment($importer,$xml,$msg) {
460
461         $guid = notags(unxmlify($xml->guid));
462         $parent_guid = notags(unxmlify($xml->parent_guid));
463         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
464         $target_type = notags(unxmlify($xml->target_type));
465         $text = unxmlify($xml->text);
466         $author_signature = notags(unxmlify($xml->author_signature));
467
468         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
469
470         $text = $xml->text;
471
472         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
473         if(! $contact)
474                 return;
475
476         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
477                 logger('diaspora_comment: Ignoring this author.');
478                 http_status_exit(202);
479                 // NOTREACHED
480         }
481
482         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
483                 intval($importer['uid']),
484                 dbesc($parent_guid)
485         );
486         if(! count($r)) {
487                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
488                 return;
489         }
490         $parent_item = $r[0];
491
492         $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
493
494         $author_signature = base64_decode($author_signature);
495
496         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
497                 $person = $contact;
498                 $key = $msg['key'];
499         }
500         else {
501                 $person = find_diaspora_person_by_handle($diaspora_handle);     
502
503                 if(is_array($person) && x($person,'pubkey'))
504                         $key = $person['pubkey'];
505                 else {
506                         logger('diaspora_comment: unable to find author details');
507                         return;
508                 }
509         }
510
511         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha1')) {
512                 logger('diaspora_comment: verification failed.');
513 // until we figure out what is different about their signing algorithm, accept it
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,'sha1')) {
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         $a = get_app();
603         $guid = notags(unxmlify($xml->guid));
604         $parent_guid = notags(unxmlify($xml->parent_guid));
605         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
606         $target_type = notags(unxmlify($xml->target_type));
607         $positive = notags(unxmlify($xml->positive));
608         $author_signature = notags(unxmlify($xml->author_signature));
609
610         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
611
612         // likes on comments not supported here and likes on photos not supported by Diaspora
613
614         if($target_type !== 'Post')
615                 return;
616
617         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
618         if(! $contact)
619                 return;
620
621         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
622                 logger('diaspora_like: Ignoring this author.');
623                 http_status_exit(202);
624                 // NOTREACHED
625         }
626
627         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
628                 intval($importer['uid']),
629                 dbesc($parent_guid)
630         );
631         if(! count($r)) {
632                 logger('diaspora_like: parent item not found: ' . $guid);
633                 return;
634         }
635
636         $parent_item = $r[0];
637
638         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
639                 intval($importer['uid']),
640                 dbesc($guid)
641         );
642         if(count($r)) {
643                 if($positive === 'true') {
644                         logger('diaspora_like: duplicate like: ' . $guid);
645                         return;
646                 } 
647                 if($positive === 'false') {
648                         q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
649                                 intval($r[0]['id']),
650                                 intval($importer['uid'])
651                         );
652                         // FIXME
653                         //  send notification via proc_run()
654                         return;
655                 }
656         }
657         if($positive === 'false') {
658                 logger('diaspora_like: unlike received with no corresponding like');
659                 return; 
660         }
661
662         $author_signed_data = $guid . ';' . $parent_guid . ';' . $target_type . ';' . $positive . ';' . $diaspora_handle;
663
664         $author_signature = base64_decode($author_signature);
665
666         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
667                 $person = $contact;
668                 $key = $msg['key'];
669         }
670         else {
671                 $person = find_diaspora_person_by_handle($diaspora_handle);     
672                 if(is_array($person) && x($person,'pubkey'))
673                         $key = $person['pubkey'];
674                 else {
675                         logger('diaspora_comment: unable to find author details');
676                         return;
677                 }
678         }
679
680         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha1')) {
681                 logger('diaspora_like: verification failed.');
682 //              return;
683         }
684
685         if($parent_author_signature) {
686                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $target_type . ';' . $positive . ';' . $msg['author'];
687
688                 $parent_author_signature = base64_decode($parent_author_signature);
689
690                 $key = $msg['key'];
691
692                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha1')) {
693                         logger('diaspora_like: owner verification failed.');
694 //                      return;
695                 }
696         }
697
698         // Phew! Everything checks out. Now create an item.
699
700         $uri = $diaspora_handle . ':' . $guid;
701
702         $activity = ACTIVITY_LIKE;
703         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
704         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
705         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
706         $body = $parent_item['body'];
707
708         $obj = <<< EOT
709
710         <object>
711                 <type>$objtype</type>
712                 <local>1</local>
713                 <id>{$parent_item['uri']}</id>
714                 <link>$link</link>
715                 <title></title>
716                 <content>$body</content>
717         </object>
718 EOT;
719         $bodyverb = t('%1$s likes %2$s\'s %3$s');
720
721         $arr = array();
722
723         $arr['uri'] = $uri;
724         $arr['uid'] = $importer['uid'];
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         $datarray['owner-name'] = $contact['name'];
733         $datarray['owner-link'] = $contact['url'];
734         $datarray['owner-avatar'] = $contact['thumb'];
735
736         $datarray['author-name'] = $person['name'];
737         $datarray['author-link'] = $person['url'];
738         $datarray['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         // FIXME send notification
765
766         return;
767 }
768
769 function diaspora_retraction($importer,$xml) {
770
771         $guid = notags(unxmlify($xml->guid));
772         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
773
774         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
775         if(! $contact)
776                 return;
777
778 //      if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
779 //              logger('diaspora_retraction: Ignoring this author.');
780 //              http_status_exit(202);
781 //              // NOTREACHED
782 //      }
783
784
785
786 }
787
788 function diaspora_share($me,$contact) {
789         $a = get_app();
790         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
791         $theiraddr = $contact['addr'];
792
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']),'sha1');
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'],'sha1'));
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 }