]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
93e7d2cdbc57c3f90794ec51fabc64499c7eba1f
[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
519         $str_tags = '';
520
521         $tags = get_tags($body);
522
523         if(count($tags)) {
524                 foreach($tags as $tag) {
525                         if(strpos($tag,'#') === 0) {
526                                 if(strpos($tag,'[url='))
527                                         continue;
528                                 $basetag = str_replace('_',' ',substr($tag,1));
529                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
530                                 if(strlen($str_tags))
531                                         $str_tags .= ',';
532                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
533                                 continue;
534                         }
535                 }
536         }
537         
538         $datarray['uid'] = $importer['uid'];
539         $datarray['contact-id'] = $contact['id'];
540         $datarray['wall'] = 0;
541         $datarray['guid'] = $guid;
542         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
543         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
544         $datarray['private'] = $private;
545         $datarray['parent'] = 0;
546         $datarray['owner-name'] = $contact['name'];
547         $datarray['owner-link'] = $contact['url'];
548         $datarray['owner-avatar'] = $contact['thumb'];
549         $datarray['author-name'] = $contact['name'];
550         $datarray['author-link'] = $contact['url'];
551         $datarray['author-avatar'] = $contact['thumb'];
552         $datarray['body'] = $body;
553         $datarray['tag'] = $str_tags;
554         $datarray['app']  = 'Diaspora';
555
556         $message_id = item_store($datarray);
557
558         if($message_id) {
559                 q("update item set plink = '%s' where id = %d limit 1",
560                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
561                         intval($message_id)
562                 );
563         }
564
565         return;
566
567 }
568
569 function diaspora_comment($importer,$xml,$msg) {
570
571         $a = get_app();
572         $guid = notags(unxmlify($xml->guid));
573         $parent_guid = notags(unxmlify($xml->parent_guid));
574         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
575         $target_type = notags(unxmlify($xml->target_type));
576         $text = unxmlify($xml->text);
577         $author_signature = notags(unxmlify($xml->author_signature));
578
579         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
580
581         $text = $xml->text;
582
583         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
584         if(! $contact) {
585                 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
586                 return;
587         }
588
589         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
590                 logger('diaspora_comment: Ignoring this author.');
591                 return 202;
592         }
593
594         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
595                 intval($importer['uid']),
596                 dbesc($guid)
597         );
598         if(count($r)) {
599                 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
600                 return;
601         }
602
603         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
604                 intval($importer['uid']),
605                 dbesc($parent_guid)
606         );
607         if(! count($r)) {
608                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
609                 return;
610         }
611         $parent_item = $r[0];
612
613         $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
614
615         $author_signature = base64_decode($author_signature);
616
617         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
618                 $person = $contact;
619                 $key = $msg['key'];
620         }
621         else {
622                 $person = find_diaspora_person_by_handle($diaspora_handle);     
623
624                 if(is_array($person) && x($person,'pubkey'))
625                         $key = $person['pubkey'];
626                 else {
627                         logger('diaspora_comment: unable to find author details');
628                         return;
629                 }
630         }
631
632         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
633                 logger('diaspora_comment: verification failed.');
634                 return;
635         }
636
637         if($parent_author_signature) {
638                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
639
640                 $parent_author_signature = base64_decode($parent_author_signature);
641
642                 $key = $msg['key'];
643
644                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
645                         logger('diaspora_comment: owner verification failed.');
646                         return;
647                 }
648         }
649
650         // Phew! Everything checks out. Now create an item.
651
652         $body = diaspora2bb($text);
653
654         $message_id = $diaspora_handle . ':' . $guid;
655
656         $datarray = array();
657
658         $str_tags = '';
659
660         $tags = get_tags($body);
661
662         if(count($tags)) {
663                 foreach($tags as $tag) {
664                         if(strpos($tag,'#') === 0) {
665                                 if(strpos($tag,'[url='))
666                                         continue;
667                                 $basetag = str_replace('_',' ',substr($tag,1));
668                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
669                                 if(strlen($str_tags))
670                                         $str_tags .= ',';
671                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
672                                 continue;
673                         }
674                 }
675         }
676
677         $datarray['uid'] = $importer['uid'];
678         $datarray['contact-id'] = $contact['id'];
679         $datarray['wall'] = $parent_item['wall'];
680         $datarray['gravity'] = GRAVITY_COMMENT;
681         $datarray['guid'] = $guid;
682         $datarray['uri'] = $message_id;
683         $datarray['parent-uri'] = $parent_item['uri'];
684
685         // No timestamps for comments? OK, we'll the use current time.
686         $datarray['created'] = $datarray['edited'] = datetime_convert();
687         $datarray['private'] = $parent_item['private'];
688
689         $datarray['owner-name'] = $parent_item['owner-name'];
690         $datarray['owner-link'] = $parent_item['owner-link'];
691         $datarray['owner-avatar'] = $parent_item['owner-avatar'];
692
693         $datarray['author-name'] = $person['name'];
694         $datarray['author-link'] = $person['url'];
695         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
696         $datarray['body'] = $body;
697         $datarray['tag'] = $str_tags;
698         $datarray['app']  = 'Diaspora';
699
700         $message_id = item_store($datarray);
701
702         if($message_id) {
703                 q("update item set plink = '%s' where id = %d limit 1",
704                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
705                         intval($message_id)
706                 );
707         }
708
709         if(! $parent_author_signature) {
710                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
711                         intval($message_id),
712                         dbesc($author_signed_data),
713                         dbesc(base64_encode($author_signature)),
714                         dbesc($diaspora_handle)
715                 );
716
717                 // if the message isn't already being relayed, notify others
718                 // the existence of parent_author_signature means the parent_author or owner
719                 // is already relaying.
720
721                 proc_run('php','include/notifier.php','comment',$message_id);
722         }
723         return;
724 }
725
726 function diaspora_photo($importer,$xml,$msg) {
727
728         $a = get_app();
729         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
730
731         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
732
733         $status_message_guid = notags(unxmlify($xml->status_message_guid));
734
735         $guid = notags(unxmlify($xml->guid));
736
737         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
738
739         $public = notags(unxmlify($xml->public));
740
741         $created_at = notags(unxmlify($xml_created_at));
742
743
744         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
745         if(! $contact)
746                 return;
747
748         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
749                 logger('diaspora_photo: Ignoring this author.');
750                 return 202;
751         }
752
753         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
754                 intval($importer['uid']),
755                 dbesc($status_message_guid)
756         );
757         if(! count($r)) {
758                 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
759                 return;
760         }
761         $parent_item = $r[0];
762
763         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
764
765         if(strpos($parent_item['body'],$link_text) === false) {
766                 $r = q("update item set `body` = '%s' where `id` = %d and `uid` = %d limit 1",
767                         dbesc($link_text . $parent_item['body']),
768                         intval($parent_item['id']),
769                         intval($parent_item['uid'])
770                 );
771         }
772
773         return;
774 }
775
776
777
778
779 function diaspora_like($importer,$xml,$msg) {
780
781         $a = get_app();
782         $guid = notags(unxmlify($xml->guid));
783         $parent_guid = notags(unxmlify($xml->parent_guid));
784         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
785         $target_type = notags(unxmlify($xml->target_type));
786         $positive = notags(unxmlify($xml->positive));
787         $author_signature = notags(unxmlify($xml->author_signature));
788
789         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
790
791         // likes on comments not supported here and likes on photos not supported by Diaspora
792
793         if($target_type !== 'Post')
794                 return;
795
796         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
797         if(! $contact) {
798                 logger('diaspora_like: cannot find contact: ' . $msg['author']);
799                 return;
800         }
801
802         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
803                 logger('diaspora_like: Ignoring this author.');
804                 return 202;
805         }
806
807         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
808                 intval($importer['uid']),
809                 dbesc($parent_guid)
810         );
811         if(! count($r)) {
812                 logger('diaspora_like: parent item not found: ' . $guid);
813                 return;
814         }
815
816         $parent_item = $r[0];
817
818         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
819                 intval($importer['uid']),
820                 dbesc($guid)
821         );
822         if(count($r)) {
823                 if($positive === 'true') {
824                         logger('diaspora_like: duplicate like: ' . $guid);
825                         return;
826                 } 
827                 if($positive === 'false') {
828                         q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
829                                 intval($r[0]['id']),
830                                 intval($importer['uid'])
831                         );
832                         // FIXME
833                         //  send notification via proc_run()
834                         return;
835                 }
836         }
837         if($positive === 'false') {
838                 logger('diaspora_like: unlike received with no corresponding like');
839                 return; 
840         }
841
842         $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
843
844         $author_signature = base64_decode($author_signature);
845
846         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
847                 $person = $contact;
848                 $key = $msg['key'];
849         }
850         else {
851                 $person = find_diaspora_person_by_handle($diaspora_handle);     
852                 if(is_array($person) && x($person,'pubkey'))
853                         $key = $person['pubkey'];
854                 else {
855                         logger('diaspora_like: unable to find author details');
856                         return;
857                 }
858         }
859
860         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
861                 logger('diaspora_like: verification failed.');
862                 return;
863         }
864
865         if($parent_author_signature) {
866
867                 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
868
869                 $parent_author_signature = base64_decode($parent_author_signature);
870
871                 $key = $msg['key'];
872
873                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
874                         logger('diaspora_like: owner verification failed.');
875                         return;
876                 }
877         }
878
879         // Phew! Everything checks out. Now create an item.
880
881         $uri = $diaspora_handle . ':' . $guid;
882
883         $activity = ACTIVITY_LIKE;
884         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
885         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
886         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
887         $body = $parent_item['body'];
888
889         $obj = <<< EOT
890
891         <object>
892                 <type>$objtype</type>
893                 <local>1</local>
894                 <id>{$parent_item['uri']}</id>
895                 <link>$link</link>
896                 <title></title>
897                 <content>$body</content>
898         </object>
899 EOT;
900         $bodyverb = t('%1$s likes %2$s\'s %3$s');
901
902         $arr = array();
903
904         $arr['uri'] = $uri;
905         $arr['uid'] = $importer['uid'];
906         $arr['guid'] = $guid;
907         $arr['contact-id'] = $contact['id'];
908         $arr['type'] = 'activity';
909         $arr['wall'] = $parent_item['wall'];
910         $arr['gravity'] = GRAVITY_LIKE;
911         $arr['parent'] = $parent_item['id'];
912         $arr['parent-uri'] = $parent_item['uri'];
913
914         $arr['owner-name'] = $contact['name'];
915         $arr['owner-link'] = $contact['url'];
916         $arr['owner-avatar'] = $contact['thumb'];
917
918         $arr['author-name'] = $person['name'];
919         $arr['author-link'] = $person['url'];
920         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
921         
922         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
923         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
924         $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
925         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
926
927         $arr['app']  = 'Diaspora';
928
929         $arr['private'] = $parent_item['private'];
930         $arr['verb'] = $activity;
931         $arr['object-type'] = $objtype;
932         $arr['object'] = $obj;
933         $arr['visible'] = 1;
934         $arr['unseen'] = 1;
935         $arr['last-child'] = 0;
936
937         $message_id = item_store($arr);
938
939
940         if($message_id) {
941                 q("update item set plink = '%s' where id = %d limit 1",
942                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
943                         intval($message_id)
944                 );
945         }
946
947         if(! $parent_author_signature) {
948                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
949                         intval($message_id),
950                         dbesc($author_signed_data),
951                         dbesc(base64_encode($author_signature)),
952                         dbesc($diaspora_handle)
953                 );
954         }
955
956         // if the message isn't already being relayed, notify others
957         // the existence of parent_author_signature means the parent_author or owner
958         // is already relaying.
959
960         if(! $parent_author_signature)
961                 proc_run('php','include/notifier.php','comment',$message_id);
962
963         return;
964 }
965
966 function diaspora_retraction($importer,$xml) {
967
968         $guid = notags(unxmlify($xml->guid));
969         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
970         $type = notags(unxmlify($xml->type));
971
972         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
973         if(! $contact)
974                 return;
975
976         if($type === 'Person') {
977                 contact_remove($contact['id']);
978         }
979         elseif($type === 'Post') {
980                 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
981                         dbesc('guid'),
982                         intval($importer['uid'])
983                 );
984                 if(count($r)) {
985                         if(link_compare($r[0]['author-link'],$contact['url'])) {
986                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
987                                         dbesc(datetime_convert()),                      
988                                         intval($r[0]['id'])
989                                 );
990                         }
991                 }
992         }
993
994         return 202;
995         // NOTREACHED
996 }
997
998 function diaspora_share($me,$contact) {
999         $a = get_app();
1000         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1001         $theiraddr = $contact['addr'];
1002
1003         $tpl = get_markup_template('diaspora_share.tpl');
1004         $msg = replace_macros($tpl, array(
1005                 '$sender' => $myaddr,
1006                 '$recipient' => $theiraddr
1007         ));
1008
1009         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1010
1011         return(diaspora_transmit($owner,$contact,$slap));
1012 }
1013
1014 function diaspora_unshare($me,$contact) {
1015
1016         $a = get_app();
1017         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1018
1019         $tpl = get_markup_template('diaspora_retract.tpl');
1020         $msg = replace_macros($tpl, array(
1021                 '$guid'   => $me['guid'],
1022                 '$type'   => 'Person',
1023                 '$handle' => $myaddr
1024         ));
1025
1026         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1027
1028         return(diaspora_transmit($owner,$contact,$slap));
1029
1030 }
1031
1032
1033
1034 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1035
1036         $a = get_app();
1037         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1038         $theiraddr = $contact['addr'];
1039
1040         $images = array();
1041
1042         $body = $item['body'];
1043
1044         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1045         if($cnt) {
1046                 foreach($matches as $mtch) {
1047                         $detail = array();
1048                         $detail['str'] = $mtch[0];
1049                         $detail['path'] = dirname($mtch[1]) . '/';
1050                         $detail['file'] = basename($mtch[1]);
1051                         $detail['guid'] = $item['guid'];
1052                         $detail['handle'] = $myaddr;
1053                         $images[] = $detail;
1054                         $body = str_replace($detail['str'],t('link'),$body);
1055                 }
1056         }       
1057
1058         $body = xmlify(html_entity_decode(bb2diaspora($body)));
1059
1060         $public = (($item['private']) ? 'false' : 'true');
1061
1062         require_once('include/datetime.php');
1063         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1064
1065         $tpl = get_markup_template('diaspora_post.tpl');
1066         $msg = replace_macros($tpl, array(
1067                 '$body' => $body,
1068                 '$guid' => $item['guid'],
1069                 '$handle' => xmlify($myaddr),
1070                 '$public' => $public,
1071                 '$created' => $created
1072         ));
1073
1074         logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1075
1076         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1077
1078         $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1079
1080         if(count($images)) {
1081                 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1082         }
1083
1084         return $return_code;
1085 }
1086
1087
1088 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1089         $a = get_app();
1090         if(! count($images))
1091                 return;
1092         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1093
1094         $tpl = get_markup_template('diaspora_photo.tpl');
1095         foreach($images as $image) {
1096                 if(! stristr($image['path'],$mysite))
1097                         continue;
1098                 $resource = str_replace('.jpg','',$image['file']);
1099                 $resource = substr($resource,0,strpos($resource,'-'));
1100
1101                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1102                         dbesc($resource),
1103                         intval($owner['uid'])
1104                 );
1105                 if(! count($r))
1106                         continue;
1107                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1108                 $msg = replace_macros($tpl,array(               
1109                         '$path' => xmlify($image['path']),
1110                         '$filename' => xmlify($image['file']),
1111                         '$msg_guid' => xmlify($image['guid']),
1112                         '$guid' => xmlify($r[0]['guid']),
1113                         '$handle' => xmlify($image['handle']),
1114                         '$public' => xmlify($public),
1115                         '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1116                 ));
1117
1118
1119                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1120                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1121
1122                 diaspora_transmit($owner,$contact,$slap,$public_batch);
1123         }
1124
1125 }
1126
1127 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1128
1129         $a = get_app();
1130         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1131         $theiraddr = $contact['addr'];
1132
1133         $p = q("select guid from item where parent = %d limit 1",
1134                 $item['parent']
1135         );
1136         if(count($p))
1137                 $parent_guid = $p[0]['guid'];
1138         else
1139                 return;
1140
1141         if($item['verb'] === ACTIVITY_LIKE) {
1142                 $tpl = get_markup_template('diaspora_like.tpl');
1143                 $like = true;
1144                 $target_type = 'Post';
1145                 $positive = (($item['deleted']) ? 'false' : 'true');
1146         }
1147         else {
1148                 $tpl = get_markup_template('diaspora_comment.tpl');
1149                 $like = false;
1150         }
1151
1152         $text = html_entity_decode(bb2diaspora($item['body']));
1153
1154         // sign it
1155
1156         if($like)
1157                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1158         else
1159                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1160
1161         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1162
1163         $msg = replace_macros($tpl,array(
1164                 '$guid' => xmlify($item['guid']),
1165                 '$parent_guid' => xmlify($parent_guid),
1166                 '$target_type' =>xmlify($target_type),
1167                 '$authorsig' => xmlify($authorsig),
1168                 '$body' => xmlify($text),
1169                 '$positive' => xmlify($positive),
1170                 '$handle' => xmlify($myaddr)
1171         ));
1172
1173         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1174
1175         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1176
1177         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1178 }
1179
1180
1181 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1182
1183
1184         $a = get_app();
1185         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1186         $theiraddr = $contact['addr'];
1187
1188
1189         $p = q("select guid from item where parent = %d limit 1",
1190                 $item['parent']
1191         );
1192         if(count($p))
1193                 $parent_guid = $p[0]['guid'];
1194         else
1195                 return;
1196
1197         if($item['verb'] === ACTIVITY_LIKE) {
1198                 $tpl = get_markup_template('diaspora_like_relay.tpl');
1199                 $like = true;
1200                 $target_type = 'Post';
1201                 $positive = (($item['deleted']) ? 'false' : 'true');
1202         }
1203         else {
1204                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1205                 $like = false;
1206         }
1207
1208         $body = $item['body'];
1209
1210         $text = html_entity_decode(bb2diaspora($body));
1211
1212         // fetch the original signature if somebody sent the post to us to relay
1213         // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1214         // action. It wasn't needed. In that case create the original signature and the 
1215         // owner (parent author) signature
1216         // comments from other networks will be relayed under our name, with a brief 
1217         // preamble to describe what's happening and noting the real author
1218
1219         $r = q("select * from sign where iid = %d limit 1",
1220                 intval($item['id'])
1221         );
1222         if(count($r)) { 
1223                 $orig_sign = $r[0];
1224                 $signed_text = $orig_sign['signed_text'];
1225                 $authorsig = $orig_sign['signature'];
1226                 $handle = $orig_sign['signer'];
1227         }
1228         else {
1229
1230                 $itemcontact = q("select * from contact where `id` = %d limit 1",
1231                         intval($item['contact-id'])
1232                 );
1233                 if(count($itemcontact)) {
1234                         if(! $itemcontact[0]['self']) {
1235                                 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1236                                         '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',  
1237                                         network_to_name($itemcontact['network'])) . "\n";
1238                                 $body = $prefix . $body;
1239                         }
1240                 }
1241                 else {
1242
1243                         if($like)
1244                                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1245                         else
1246                                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1247
1248                         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1249
1250                         q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1251                                 intval($item['id']),
1252                                 dbesc($signed_text),
1253                                 dbesc(base64_encode($authorsig)),
1254                                 dbesc($myaddr)
1255                         );
1256                         $handle = $myaddr;
1257                 }
1258         }
1259
1260         // sign it
1261
1262         $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1263
1264         $msg = replace_macros($tpl,array(
1265                 '$guid' => xmlify($item['guid']),
1266                 '$parent_guid' => xmlify($parent_guid),
1267                 '$target_type' =>xmlify($target_type),
1268                 '$authorsig' => xmlify($orig_sign['signature']),
1269                 '$parentsig' => xmlify($parentauthorsig),
1270                 '$body' => xmlify($text),
1271                 '$positive' => xmlify($positive),
1272                 '$handle' => xmlify($handle)
1273         ));
1274
1275         logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1276
1277         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1278
1279         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1280
1281 }
1282
1283
1284
1285 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1286
1287         $a = get_app();
1288         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1289
1290         $tpl = get_markup_template('diaspora_retract.tpl');
1291         $msg = replace_macros($tpl, array(
1292                 '$guid'   => $item['guid'],
1293                 '$type'   => 'Post',
1294                 '$handle' => $myaddr
1295         ));
1296
1297         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1298
1299         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1300 }
1301
1302
1303
1304 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
1305
1306         $a = get_app();
1307         $logid = random_string(4);
1308         logger('diaspora_transmit: ' . $logid . ' ' . (($public_batch) ? $contact['batch'] : $contact['notify']));
1309         post_url((($public_batch) ? $contact['batch'] : $contact['notify']) . '/',$slap);
1310         $return_code = $a->get_curl_code();
1311         logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
1312
1313         if((! $return_code) || (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
1314                 logger('diaspora_transmit: queue message');
1315                 // queue message for redelivery
1316                 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`,`batch`)
1317                         VALUES ( %d, '%s', '%s', '%s', %d) ",
1318                         intval($contact['id']),
1319                         dbesc(datetime_convert()),
1320                         dbesc(datetime_convert()),
1321                         dbesc($slap),
1322                         intval($public_batch)
1323                 );
1324         }
1325
1326
1327         return(($return_code) ? $return_code : (-1));
1328 }