]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
check for existing diaspora comment before accepting, add 'Diaspora' app to item...
[friendica.git] / include / diaspora.php
1 <?php
2
3 require_once('include/crypto.php');
4 require_once('include/items.php');
5 require_once('include/bb2diaspora.php');
6
7 function diaspora_dispatch($importer,$msg) {
8
9         $parsed_xml = parse_xml_string($msg['message'],false);
10
11         $xmlbase = $parsed_xml->post;
12
13         if($xmlbase->request) {
14                 diaspora_request($importer,$xmlbase->request);
15         }
16         elseif($xmlbase->status_message) {
17                 diaspora_post($importer,$xmlbase->status_message);
18         }
19         elseif($xmlbase->comment) {
20                 diaspora_comment($importer,$xmlbase->comment,$msg);
21         }
22         elseif($xmlbase->like) {
23                 diaspora_like($importer,$xmlbase->like,$msg);
24         }
25         elseif($xmlbase->retraction) {
26                 diaspora_retraction($importer,$xmlbase->retraction,$msg);
27         }
28         elseif($xmlbase->photo) {
29                 diaspora_photo($importer,$xmlbase->photo,$msg);
30         }
31         else {
32                 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
33         }
34         return;
35 }
36
37 function diaspora_get_contact_by_handle($uid,$handle) {
38         $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
39                 dbesc(NETWORK_DIASPORA),
40                 intval($uid),
41                 dbesc($handle)
42         );
43         if($r && count($r))
44                 return $r[0];
45         return false;
46 }
47
48 function find_diaspora_person_by_handle($handle) {
49         $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
50                 dbesc(NETWORK_DIASPORA),
51                 dbesc($handle)
52         );
53         if(count($r)) {
54                 // update record occasionally so it doesn't get stale
55                 $d = strtotime($r[0]['updated'] . ' +00:00');
56                 if($d < strtotime('now - 14 days')) {
57                         q("delete from fcontact where id = %d limit 1",
58                                 intval($r[0]['id'])
59                         );
60                 }
61                 else
62                         return $r[0];
63         }
64         require_once('include/Scrape.php');
65         $r = probe_url($handle, PROBE_DIASPORA);
66         if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
67                 add_fcontact($r);
68                 return ($r);
69         }
70         return false;
71 }
72
73
74 function get_diaspora_key($uri) {
75         logger('Fetching diaspora key for: ' . $uri);
76
77         $r = find_diaspora_person_by_handle($uri);
78         if($r)
79                 return $r['pubkey'];
80         return '';
81 }
82
83
84 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey) {
85         $a = get_app();
86
87         logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
88
89         $inner_aes_key = random_string(32);
90         $b_inner_aes_key = base64_encode($inner_aes_key);
91         $inner_iv = random_string(16);
92         $b_inner_iv = base64_encode($inner_iv);
93
94         $outer_aes_key = random_string(32);
95         $b_outer_aes_key = base64_encode($outer_aes_key);
96         $outer_iv = random_string(16);
97         $b_outer_iv = base64_encode($outer_iv);
98         
99         $handle = 'acct:' . $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
100
101         $padded_data = pkcs5_pad($msg,16);
102         $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
103
104         $b64_data = base64_encode($inner_encrypted);
105
106
107         $b64url_data = base64url_encode($b64_data);
108         $b64url_stripped = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
109     $lines = str_split($b64url_stripped,60);
110     $data = implode("\n",$lines);
111         $data = $data . (($data[-1] != "\n") ? "\n" : '') ;
112         $type = 'application/atom+xml';
113         $encoding = 'base64url';
114         $alg = 'RSA-SHA256';
115
116         $signable_data = $data  . '.' . base64url_encode($type) . "\n" . '.' 
117                 . base64url_encode($encoding) . "\n" . '.' . base64url_encode($alg) . "\n";
118
119         $signature = rsa_sign($signable_data,$prvkey);
120         $sig = base64url_encode($signature);
121
122 $decrypted_header = <<< EOT
123 <decrypted_header>
124   <iv>$b_inner_iv</iv>
125   <aes_key>$b_inner_aes_key</aes_key>
126   <author>
127     <name>{$user['username']}</name>
128     <uri>$handle</uri>
129   </author>
130 </decrypted_header>
131 EOT;
132
133         $decrypted_header = pkcs5_pad($decrypted_header,16);
134
135         $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
136
137         $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
138
139         $encrypted_outer_key_bundle = '';
140         openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
141
142         logger('outer_bundle_encrypt: ' . openssl_error_string());
143         $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
144
145         logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey);
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);
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                 return;
422
423     // allocate a guid on our system - we aren't fixing any collisions.
424         // we're ignoring them
425
426         $g = q("select * from guid where guid = '%s' limit 1",
427                 dbesc($guid)
428         );
429         if(! count($g)) {
430                 q("insert into guid ( guid ) values ( '%s' )",
431                         dbesc($guid)
432                 );
433         }
434
435         $created = unxmlify($xml->created_at);
436         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
437
438         $body = diaspora2bb($xml->raw_message);
439
440         $datarray = array();
441         $datarray['uid'] = $importer['uid'];
442         $datarray['contact-id'] = $contact['id'];
443         $datarray['wall'] = 0;
444         $datarray['guid'] = $guid;
445         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
446         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
447         $datarray['private'] = $private;
448         $datarray['parent'] = 0;
449         $datarray['owner-name'] = $contact['name'];
450         $datarray['owner-link'] = $contact['url'];
451         $datarray['owner-avatar'] = $contact['thumb'];
452         $datarray['author-name'] = $contact['name'];
453         $datarray['author-link'] = $contact['url'];
454         $datarray['author-avatar'] = $contact['thumb'];
455         $datarray['body'] = $body;
456         $datarray['app']  = 'Diaspora';
457
458         item_store($datarray);
459
460         return;
461
462 }
463
464 function diaspora_comment($importer,$xml,$msg) {
465
466         $guid = notags(unxmlify($xml->guid));
467         $parent_guid = notags(unxmlify($xml->parent_guid));
468         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
469         $target_type = notags(unxmlify($xml->target_type));
470         $text = unxmlify($xml->text);
471         $author_signature = notags(unxmlify($xml->author_signature));
472
473         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
474
475         $text = $xml->text;
476
477         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
478         if(! $contact)
479                 return;
480
481         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
482                 logger('diaspora_comment: Ignoring this author.');
483                 http_status_exit(202);
484                 // NOTREACHED
485         }
486
487         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
488                 intval($importer['uid']),
489                 dbesc($guid)
490         );
491         if(count($r)) {
492                 logger('daspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
493                 return;
494         }
495
496         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
497                 intval($importer['uid']),
498                 dbesc($parent_guid)
499         );
500         if(! count($r)) {
501                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
502                 return;
503         }
504         $parent_item = $r[0];
505
506         $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
507
508         $author_signature = base64_decode($author_signature);
509
510         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
511                 $person = $contact;
512                 $key = $msg['key'];
513         }
514         else {
515                 $person = find_diaspora_person_by_handle($diaspora_handle);     
516
517                 if(is_array($person) && x($person,'pubkey'))
518                         $key = $person['pubkey'];
519                 else {
520                         logger('diaspora_comment: unable to find author details');
521                         return;
522                 }
523         }
524
525         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha')) {
526                 logger('diaspora_comment: verification failed.');
527                 return;
528         }
529
530
531         if($parent_author_signature) {
532                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
533
534                 $parent_author_signature = base64_decode($parent_author_signature);
535
536                 $key = $msg['key'];
537
538                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha')) {
539                         logger('diaspora_comment: owner verification failed.');
540                         return;
541                 }
542         }
543
544         // Phew! Everything checks out. Now create an item.
545
546         $body = diaspora2bb($text);
547
548         $message_id = $diaspora_handle . ':' . $guid;
549
550         $datarray = array();
551         $datarray['uid'] = $importer['uid'];
552         $datarray['contact-id'] = $contact['id'];
553         $datarray['wall'] = $parent_item['wall'];
554         $datarray['gravity'] = GRAVITY_COMMENT;
555         $datarray['guid'] = $guid;
556         $datarray['uri'] = $message_id;
557         $datarray['parent-uri'] = $parent_item['uri'];
558
559         // No timestamps for comments? OK, we'll the use current time.
560         $datarray['created'] = $datarray['edited'] = datetime_convert();
561         $datarray['private'] = $parent_item['private'];
562
563         $datarray['owner-name'] = $contact['name'];
564         $datarray['owner-link'] = $contact['url'];
565         $datarray['owner-avatar'] = $contact['thumb'];
566
567         $datarray['author-name'] = $person['name'];
568         $datarray['author-link'] = $person['url'];
569         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
570         $datarray['body'] = $body;
571         $datarray['app']  = 'Diaspora';
572
573         $message_id = item_store($datarray);
574
575         if(! $parent_author_signature) {
576                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
577                         intval($message_id),
578                         dbesc($author_signed_data),
579                         dbesc(base64_encode($author_signature)),
580                         dbesc($diaspora_handle)
581                 );
582
583                 // if the message isn't already being relayed, notify others
584                 // the existence of parent_author_signature means the parent_author or owner
585                 // is already relaying.
586
587                 proc_run('php','include/notifier.php','comment',$message_id);
588         }
589         return;
590 }
591
592 function diaspora_photo($importer,$xml,$msg) {
593
594         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
595
596         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
597
598         $status_message_guid = notags(unxmlify($xml->status_message_guid));
599
600         $guid = notags(unxmlify($xml->guid));
601
602         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
603
604         $public = notags(unxmlify($xml->public));
605
606         $created_at = notags(unxmlify($xml_created_at));
607
608
609         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
610         if(! $contact)
611                 return;
612
613         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
614                 logger('diaspora_photo: Ignoring this author.');
615                 http_status_exit(202);
616                 // NOTREACHED
617         }
618
619         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
620                 intval($importer['uid']),
621                 dbesc($status_message_guid)
622         );
623         if(! count($r)) {
624                 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
625                 return;
626         }
627         $parent_item = $r[0];
628
629         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
630
631         $r = q("update item set `body` = '%s' where `id` = %d and `uid` = %d limit 1",
632                 dbesc($link_text . $parent_item['body']),
633                 intval($parent_item['id']),
634                 intval($parent_item['uid'])
635         );
636
637         return;
638 }
639
640
641
642
643 function diaspora_like($importer,$xml,$msg) {
644
645         $a = get_app();
646         $guid = notags(unxmlify($xml->guid));
647         $parent_guid = notags(unxmlify($xml->parent_guid));
648         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
649         $target_type = notags(unxmlify($xml->target_type));
650         $positive = notags(unxmlify($xml->positive));
651         $author_signature = notags(unxmlify($xml->author_signature));
652
653         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
654
655         // likes on comments not supported here and likes on photos not supported by Diaspora
656
657         if($target_type !== 'Post')
658                 return;
659
660         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
661         if(! $contact)
662                 return;
663
664         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
665                 logger('diaspora_like: Ignoring this author.');
666                 http_status_exit(202);
667                 // NOTREACHED
668         }
669
670         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
671                 intval($importer['uid']),
672                 dbesc($parent_guid)
673         );
674         if(! count($r)) {
675                 logger('diaspora_like: parent item not found: ' . $guid);
676                 return;
677         }
678
679         $parent_item = $r[0];
680
681         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
682                 intval($importer['uid']),
683                 dbesc($guid)
684         );
685         if(count($r)) {
686                 if($positive === 'true') {
687                         logger('diaspora_like: duplicate like: ' . $guid);
688                         return;
689                 } 
690                 if($positive === 'false') {
691                         q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
692                                 intval($r[0]['id']),
693                                 intval($importer['uid'])
694                         );
695                         // FIXME
696                         //  send notification via proc_run()
697                         return;
698                 }
699         }
700         if($positive === 'false') {
701                 logger('diaspora_like: unlike received with no corresponding like');
702                 return; 
703         }
704
705         $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
706
707         $author_signature = base64_decode($author_signature);
708
709         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
710                 $person = $contact;
711                 $key = $msg['key'];
712         }
713         else {
714                 $person = find_diaspora_person_by_handle($diaspora_handle);     
715                 if(is_array($person) && x($person,'pubkey'))
716                         $key = $person['pubkey'];
717                 else {
718                         logger('diaspora_like: unable to find author details');
719                         return;
720                 }
721         }
722
723         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha')) {
724                 logger('diaspora_like: verification failed.');
725                 return;
726         }
727
728         if($parent_author_signature) {
729 //              $owner_signed_data = $guid . ';' . $parent_guid . ';' . $target_type . ';' . $positive . ';' . $msg['author'];
730                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $target_type . ';' . $positive . ';' . $diaspora_handle;
731
732                 $parent_author_signature = base64_decode($parent_author_signature);
733
734                 $key = $msg['key'];
735
736                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha')) {
737                         logger('diaspora_like: owner verification failed.');
738                         return;
739                 }
740         }
741
742         // Phew! Everything checks out. Now create an item.
743
744         $uri = $diaspora_handle . ':' . $guid;
745
746         $activity = ACTIVITY_LIKE;
747         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
748         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
749         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
750         $body = $parent_item['body'];
751
752         $obj = <<< EOT
753
754         <object>
755                 <type>$objtype</type>
756                 <local>1</local>
757                 <id>{$parent_item['uri']}</id>
758                 <link>$link</link>
759                 <title></title>
760                 <content>$body</content>
761         </object>
762 EOT;
763         $bodyverb = t('%1$s likes %2$s\'s %3$s');
764
765         $arr = array();
766
767         $arr['uri'] = $uri;
768         $arr['uid'] = $importer['uid'];
769         $arr['guid'] = $guid;
770         $arr['contact-id'] = $contact['id'];
771         $arr['type'] = 'activity';
772         $arr['wall'] = $parent_item['wall'];
773         $arr['gravity'] = GRAVITY_LIKE;
774         $arr['parent'] = $parent_item['id'];
775         $arr['parent-uri'] = $parent_item['uri'];
776
777         $arr['owner-name'] = $contact['name'];
778         $arr['owner-link'] = $contact['url'];
779         $arr['owner-avatar'] = $contact['thumb'];
780
781         $arr['author-name'] = $person['name'];
782         $arr['author-link'] = $person['url'];
783         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
784         
785         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
786         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
787         $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
788         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
789
790         $arr['app']  = 'Diaspora';
791
792         $arr['private'] = $parent_item['private'];
793         $arr['verb'] = $activity;
794         $arr['object-type'] = $objtype;
795         $arr['object'] = $obj;
796         $arr['visible'] = 1;
797         $arr['unseen'] = 1;
798         $arr['last-child'] = 0;
799
800         $message_id = item_store($arr);
801
802         if(! $parent_author_signature) {
803                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
804                         intval($message_id),
805                         dbesc($author_signed_data),
806                         dbesc(base64_encode($author_signature)),
807                         dbesc($diaspora_handle)
808                 );
809         }
810
811         // if the message isn't already being relayed, notify others
812         // the existence of parent_author_signature means the parent_author or owner
813         // is already relaying.
814
815         if(! $parent_author_signature)
816                 proc_run('php','include/notifier.php','comment',$message_id);
817
818         return;
819 }
820
821 function diaspora_retraction($importer,$xml) {
822
823         $guid = notags(unxmlify($xml->guid));
824         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
825         $type = notags(unxmlify($xml->type));
826
827         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
828         if(! $contact)
829                 return;
830
831         if($type === 'Person') {
832                 contact_remove($contact['id']);
833         }
834         elseif($type === 'Post') {
835                 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
836                         dbesc('guid'),
837                         intval($importer['uid'])
838                 );
839                 if(count($r)) {
840                         if(link_compare($r[0]['author-link'],$contact['url'])) {
841                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
842                                         dbesc(datetime_convert()),                      
843                                         intval($r[0]['id'])
844                                 );
845                         }
846                 }
847         }
848
849         http_exit_status(202);
850         // NOTREACHED
851 }
852
853 function diaspora_share($me,$contact) {
854         $a = get_app();
855         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
856         $theiraddr = $contact['addr'];
857
858         $tpl = get_markup_template('diaspora_share.tpl');
859         $msg = replace_macros($tpl, array(
860                 '$sender' => $myaddr,
861                 '$recipient' => $theiraddr
862         ));
863
864         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
865
866         return(diaspora_transmit($owner,$contact,$slap));
867 }
868
869 function diaspora_unshare($me,$contact) {
870
871         $a = get_app();
872         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
873
874         $tpl = get_markup_template('diaspora_retract.tpl');
875         $msg = replace_macros($tpl, array(
876                 '$guid'   => $me['guid'],
877                 '$type'   => 'Person',
878                 '$handle' => $myaddr
879         ));
880
881         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
882
883         return(diaspora_transmit($owner,$contact,$slap));
884
885 }
886
887
888
889 function diaspora_send_status($item,$owner,$contact) {
890
891         $a = get_app();
892         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
893         $theiraddr = $contact['addr'];
894
895         $images = array();
896
897         $body = $item['body'];
898
899         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
900         if($cnt) {
901                 foreach($matches as $mtch) {
902                         $detail = array();
903                         $detail['str'] = $mtch[0];
904                         $detail['path'] = dirname($mtch[1]) . '/';
905                         $detail['file'] = basename($mtch[1]);
906                         $detail['guid'] = $item['guid'];
907                         $detail['handle'] = $myaddr;
908                         $images[] = $detail;
909                         $body = str_replace($detail['str'],t('link'),$body);
910                 }
911         }       
912
913         $body = xmlify(html_entity_decode(bb2diaspora($body)));
914
915         $public = (($item['private']) ? 'false' : 'true');
916
917         require_once('include/datetime.php');
918         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d h:i:s \U\T\C');
919
920         $tpl = get_markup_template('diaspora_post.tpl');
921         $msg = replace_macros($tpl, array(
922                 '$body' => $body,
923                 '$guid' => $item['guid'],
924                 '$handle' => xmlify($myaddr),
925                 '$public' => $public,
926                 '$created' => $created
927         ));
928
929         logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
930
931         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
932
933         $return_code = diaspora_transmit($owner,$contact,$slap);
934
935         if(count($images)) {
936                 diaspora_send_images($item,$owner,$contact,$images);
937         }
938
939         return $return_code;
940 }
941
942
943 function diaspora_send_images($item,$owner,$contact,$images) {
944         $a = get_app();
945         if(! count($images))
946                 return;
947         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
948
949         $tpl = get_markup_template('diaspora_photo.tpl');
950         foreach($images as $image) {
951                 if(! stristr($image['path'],$mysite))
952                         continue;
953                 $resource = str_replace('.jpg','',$image['file']);
954                 $resource = substr($resource,0,strpos($resource,'-'));
955
956                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
957                         dbesc($resource),
958                         intval($owner['uid'])
959                 );
960                 if(! count($r))
961                         continue;
962                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
963                 $msg = replace_macros($tpl,array(               
964                         '$path' => xmlify($image['path']),
965                         '$filename' => xmlify($image['file']),
966                         '$msg_guid' => xmlify($image['guid']),
967                         '$guid' => xmlify($r[0]['guid']),
968                         '$handle' => xmlify($image['handle']),
969                         '$public' => xmlify($public),
970                         '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d h:i:s \U\T\C'))
971                 ));
972
973
974                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
975                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
976
977                 diaspora_transmit($owner,$contact,$slap);
978         }
979
980 }
981
982 function diaspora_send_followup($item,$owner,$contact) {
983
984         $a = get_app();
985         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
986         $theiraddr = $contact['addr'];
987
988         $p = q("select guid from item where parent = %d limit 1",
989                 $item['parent']
990         );
991         if(count($p))
992                 $parent_guid = $p[0]['guid'];
993         else
994                 return;
995
996         if($item['verb'] === ACTIVITY_LIKE) {
997                 $tpl = get_markup_template('diaspora_like.tpl');
998                 $like = true;
999                 $target_type = 'Post';
1000                 $positive = (($item['deleted']) ? 'false' : 'true');
1001         }
1002         else {
1003                 $tpl = get_markup_template('diaspora_comment.tpl');
1004                 $like = false;
1005         }
1006
1007         $text = html_entity_decode(bb2diaspora($item['body']));
1008
1009         // sign it
1010
1011         if($like)
1012                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1013         else
1014                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1015
1016         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha'));
1017
1018         $msg = replace_macros($tpl,array(
1019                 '$guid' => xmlify($item['guid']),
1020                 '$parent_guid' => xmlify($parent_guid),
1021                 '$target_type' =>xmlify($target_type),
1022                 '$authorsig' => xmlify($authorsig),
1023                 '$body' => xmlify($text),
1024                 '$positive' => xmlify($positive),
1025                 '$handle' => xmlify($myaddr)
1026         ));
1027
1028         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1029
1030         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1031
1032         return(diaspora_transmit($owner,$contact,$slap));
1033 }
1034
1035
1036 function diaspora_send_relay($item,$owner,$contact) {
1037
1038
1039         $a = get_app();
1040         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1041         $theiraddr = $contact['addr'];
1042
1043
1044         $p = q("select guid from item where parent = %d limit 1",
1045                 $item['parent']
1046         );
1047         if(count($p))
1048                 $parent_guid = $p[0]['guid'];
1049         else
1050                 return;
1051
1052         if($item['verb'] === ACTIVITY_LIKE) {
1053                 $tpl = get_markup_template('diaspora_like_relay.tpl');
1054                 $like = true;
1055                 $target_type = 'Post';
1056                 $positive = (($item['deleted']) ? 'false' : 'true');
1057         }
1058         else {
1059                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1060                 $like = false;
1061         }
1062
1063         $text = html_entity_decode(bb2diaspora($item['body']));
1064
1065         // fetch the original signature if somebody sent the post to us to relay
1066         // if we are relaying for a reply originating here, there wasn't a 'send to relay'
1067         // action. It wasn't needed. In that case create the original signature and the 
1068         // owner (parent author) signature
1069
1070         $r = q("select * from sign where iid = %d limit 1",
1071                 intval($item['id'])
1072         );
1073         if(count($r)) { 
1074                 $orig_sign = $r[0];
1075                 $signed_text = $orig_sign['signed_text'];
1076                 $authorsig = $orig_sign['signature'];
1077         }
1078         else {
1079                 if($like)
1080                         $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1081                 else
1082                         $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1083
1084                 $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha'));
1085
1086                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1087                         intval($item['id']),
1088                         dbesc($signed_text),
1089                         dbesc(base64_encode($authorsig)),
1090                         dbesc($myaddr)
1091                 );
1092
1093         }
1094
1095         // sign it
1096
1097         $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha'));
1098
1099         $msg = replace_macros($tpl,array(
1100                 '$guid' => xmlify($item['guid']),
1101                 '$parent_guid' => xmlify($parent_guid),
1102                 '$target_type' =>xmlify($target_type),
1103                 '$authorsig' => xmlify($orig_sign['signature']),
1104                 '$parentsig' => xmlify($parentauthorsig),
1105                 '$body' => xmlify($text),
1106                 '$positive' => xmlify($positive),
1107                 '$handle' => xmlify($myaddr)
1108         ));
1109
1110         logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1111
1112         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1113
1114         return(diaspora_transmit($owner,$contact,$slap));
1115
1116 }
1117
1118
1119
1120 function diaspora_send_retraction($item,$owner,$contact) {
1121
1122         $a = get_app();
1123         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1124
1125         $tpl = get_markup_template('diaspora_retract.tpl');
1126         $msg = replace_macros($tpl, array(
1127                 '$guid'   => $item['guid'],
1128                 '$type'   => 'Post',
1129                 '$handle' => $myaddr
1130         ));
1131
1132         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'])));
1133
1134         return(diaspora_transmit($owner,$contact,$slap));
1135 }
1136
1137
1138
1139 function diaspora_transmit($owner,$contact,$slap) {
1140
1141         $a = get_app();
1142
1143         post_url($contact['notify'] . '/',$slap);
1144         $return_code = $a->get_curl_code();
1145         logger('diaspora_transmit: returns: ' . $return_code);
1146
1147         if(! $return_code) {
1148                 logger('diaspora_transmit: queue message');
1149                 // queue message for redelivery
1150                 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
1151                         VALUES ( %d, '%s', '%s', '%s') ",
1152                         intval($contact['id']),
1153                         dbesc(datetime_convert()),
1154                         dbesc(datetime_convert()),
1155                         dbesc($slap)
1156                 );
1157         }
1158
1159         return(($return_code) ? $return_code : (-1));
1160 }