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