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