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