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