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