]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
better reporting when d* parent not found
[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
329         $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
330                 VALUES ( %d, '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
331                 intval($importer['uid']),
332                 dbesc($ret['network']),
333                 dbesc($ret['addr']),
334                 datetime_convert(),
335                 dbesc($ret['url']),
336                 dbesc($ret['name']),
337                 dbesc($ret['nick']),
338                 dbesc($ret['photo']),
339                 dbesc($ret['pubkey']),
340                 dbesc($ret['notify']),
341                 dbesc($ret['poll']),
342                 1,
343                 2
344         );
345                  
346         // find the contact record we just created
347
348         $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
349
350         $hash = random_string() . (string) time();   // Generate a confirm_key
351         
352         if($contact_record) {
353                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
354                         VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
355                         intval($importer['uid']),
356                         intval($contact_record['id']),
357                         0,
358                         0,
359                         dbesc( t('Sharing notification from Diaspora network')),
360                         dbesc($hash),
361                         dbesc(datetime_convert())
362                 );
363         }
364
365         return;
366 }
367
368 function diaspora_post($importer,$xml) {
369
370         $guid = notags(unxmlify($xml->guid));
371         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
372
373         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
374         if(! $contact)
375                 return;
376
377         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
378                 logger('diaspora_post: Ignoring this author.');
379                 http_status_exit(202);
380                 // NOTREACHED
381         }
382
383         $message_id = $diaspora_handle . ':' . $guid;
384         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
385                 intval($importer['uid']),
386                 dbesc($message_id),
387                 dbesc($guid)
388         );
389         if(count($r))
390                 return;
391
392     // allocate a guid on our system - we aren't fixing any collisions.
393         // we're ignoring them
394
395         $g = q("select * from guid where guid = '%s' limit 1",
396                 dbesc($guid)
397         );
398         if(! count($g)) {
399                 q("insert into guid ( guid ) values ( '%s' )",
400                         dbesc($guid)
401                 );
402         }
403
404         $created = unxmlify($xml->created_at);
405         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
406
407         $body = unxmlify($xml->raw_message);
408
409         require_once('library/HTMLPurifier.auto.php');
410         require_once('include/html2bbcode.php');
411
412         $maxlen = get_max_import_size();
413         if($maxlen && (strlen($body) > $maxlen))
414                 $body = substr($body,0, $maxlen);
415
416         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
417
418                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
419                         '[youtube]$1[/youtube]', $body);
420
421                 $body = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
422                         '[youtube]$1[/youtube]', $body);
423
424                 $body = oembed_html2bbcode($body);
425
426                 $config = HTMLPurifier_Config::createDefault();
427                 $config->set('Cache.DefinitionImpl', null);
428                 $purifier = new HTMLPurifier($config);
429                 $body = $purifier->purify($body);
430
431                 $body = html2bbcode($body);
432         }
433
434         $datarray = array();
435         $datarray['uid'] = $importer['uid'];
436         $datarray['contact-id'] = $contact['id'];
437         $datarray['wall'] = 0;
438         $datarray['guid'] = $guid;
439         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
440         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
441         $datarray['private'] = $private;
442         $datarray['parent'] = 0;
443         $datarray['owner-name'] = $contact['name'];
444         $datarray['owner-link'] = $contact['url'];
445         $datarray['owner-avatar'] = $contact['thumb'];
446         $datarray['author-name'] = $contact['name'];
447         $datarray['author-link'] = $contact['url'];
448         $datarray['author-avatar'] = $contact['thumb'];
449         $datarray['body'] = $body;
450
451         item_store($datarray);
452
453         return;
454
455 }
456
457 function diaspora_comment($importer,$xml,$msg) {
458
459         $guid = notags(unxmlify($xml->guid));
460         $parent_guid = notags(unxmlify($xml->parent_guid));
461         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
462         $target_type = notags(unxmlify($xml->target_type));
463         $text = unxmlify($xml->text);
464         $author_signature = notags(unxmlify($xml->author_signature));
465
466         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
467
468         $text = $xml->text;
469
470         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
471         if(! $contact)
472                 return;
473
474         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
475                 logger('diaspora_comment: Ignoring this author.');
476                 http_status_exit(202);
477                 // NOTREACHED
478         }
479
480         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
481                 intval($importer['uid']),
482                 dbesc($parent_guid)
483         );
484         if(! count($r)) {
485                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
486                 return;
487         }
488         $parent_item = $r[0];
489
490         $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
491
492         $author_signature = base64_decode($author_signature);
493
494         if(stricmp($diaspora_handle,$msg['author']) == 0) {
495                 $person = $contact;
496                 $key = $msg['key'];
497         }
498         else {
499                 $person = find_diaspora_person_by_handle($diaspora_handle);     
500
501                 if(is_array($person) && x($person,'pubkey'))
502                         $key = $person['pubkey'];
503                 else {
504                         logger('diaspora_comment: unable to find author details');
505                         return;
506                 }
507         }
508
509         if(! rsa_verify($author_signed_data,$author_signature,$key)) {
510                 logger('diaspora_comment: verification failed.');
511                 return;
512         }
513
514
515         if($parent_author_signature) {
516                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $msg['author'];
517
518                 $parent_author_signature = base64_decode($parent_author_signature);
519
520                 $key = $msg['key'];
521
522                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key)) {
523                         logger('diaspora_comment: owner verification failed.');
524                         return;
525                 }
526         }
527
528         // Phew! Everything checks out. Now create an item.
529
530         require_once('library/HTMLPurifier.auto.php');
531         require_once('include/html2bbcode.php');
532
533         $body = $text;
534
535         $maxlen = get_max_import_size();
536         if($maxlen && (strlen($body) > $maxlen))
537                 $body = substr($body,0, $maxlen);
538
539         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
540
541                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
542                         '[youtube]$1[/youtube]', $body);
543
544                 $body = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
545                         '[youtube]$1[/youtube]', $body);
546
547                 $body = oembed_html2bbcode($body);
548
549                 $config = HTMLPurifier_Config::createDefault();
550                 $config->set('Cache.DefinitionImpl', null);
551                 $purifier = new HTMLPurifier($config);
552                 $body = $purifier->purify($body);
553
554                 $body = html2bbcode($body);
555         }
556
557         $message_id = $diaspora_handle . ':' . $guid;
558
559         $datarray = array();
560         $datarray['uid'] = $importer['uid'];
561         $datarray['contact-id'] = $contact['id'];
562         $datarray['wall'] = $parent_item['wall'];
563         $datarray['gravity'] = GRAVITY_COMMENT;
564         $datarray['guid'] = $guid;
565         $datarray['uri'] = $message_id;
566         $datarray['parent-uri'] = $parent_item['uri'];
567
568         // No timestamps for comments? OK, we'll the use current time.
569         $datarray['created'] = $datarray['edited'] = datetime_convert();
570         $datarray['private'] = $parent_item['private'];
571
572         $datarray['owner-name'] = $contact['name'];
573         $datarray['owner-link'] = $contact['url'];
574         $datarray['owner-avatar'] = $contact['thumb'];
575
576         $datarray['author-name'] = $person['name'];
577         $datarray['author-link'] = $person['url'];
578         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
579         $datarray['body'] = $body;
580
581         $message_id = item_store($datarray);
582
583         if(! $parent_author_signature) {
584                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
585                         intval($message_id),
586                         dbesc($author_signed_data),
587                         dbesc(base64_encode($author_signature)),
588                         dbesc($diaspora_handle)
589                 );
590         }
591
592         // notify others
593         return;
594
595 }
596
597 function diaspora_like($importer,$xml,$msg) {
598
599         $guid = notags(unxmlify($xml->guid));
600         $parent_guid = notags(unxmlify($xml->parent_guid));
601         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
602         $target_type = notags(unxmlify($xml->target_type));
603         $positive = notags(unxmlify($xml->positive));
604         $author_signature = notags(unxmlify($xml->author_signature));
605
606         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
607
608         // likes on comments not supported here and likes on photos not supported by Diaspora
609
610         if($target_type !== 'Post')
611                 return;
612
613         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
614         if(! $contact)
615                 return;
616
617         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
618                 logger('diaspora_like: Ignoring this author.');
619                 http_status_exit(202);
620                 // NOTREACHED
621         }
622
623         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
624                 intval($importer['uid']),
625                 dbesc($parent_guid)
626         );
627         if(! count($r)) {
628                 logger('diaspora_like: parent item not found: ' . $guid);
629                 return;
630         }
631
632         $parent_item = $r[0];
633
634         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '$s' LIMIT 1",
635                 intval($importer['uid']),
636                 dbesc($guid)
637         );
638         if(count($r)) {
639                 if($positive === 'true') {
640                         logger('diaspora_like: duplicate like: ' . $guid);
641                         return;
642                 } 
643                 if($positive === 'false') {
644                         q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
645                                 intval($r[0]['id']),
646                                 intval($importer['uid'])
647                         );
648                         // FIXME
649                         //  send notification via proc_run()
650                         return;
651                 }
652         }
653         if($positive === 'false') {
654                 logger('diaspora_like: unlike received with no corresponding like');
655                 return; 
656         }
657
658         $author_signed_data = $guid . ';' . $parent_guid . ';' . $target_type . ';' . $positive . ';' . $diaspora_handle;
659
660         $author_signature = base64_decode($author_signature);
661
662         if(stricmp($diaspora_handle,$msg['author']) == 0) {
663                 $person = $contact;
664                 $key = $msg['key'];
665         }
666         else {
667                 $person = find_diaspora_person_by_handle($diaspora_handle);     
668                 if(is_array($person) && x($person,'pubkey'))
669                         $key = $person['pubkey'];
670                 else {
671                         logger('diaspora_comment: unable to find author details');
672                         return;
673                 }
674         }
675
676         if(! rsa_verify($author_signed_data,$author_signature,$key)) {
677                 logger('diaspora_like: verification failed.');
678                 return;
679         }
680
681         if($parent_author_signature) {
682                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $target_type . ';' . $positive . ';' . $msg['author'];
683
684                 $parent_author_signature = base64_decode($parent_author_signature);
685
686                 $key = $msg['key'];
687
688                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key)) {
689                         logger('diaspora_like: owner verification failed.');
690                         return;
691                 }
692         }
693
694         // Phew! Everything checks out. Now create an item.
695
696         $uri = $diaspora_handle . ':' . $guid;
697
698         $activity = ACTIVITY_LIKE;
699         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
700         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
701         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
702         $body = $parent_item['body'];
703
704         $obj = <<< EOT
705
706         <object>
707                 <type>$objtype</type>
708                 <local>1</local>
709                 <id>{$parent_item['uri']}</id>
710                 <link>$link</link>
711                 <title></title>
712                 <content>$body</content>
713         </object>
714 EOT;
715         $bodyverb = t('%1$s likes %2$s\'s %3$s');
716
717         $arr = array();
718
719         $arr['uri'] = $uri;
720         $arr['uid'] = $importer['uid'];
721         $arr['contact-id'] = $contact['id'];
722         $arr['type'] = 'activity';
723         $arr['wall'] = $parent_item['wall'];
724         $arr['gravity'] = GRAVITY_LIKE;
725         $arr['parent'] = $parent_item['id'];
726         $arr['parent-uri'] = $parent_item['uri'];
727
728         $datarray['owner-name'] = $contact['name'];
729         $datarray['owner-link'] = $contact['url'];
730         $datarray['owner-avatar'] = $contact['thumb'];
731
732         $datarray['author-name'] = $person['name'];
733         $datarray['author-link'] = $person['url'];
734         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
735         
736         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
737         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
738         $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
739         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
740
741         $arr['private'] = $parent_item['private'];
742         $arr['verb'] = $activity;
743         $arr['object-type'] = $objtype;
744         $arr['object'] = $obj;
745         $arr['visible'] = 1;
746         $arr['unseen'] = 1;
747         $arr['last-child'] = 0;
748
749         $message_id = item_store($arr);
750
751         if(! $parent_author_signature) {
752                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
753                         intval($message_id),
754                         dbesc($author_signed_data),
755                         dbesc(base64_encode($author_signature)),
756                         dbesc($diaspora_handle)
757                 );
758         }
759
760         // FIXME send notification
761
762         return;
763 }
764
765 function diaspora_retraction($importer,$xml) {
766
767         $guid = notags(unxmlify($xml->guid));
768         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
769
770         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
771         if(! $contact)
772                 return;
773
774 //      if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
775 //              logger('diaspora_retraction: Ignoring this author.');
776 //              http_status_exit(202);
777 //              // NOTREACHED
778 //      }
779
780
781
782 }
783
784 function diaspora_share($me,$contact) {
785         $a = get_app();
786         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
787         $theiraddr = $contact['addr'];
788
789         $tpl = get_markup_template('diaspora_share.tpl');
790         $msg = replace_macros($tpl, array(
791                 '$sender' => myaddr,
792                 '$recipient' => $theiraddr
793         ));
794
795         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
796
797         post_url($contact['notify'],$slap);
798         $return_code = $a->get_curl_code();
799         return $return_code;
800 }
801
802 function diaspora_send_status($item,$owner,$contact) {
803
804         $a = get_app();
805         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
806         $theiraddr = $contact['addr'];
807         require_once('include/bbcode.php');
808
809         $body = xmlify(bbcode($item['body']));
810         $public = (($item['private']) ? 'false' : 'true');
811
812         require_once('include/datetime.php');
813         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d h:i:s \U\T\C');
814
815         $tpl = get_markup_template('diaspora_post.tpl');
816         $msg = replace_macros($tpl, array(
817                 '$body' => $body,
818                 '$guid' => $item['guid'],
819                 '$handle' => xmlify($myaddr),
820                 '$public' => $public,
821                 '$created' => $created
822         ));
823
824         logger('diaspora_send_status: base message: ' . $msg, LOGGER_DATA);
825
826         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
827
828         post_url($contact['notify'],$slap);
829         $return_code = $a->get_curl_code();
830         logger('diaspora_send_status: returns: ' . $return_code);
831         return $return_code;
832 }
833
834
835 function diaspora_send_followup($item,$owner,$contact) {
836
837         $a = get_app();
838         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
839         $theiraddr = $contact['addr'];
840
841         $p = q("select guid from item where parent = %d limit 1",
842                 $item['parent']
843         );
844         if(count($p))
845                 $parent_guid = $p[0]['guid'];
846         else
847                 return;
848
849         if($item['verb'] === ACTIVITY_LIKE) {
850                 $tpl = get_markup_template('diaspora_like.tpl');
851                 $like = true;
852                 $target_type = 'Post';
853                 $positive = (($item['deleted']) ? 'false' : 'true');
854         }
855         else {
856                 $tpl = get_markup_template('diaspora_comment.tpl');
857                 $like = false;
858         }
859
860         $text = bbcode($item['body']);
861
862         // sign it
863
864         if($like)
865                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $positive . ';' . $myaddr;
866         else
867                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
868
869         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey']));
870
871         $msg = replace_macros($tpl,array(
872                 '$guid' => xmlify($item['guid']),
873                 '$parent_guid' => xmlify($parent_guid),
874                 '$target_type' =>xmlify($target_type),
875                 '$authorsig' => xmlify($authorsig),
876                 '$body' => xmlify($text),
877                 '$positive' => xmlify($positive),
878                 '$handle' => xmlify($myaddr)
879         ));
880
881         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
882
883         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
884
885         post_url($contact['notify'],$slap);
886         $return_code = $a->get_curl_code();
887         logger('diaspora_send_status: returns: ' . $return_code);
888         return $return_code;
889
890 }
891
892
893 function diaspora_send_relay($item,$owner,$contact) {
894
895
896         $a = get_app();
897         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
898         $theiraddr = $contact['addr'];
899
900
901         $p = q("select guid from item where parent = %d limit 1",
902                 $item['parent']
903         );
904         if(count($p))
905                 $parent_guid = $p[0]['guid'];
906         else
907                 return;
908
909         // fetch the original signature 
910         $r = q("select * from sign where iid = %d limit 1",
911                 intval($item['id'])
912         );
913         if(! count($r)) 
914                 return;
915         $orig_sign = $r[0];
916
917         if($item['verb'] === ACTIVITY_LIKE) {
918                 $tpl = get_markup_template('diaspora_like_relay.tpl');
919                 $like = true;
920                 $target_type = 'Post';
921                 $positive = (($item['deleted']) ? 'false' : 'true');
922         }
923         else {
924                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
925                 $like = false;
926         }
927
928         $text = bbcode($item['body']);
929
930         // sign it
931
932         if($like)
933                 $parent_signed_text = $orig_sign['signed_text'];
934         else
935                 $parent_signed_text = $orig_sign['signed_text'];
936
937         $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey']));
938
939         $msg = replace_macros($tpl,array(
940                 '$guid' => xmlify($item['guid']),
941                 '$parent_guid' => xmlify($parent_guid),
942                 '$target_type' =>xmlify($target_type),
943                 '$authorsig' => xmlify($orig_sign['signature']),
944                 '$parentsig' => xmlify($parentauthorsig),
945                 '$text' => xmlify($text),
946                 '$positive' => xmlify($positive),
947                 '$diaspora_handle' => xmlify($myaddr)
948         ));
949
950         // fetch the original signature 
951         $r = q("select * from sign where iid = %d limit 1",
952                 intval($item['id'])
953         );
954         if(! count($r)) 
955                 return;
956
957         logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
958
959         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
960
961         post_url($contact['notify'],$slap);
962         $return_code = $a->get_curl_code();
963         logger('diaspora_send_status: returns: ' . $return_code);
964         return $return_code;
965
966 }
967
968
969
970 function diaspora_send_retraction($item,$owner,$contact) {
971
972
973
974
975
976 }