]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
photo fixes
[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
519                 $parent_author_signature = base64_decode($parent_author_signature);
520
521                 $key = $msg['key'];
522
523                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha')) {
524                         logger('diaspora_comment: owner verification failed.');
525                         return;
526                 }
527         }
528
529         // Phew! Everything checks out. Now create an item.
530
531         require_once('library/HTMLPurifier.auto.php');
532         require_once('include/html2bbcode.php');
533
534         $body = $text;
535
536         $maxlen = get_max_import_size();
537         if($maxlen && (strlen($body) > $maxlen))
538                 $body = substr($body,0, $maxlen);
539
540         if((strpos($body,'<') !== false) || (strpos($body,'>') !== false)) {
541
542                 $body = preg_replace('#<object[^>]+>.+?' . 'http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+).+?</object>#s',
543                         '[youtube]$1[/youtube]', $body);
544
545                 $body = preg_replace('#<iframe[^>].+?' . 'http://www.youtube.com/embed/([A-Za-z0-9\-_=]+).+?</iframe>#s',
546                         '[youtube]$1[/youtube]', $body);
547
548                 $body = oembed_html2bbcode($body);
549
550                 $config = HTMLPurifier_Config::createDefault();
551                 $config->set('Cache.DefinitionImpl', null);
552                 $purifier = new HTMLPurifier($config);
553                 $body = $purifier->purify($body);
554
555                 $body = html2bbcode($body);
556         }
557
558         $message_id = $diaspora_handle . ':' . $guid;
559
560         $datarray = array();
561         $datarray['uid'] = $importer['uid'];
562         $datarray['contact-id'] = $contact['id'];
563         $datarray['wall'] = $parent_item['wall'];
564         $datarray['gravity'] = GRAVITY_COMMENT;
565         $datarray['guid'] = $guid;
566         $datarray['uri'] = $message_id;
567         $datarray['parent-uri'] = $parent_item['uri'];
568
569         // No timestamps for comments? OK, we'll the use current time.
570         $datarray['created'] = $datarray['edited'] = datetime_convert();
571         $datarray['private'] = $parent_item['private'];
572
573         $datarray['owner-name'] = $contact['name'];
574         $datarray['owner-link'] = $contact['url'];
575         $datarray['owner-avatar'] = $contact['thumb'];
576
577         $datarray['author-name'] = $person['name'];
578         $datarray['author-link'] = $person['url'];
579         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
580         $datarray['body'] = $body;
581
582         $message_id = item_store($datarray);
583
584         if(! $parent_author_signature) {
585                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
586                         intval($message_id),
587                         dbesc($author_signed_data),
588                         dbesc(base64_encode($author_signature)),
589                         dbesc($diaspora_handle)
590                 );
591         }
592
593         // notify others
594         proc_run('php','include/notifier.php','comment',$message_id);
595
596         return;
597
598 }
599
600 function diaspora_photo($importer,$xml,$msg) {
601
602         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
603
604         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
605
606         $status_message_guid = notags(unxmlify($xml->status_message_guid));
607
608         $guid = notags(unxmlify($xml->guid));
609
610         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
611
612         $public = notags(unxmlify($xml->public));
613
614         $created_at = notags(unxmlify($xml_created_at));
615
616
617         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
618         if(! $contact)
619                 return;
620
621         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
622                 logger('diaspora_photo: Ignoring this author.');
623                 http_status_exit(202);
624                 // NOTREACHED
625         }
626
627         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
628                 intval($importer['uid']),
629                 dbesc($status_message_guid)
630         );
631         if(! count($r)) {
632                 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
633                 return;
634         }
635         $parent_item = $r[0];
636
637         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
638
639         $r = q("update item set `body` = '%s' where `id` = %d and `uid` = %d limit 1",
640                 dbesc($link_text . $parent_item['body']),
641                 intval($parent_item['id']),
642                 intval($parent_item['uid'])
643         );
644
645         return;
646 }
647
648
649
650
651 function diaspora_like($importer,$xml,$msg) {
652
653         $a = get_app();
654         $guid = notags(unxmlify($xml->guid));
655         $parent_guid = notags(unxmlify($xml->parent_guid));
656         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
657         $target_type = notags(unxmlify($xml->target_type));
658         $positive = notags(unxmlify($xml->positive));
659         $author_signature = notags(unxmlify($xml->author_signature));
660
661         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
662
663         // likes on comments not supported here and likes on photos not supported by Diaspora
664
665         if($target_type !== 'Post')
666                 return;
667
668         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
669         if(! $contact)
670                 return;
671
672         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
673                 logger('diaspora_like: Ignoring this author.');
674                 http_status_exit(202);
675                 // NOTREACHED
676         }
677
678         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
679                 intval($importer['uid']),
680                 dbesc($parent_guid)
681         );
682         if(! count($r)) {
683                 logger('diaspora_like: parent item not found: ' . $guid);
684                 return;
685         }
686
687         $parent_item = $r[0];
688
689         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
690                 intval($importer['uid']),
691                 dbesc($guid)
692         );
693         if(count($r)) {
694                 if($positive === 'true') {
695                         logger('diaspora_like: duplicate like: ' . $guid);
696                         return;
697                 } 
698                 if($positive === 'false') {
699                         q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
700                                 intval($r[0]['id']),
701                                 intval($importer['uid'])
702                         );
703                         // FIXME
704                         //  send notification via proc_run()
705                         return;
706                 }
707         }
708         if($positive === 'false') {
709                 logger('diaspora_like: unlike received with no corresponding like');
710                 return; 
711         }
712
713         $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
714
715         $author_signature = base64_decode($author_signature);
716
717         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
718                 $person = $contact;
719                 $key = $msg['key'];
720         }
721         else {
722                 $person = find_diaspora_person_by_handle($diaspora_handle);     
723                 if(is_array($person) && x($person,'pubkey'))
724                         $key = $person['pubkey'];
725                 else {
726                         logger('diaspora_like: unable to find author details');
727                         return;
728                 }
729         }
730
731         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha')) {
732                 logger('diaspora_like: verification failed.');
733                 return;
734         }
735
736         if($parent_author_signature) {
737                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $target_type . ';' . $positive . ';' . $msg['author'];
738
739                 $parent_author_signature = base64_decode($parent_author_signature);
740
741                 $key = $msg['key'];
742
743                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha')) {
744                         logger('diaspora_like: owner verification failed.');
745                         return;
746                 }
747         }
748
749         // Phew! Everything checks out. Now create an item.
750
751         $uri = $diaspora_handle . ':' . $guid;
752
753         $activity = ACTIVITY_LIKE;
754         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
755         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
756         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
757         $body = $parent_item['body'];
758
759         $obj = <<< EOT
760
761         <object>
762                 <type>$objtype</type>
763                 <local>1</local>
764                 <id>{$parent_item['uri']}</id>
765                 <link>$link</link>
766                 <title></title>
767                 <content>$body</content>
768         </object>
769 EOT;
770         $bodyverb = t('%1$s likes %2$s\'s %3$s');
771
772         $arr = array();
773
774         $arr['uri'] = $uri;
775         $arr['uid'] = $importer['uid'];
776         $arr['guid'] = $guid;
777         $arr['contact-id'] = $contact['id'];
778         $arr['type'] = 'activity';
779         $arr['wall'] = $parent_item['wall'];
780         $arr['gravity'] = GRAVITY_LIKE;
781         $arr['parent'] = $parent_item['id'];
782         $arr['parent-uri'] = $parent_item['uri'];
783
784         $arr['owner-name'] = $contact['name'];
785         $arr['owner-link'] = $contact['url'];
786         $arr['owner-avatar'] = $contact['thumb'];
787
788         $arr['author-name'] = $person['name'];
789         $arr['author-link'] = $person['url'];
790         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
791         
792         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
793         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
794         $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
795         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
796
797         $arr['private'] = $parent_item['private'];
798         $arr['verb'] = $activity;
799         $arr['object-type'] = $objtype;
800         $arr['object'] = $obj;
801         $arr['visible'] = 1;
802         $arr['unseen'] = 1;
803         $arr['last-child'] = 0;
804
805         $message_id = item_store($arr);
806
807         if(! $parent_author_signature) {
808                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
809                         intval($message_id),
810                         dbesc($author_signed_data),
811                         dbesc(base64_encode($author_signature)),
812                         dbesc($diaspora_handle)
813                 );
814         }
815
816         // notify others
817         proc_run('php','include/notifier.php','comment',$message_id);
818
819         return;
820 }
821
822 function diaspora_retraction($importer,$xml) {
823
824         $guid = notags(unxmlify($xml->guid));
825         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
826         $type = notags(unxmlify($xml->type));
827
828         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
829         if(! $contact)
830                 return;
831
832         if($type === 'Person') {
833                 contact_remove($contact['id']);
834         }
835         elseif($type === 'Post') {
836                 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
837                         dbesc('guid'),
838                         intval($importer['uid'])
839                 );
840                 if(count($r)) {
841                         if(link_compare($r[0]['author-link'],$contact['url'])) {
842                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
843                                         dbesc(datetime_convert()),                      
844                                         intval($r[0]['id'])
845                                 );
846                         }
847                 }
848         }
849
850         http_exit_status(202);
851         // NOTREACHED
852 }
853
854 function diaspora_share($me,$contact) {
855         $a = get_app();
856         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
857         $theiraddr = $contact['addr'];
858
859         $tpl = get_markup_template('diaspora_share.tpl');
860         $msg = replace_macros($tpl, array(
861                 '$sender' => $myaddr,
862                 '$recipient' => $theiraddr
863         ));
864
865         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
866
867         post_url($contact['notify'] . '/',$slap);
868         $return_code = $a->get_curl_code();
869         logger('diaspora_send_share: returns: ' . $return_code);
870         return $return_code;
871 }
872
873 function diaspora_unshare($me,$contact) {
874
875         $a = get_app();
876         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
877
878         $tpl = get_markup_template('diaspora_retract.tpl');
879         $msg = replace_macros($tpl, array(
880                 '$guid'   => $me['guid'],
881                 '$type'   => 'Person',
882                 '$handle' => $myaddr
883         ));
884
885         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
886
887         post_url($contact['notify'] . '/',$slap);
888         $return_code = $a->get_curl_code();
889         logger('diaspora_send_unshare: returns: ' . $return_code);
890         return $return_code;
891 }
892
893
894
895 function diaspora_send_status($item,$owner,$contact) {
896
897         $a = get_app();
898         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
899         $theiraddr = $contact['addr'];
900
901         $images = array();
902
903         $body = $item['body'];
904
905         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
906         if($cnt) {
907                 foreach($matches as $mtch) {
908                         $detail = array();
909                         $detail['str'] = $mtch[0];
910                         $detail['path'] = dirname($mtch[1]) . '/';
911                         $detail['file'] = basename($mtch[1]);
912                         $detail['guid'] = $item['guid'];
913                         $detail['handle'] = $myaddr;
914                         $images[] = $detail;
915                         $body = str_replace($detail['str'],t('link to photo'),$body);
916                 }
917         }       
918
919         $body = xmlify(bb2diaspora($body));
920         $public = (($item['private']) ? 'false' : 'true');
921
922         require_once('include/datetime.php');
923         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d h:i:s \U\T\C');
924
925         $tpl = get_markup_template('diaspora_post.tpl');
926         $msg = replace_macros($tpl, array(
927                 '$body' => $body,
928                 '$guid' => $item['guid'],
929                 '$handle' => xmlify($myaddr),
930                 '$public' => $public,
931                 '$created' => $created
932         ));
933
934         logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
935
936         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
937
938         post_url($contact['notify'] . '/',$slap);
939         $return_code = $a->get_curl_code();
940         logger('diaspora_send_status: returns: ' . $return_code);
941
942         if(count($images)) {
943                 diaspora_send_images($item,$owner,$contact,$images);
944         }
945
946         return $return_code;
947 }
948
949
950 function diaspora_send_images($item,$owner,$contact,$images) {
951         $a = get_app();
952         if(! count($images))
953                 return;
954         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
955
956         $tpl = get_markup_template('diaspora_photo.tpl');
957         foreach($images as $image) {
958                 if(! stristr($image['path'],$mysite))
959                         continue;
960                 $resource = str_replace('.jpg','',$image['file']);
961                 $resource = substr($resource,0,strpos($resource,'-'));
962
963                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
964                         dbesc($resource),
965                         intval($owner['uid'])
966                 );
967                 if(! count($r))
968                         continue;
969                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
970                 $msg = replace_macros($tpl,array(               
971                         '$path' => xmlify($image['path']),
972                         '$filename' => xmlify($image['file']),
973                         '$msg_guid' => xmlify($image['guid']),
974                         '$guid' => xmlify($r[0]['guid']),
975                         '$handle' => xmlify($image['handle']),
976                         '$public' => xmlify($public),
977                         '$created_at' => xmlify('UTC','UTC',$r[0]['created'],'Y-m-d h:i:s \U\T\C')
978                 ));
979
980                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
981                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
982
983                 post_url($contact['notify'] . '/',$slap);
984                 $return_code = $a->get_curl_code();
985                 logger('diaspora_send_photo: returns: ' . $return_code);
986         }
987
988 }
989
990 function diaspora_send_followup($item,$owner,$contact) {
991
992         $a = get_app();
993         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
994         $theiraddr = $contact['addr'];
995
996         $p = q("select guid from item where parent = %d limit 1",
997                 $item['parent']
998         );
999         if(count($p))
1000                 $parent_guid = $p[0]['guid'];
1001         else
1002                 return;
1003
1004         if($item['verb'] === ACTIVITY_LIKE) {
1005                 $tpl = get_markup_template('diaspora_like.tpl');
1006                 $like = true;
1007                 $target_type = 'Post';
1008                 $positive = (($item['deleted']) ? 'false' : 'true');
1009         }
1010         else {
1011                 $tpl = get_markup_template('diaspora_comment.tpl');
1012                 $like = false;
1013         }
1014
1015         $text = bb2diaspora($item['body']);
1016
1017         // sign it
1018
1019         if($like)
1020                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1021         else
1022                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1023
1024         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha'));
1025
1026         $msg = replace_macros($tpl,array(
1027                 '$guid' => xmlify($item['guid']),
1028                 '$parent_guid' => xmlify($parent_guid),
1029                 '$target_type' =>xmlify($target_type),
1030                 '$authorsig' => xmlify($authorsig),
1031                 '$body' => xmlify($text),
1032                 '$positive' => xmlify($positive),
1033                 '$handle' => xmlify($myaddr)
1034         ));
1035
1036         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1037
1038         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1039
1040         post_url($contact['notify'] . '/',$slap);
1041         $return_code = $a->get_curl_code();
1042         logger('diaspora_send_followup: returns: ' . $return_code);
1043         return $return_code;
1044
1045 }
1046
1047
1048 function diaspora_send_relay($item,$owner,$contact) {
1049
1050
1051         $a = get_app();
1052         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1053         $theiraddr = $contact['addr'];
1054
1055
1056         $p = q("select guid from item where parent = %d limit 1",
1057                 $item['parent']
1058         );
1059         if(count($p))
1060                 $parent_guid = $p[0]['guid'];
1061         else
1062                 return;
1063
1064         // fetch the original signature 
1065         $r = q("select * from sign where iid = %d limit 1",
1066                 intval($item['id'])
1067         );
1068         if(! count($r)) 
1069                 return;
1070         $orig_sign = $r[0];
1071
1072         if($item['verb'] === ACTIVITY_LIKE) {
1073                 $tpl = get_markup_template('diaspora_like_relay.tpl');
1074                 $like = true;
1075                 $target_type = 'Post';
1076                 $positive = (($item['deleted']) ? 'false' : 'true');
1077         }
1078         else {
1079                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1080                 $like = false;
1081         }
1082
1083         $text = bb2diaspora($item['body']);
1084
1085         // sign it
1086
1087         if($like)
1088                 $parent_signed_text = $orig_sign['signed_text'];
1089         else
1090                 $parent_signed_text = $orig_sign['signed_text'];
1091
1092         $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha'));
1093
1094         $msg = replace_macros($tpl,array(
1095                 '$guid' => xmlify($item['guid']),
1096                 '$parent_guid' => xmlify($parent_guid),
1097                 '$target_type' =>xmlify($target_type),
1098                 '$authorsig' => xmlify($orig_sign['signature']),
1099                 '$parentsig' => xmlify($parentauthorsig),
1100                 '$text' => xmlify($text),
1101                 '$positive' => xmlify($positive),
1102                 '$diaspora_handle' => xmlify($myaddr)
1103         ));
1104
1105         // fetch the original signature 
1106         $r = q("select * from sign where iid = %d limit 1",
1107                 intval($item['id'])
1108         );
1109         if(! count($r)) 
1110                 return;
1111
1112         logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1113
1114         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1115
1116         post_url($contact['notify'] . '/',$slap);
1117         $return_code = $a->get_curl_code();
1118         logger('diaspora_send_relay: returns: ' . $return_code);
1119         return $return_code;
1120
1121 }
1122
1123
1124
1125 function diaspora_send_retraction($item,$owner,$contact) {
1126
1127         $a = get_app();
1128         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1129
1130         $tpl = get_markup_template('diaspora_retract.tpl');
1131         $msg = replace_macros($tpl, array(
1132                 '$guid'   => $item['guid'],
1133                 '$type'   => 'Post',
1134                 '$handle' => $myaddr
1135         ));
1136
1137         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1138
1139         post_url($contact['notify'] . '/',$slap);
1140         $return_code = $a->get_curl_code();
1141         logger('diaspora_send_retraction: returns: ' . $return_code);
1142         return $return_code;
1143
1144 }