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