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