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