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