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