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