]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
e91ebf442aadc405655736f09ba5ce3ca8814b26
[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 require_once('include/queue_fn.php');
8
9
10 function diaspora_dispatch_public($msg) {
11
12         $enabled = intval(get_config('system','diaspora_enabled'));
13         if(! $enabled) {
14                 logger('mod-diaspora: disabled');
15                 return;
16         }
17
18         $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 ",
19                 dbesc(NETWORK_DIASPORA),
20                 dbesc($msg['author'])
21         );
22         if(count($r)) {
23                 foreach($r as $rr) {
24                         logger('diaspora_public: delivering to: ' . $rr['username']);
25                         diaspora_dispatch($rr,$msg);
26                 }
27         }
28         else
29                 logger('diaspora_public: no subscribers');
30 }
31
32
33
34 function diaspora_dispatch($importer,$msg) {
35
36         $ret = 0;
37
38         $enabled = intval(get_config('system','diaspora_enabled'));
39         if(! $enabled) {
40                 logger('mod-diaspora: disabled');
41                 return;
42         }
43
44         // php doesn't like dashes in variable names
45
46         $msg['message'] = str_replace(
47                         array('<activity_streams-photo>','</activity_streams-photo>'),
48                         array('<asphoto>','</asphoto>'),
49                         $msg['message']);
50
51
52         $parsed_xml = parse_xml_string($msg['message'],false);
53
54         $xmlbase = $parsed_xml->post;
55
56         logger('diaspora_dispatch: ' . print_r($xmlbase,true), LOGGER_DEBUG);
57
58
59         if($xmlbase->request) {
60                 $ret = diaspora_request($importer,$xmlbase->request);
61         }
62         elseif($xmlbase->status_message) {
63                 $ret = diaspora_post($importer,$xmlbase->status_message);
64         }
65         elseif($xmlbase->profile) {
66                 $ret = diaspora_profile($importer,$xmlbase->profile);
67         }
68         elseif($xmlbase->comment) {
69                 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
70         }
71         elseif($xmlbase->like) {
72                 $ret = diaspora_like($importer,$xmlbase->like,$msg);
73         }
74         elseif($xmlbase->asphoto) {
75                 $ret = diaspora_asphoto($importer,$xmlbase->asphoto);
76         }
77         elseif($xmlbase->reshare) {
78                 $ret = diaspora_reshare($importer,$xmlbase->reshare);
79         }
80         elseif($xmlbase->retraction) {
81                 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
82         }
83         elseif($xmlbase->signed_retraction) {
84                 $ret = diaspora_signed_retraction($importer,$xmlbase->signed_retraction,$msg);
85         }
86         elseif($xmlbase->relayable_retraction) {
87                 $ret = diaspora_signed_retraction($importer,$xmlbase->relayable_retraction,$msg);
88         }
89         elseif($xmlbase->photo) {
90                 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
91         }
92         elseif($xmlbase->conversation) {
93                 $ret = diaspora_conversation($importer,$xmlbase->conversation,$msg);
94         }
95         elseif($xmlbase->message) {
96                 $ret = diaspora_message($importer,$xmlbase->message,$msg);
97         }
98         else {
99                 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
100         }
101         return $ret;
102 }
103
104 function diaspora_get_contact_by_handle($uid,$handle) {
105         $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
106                 dbesc(NETWORK_DIASPORA),
107                 intval($uid),
108                 dbesc($handle)
109         );
110         if($r && count($r))
111                 return $r[0];
112         return false;
113 }
114
115 function find_diaspora_person_by_handle($handle) {
116         $update = false;
117         $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
118                 dbesc(NETWORK_DIASPORA),
119                 dbesc($handle)
120         );
121         if(count($r)) {
122                 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
123                 // update record occasionally so it doesn't get stale
124                 $d = strtotime($r[0]['updated'] . ' +00:00');
125                 if($d > strtotime('now - 14 days'))
126                         return $r[0];
127                 $update = true;
128         }
129         logger('find_diaspora_person_by_handle: refresh',LOGGER_DEBUG);
130         require_once('include/Scrape.php');
131         $r = probe_url($handle, PROBE_DIASPORA);
132         if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
133                 add_fcontact($r,$update);
134                 return ($r);
135         }
136         return false;
137 }
138
139
140 function get_diaspora_key($uri) {
141         logger('Fetching diaspora key for: ' . $uri);
142
143         $r = find_diaspora_person_by_handle($uri);
144         if($r)
145                 return $r['pubkey'];
146         return '';
147 }
148
149
150 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
151         $a = get_app();
152
153         logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
154
155         
156         $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
157
158 //      $b64_data = base64_encode($msg);
159 //      $b64url_data = base64url_encode($b64_data);
160
161         $b64url_data = base64url_encode($msg);
162
163         $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
164
165         $type = 'application/xml';
166         $encoding = 'base64url';
167         $alg = 'RSA-SHA256';
168
169         $signable_data = $data  . '.' . base64url_encode($type) . '.' 
170                 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
171
172         $signature = rsa_sign($signable_data,$prvkey);
173         $sig = base64url_encode($signature);
174
175 $magic_env = <<< EOT
176 <?xml version='1.0' encoding='UTF-8'?>
177 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
178   <header>
179     <author_id>$handle</author_id>
180   </header>
181   <me:env>
182     <me:encoding>base64url</me:encoding>
183     <me:alg>RSA-SHA256</me:alg>
184     <me:data type="application/xml">$data</me:data>
185     <me:sig>$sig</me:sig>
186   </me:env>
187 </diaspora>
188 EOT;
189
190         logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
191         return $magic_env;
192
193 }
194
195
196
197
198 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
199         $a = get_app();
200
201         if($public)
202                 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
203
204         logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
205
206         // without a public key nothing will work
207
208         if(! $pubkey) {
209                 logger('diaspora_msg_build: pubkey missing: contact id: ' . $contact['id']);
210                 return '';
211         }
212
213         $inner_aes_key = random_string(32);
214         $b_inner_aes_key = base64_encode($inner_aes_key);
215         $inner_iv = random_string(16);
216         $b_inner_iv = base64_encode($inner_iv);
217
218         $outer_aes_key = random_string(32);
219         $b_outer_aes_key = base64_encode($outer_aes_key);
220         $outer_iv = random_string(16);
221         $b_outer_iv = base64_encode($outer_iv);
222         
223         $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
224
225         $padded_data = pkcs5_pad($msg,16);
226         $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
227
228         $b64_data = base64_encode($inner_encrypted);
229
230
231         $b64url_data = base64url_encode($b64_data);
232         $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
233
234         $type = 'application/xml';
235         $encoding = 'base64url';
236         $alg = 'RSA-SHA256';
237
238         $signable_data = $data  . '.' . base64url_encode($type) . '.' 
239                 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
240
241         $signature = rsa_sign($signable_data,$prvkey);
242         $sig = base64url_encode($signature);
243
244 $decrypted_header = <<< EOT
245 <decrypted_header>
246   <iv>$b_inner_iv</iv>
247   <aes_key>$b_inner_aes_key</aes_key>
248   <author_id>$handle</author_id>
249 </decrypted_header>
250 EOT;
251
252         $decrypted_header = pkcs5_pad($decrypted_header,16);
253
254         $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
255
256         $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
257
258         $encrypted_outer_key_bundle = '';
259         openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
260
261         $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
262
263         logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
264
265         $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle), 
266                 'ciphertext' => base64_encode($ciphertext)));
267         $cipher_json = base64_encode($encrypted_header_json_object);
268
269         $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
270
271 $magic_env = <<< EOT
272 <?xml version='1.0' encoding='UTF-8'?>
273 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
274   $encrypted_header
275   <me:env>
276     <me:encoding>base64url</me:encoding>
277     <me:alg>RSA-SHA256</me:alg>
278     <me:data type="application/xml">$data</me:data>
279     <me:sig>$sig</me:sig>
280   </me:env>
281 </diaspora>
282 EOT;
283
284         logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
285         return $magic_env;
286
287 }
288
289 /**
290  *
291  * diaspora_decode($importer,$xml)
292  *   array $importer -> from user table
293  *   string $xml -> urldecoded Diaspora salmon 
294  *
295  * Returns array
296  * 'message' -> decoded Diaspora XML message
297  * 'author' -> author diaspora handle
298  * 'key' -> author public key (converted to pkcs#8)
299  *
300  * Author and key are used elsewhere to save a lookup for verifying replies and likes
301  */
302
303
304 function diaspora_decode($importer,$xml) {
305
306         $public = false;
307         $basedom = parse_xml_string($xml);
308
309         $children = $basedom->children('https://joindiaspora.com/protocol');
310
311         if($children->header) {
312                 $public = true;
313                 $author_link = str_replace('acct:','',$children->header->author_id);
314         }
315         else {
316
317                 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
318         
319                 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
320                 $ciphertext = base64_decode($encrypted_header->ciphertext);
321
322                 $outer_key_bundle = '';
323                 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
324
325                 $j_outer_key_bundle = json_decode($outer_key_bundle);
326
327                 $outer_iv = base64_decode($j_outer_key_bundle->iv);
328                 $outer_key = base64_decode($j_outer_key_bundle->key);
329
330                 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
331
332
333                 $decrypted = pkcs5_unpad($decrypted);
334
335                 /**
336                  * $decrypted now contains something like
337                  *
338                  *  <decrypted_header>
339                  *     <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
340                  *     <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
341
342 ***** OBSOLETE
343
344                  *     <author>
345                  *       <name>Ryan Hughes</name>
346                  *       <uri>acct:galaxor@diaspora.pirateship.org</uri>
347                  *     </author>
348
349 ***** CURRENT
350
351                  *     <author_id>galaxor@diaspora.priateship.org</author_id>
352
353 ***** END DIFFS
354
355                  *  </decrypted_header>
356                  */
357
358                 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
359                 $idom = parse_xml_string($decrypted,false);
360
361                 $inner_iv = base64_decode($idom->iv);
362                 $inner_aes_key = base64_decode($idom->aes_key);
363
364                 $author_link = str_replace('acct:','',$idom->author_id);
365
366         }
367
368         $dom = $basedom->children(NAMESPACE_SALMON_ME);
369
370         // figure out where in the DOM tree our data is hiding
371
372         if($dom->provenance->data)
373                 $base = $dom->provenance;
374         elseif($dom->env->data)
375                 $base = $dom->env;
376         elseif($dom->data)
377                 $base = $dom;
378         
379         if(! $base) {
380                 logger('mod-diaspora: unable to locate salmon data in xml ');
381                 http_status_exit(400);
382         }
383
384
385         // Stash the signature away for now. We have to find their key or it won't be good for anything.
386         $signature = base64url_decode($base->sig);
387
388         // unpack the  data
389
390         // strip whitespace so our data element will return to one big base64 blob
391         $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
392
393
394         // stash away some other stuff for later
395
396         $type = $base->data[0]->attributes()->type[0];
397         $keyhash = $base->sig[0]->attributes()->keyhash[0];
398         $encoding = $base->encoding;
399         $alg = $base->alg;
400
401
402         $signed_data = $data  . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
403
404
405         // decode the data
406         $data = base64url_decode($data);
407
408
409         if($public) {
410                 $inner_decrypted = $data;
411         }
412         else {
413
414                 // Decode the encrypted blob
415
416                 $inner_encrypted = base64_decode($data);
417                 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
418                 $inner_decrypted = pkcs5_unpad($inner_decrypted);
419         }
420
421         if(! $author_link) {
422                 logger('mod-diaspora: Could not retrieve author URI.');
423                 http_status_exit(400);
424         }
425
426         // Once we have the author URI, go to the web and try to find their public key
427         // (first this will look it up locally if it is in the fcontact cache)
428         // This will also convert diaspora public key from pkcs#1 to pkcs#8
429
430         logger('mod-diaspora: Fetching key for ' . $author_link );
431         $key = get_diaspora_key($author_link);
432
433         if(! $key) {
434                 logger('mod-diaspora: Could not retrieve author key.');
435                 http_status_exit(400);
436         }
437
438         $verify = rsa_verify($signed_data,$signature,$key);
439
440         if(! $verify) {
441                 logger('mod-diaspora: Message did not verify. Discarding.');
442                 http_status_exit(400);
443         }
444
445         logger('mod-diaspora: Message verified.');
446
447         return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
448
449 }
450
451         
452 function diaspora_request($importer,$xml) {
453
454         $a = get_app();
455
456         $sender_handle = unxmlify($xml->sender_handle);
457         $recipient_handle = unxmlify($xml->recipient_handle);
458
459         if(! $sender_handle || ! $recipient_handle)
460                 return;
461          
462         $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
463
464         if($contact) {
465
466                 // perhaps we were already sharing with this person. Now they're sharing with us.
467                 // That makes us friends.
468
469                 if($contact['rel'] == CONTACT_IS_FOLLOWER && $importer['page-flags'] != PAGE_COMMUNITY) {
470                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
471                                 intval(CONTACT_IS_FRIEND),
472                                 intval($contact['id']),
473                                 intval($importer['uid'])
474                         );
475                 }
476                 // send notification
477
478                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
479                         intval($importer['uid'])
480                 );
481
482                 if((count($r)) && (! $r[0]['hide-friends']) && (! $contact['hidden'])) {
483                         require_once('include/items.php');
484
485                         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
486                                 intval($importer['uid'])
487                         );
488
489                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
490
491                         if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
492
493                                 $arr = array();
494                                 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']); 
495                                 $arr['uid'] = $importer['uid'];
496                                 $arr['contact-id'] = $self[0]['id'];
497                                 $arr['wall'] = 1;
498                                 $arr['type'] = 'wall';
499                                 $arr['gravity'] = 0;
500                                 $arr['origin'] = 1;
501                                 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
502                                 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
503                                 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
504                                 $arr['verb'] = ACTIVITY_FRIEND;
505                                 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
506                                 
507                                 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
508                                 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
509                                 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
510                                 $arr['body'] =  sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
511
512                                 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
513                                         . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
514                                 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
515                                 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
516                                 $arr['object'] .= '</link></object>' . "\n";
517                                 $arr['last-child'] = 1;
518
519                                 $arr['allow_cid'] = $user[0]['allow_cid'];
520                                 $arr['allow_gid'] = $user[0]['allow_gid'];
521                                 $arr['deny_cid']  = $user[0]['deny_cid'];
522                                 $arr['deny_gid']  = $user[0]['deny_gid'];
523
524                                 $i = item_store($arr);
525                                 if($i)
526                                 proc_run('php',"include/notifier.php","activity","$i");
527
528                         }
529
530                 }
531
532                 return;
533         }
534         
535         $ret = find_diaspora_person_by_handle($sender_handle);
536
537
538         if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
539                 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
540                 return;
541         }
542
543         $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
544
545
546
547         $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
548                 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
549                 intval($importer['uid']),
550                 dbesc($ret['network']),
551                 dbesc($ret['addr']),
552                 datetime_convert(),
553                 dbesc($ret['url']),
554                 dbesc(normalise_link($ret['url'])),
555                 dbesc($batch),
556                 dbesc($ret['name']),
557                 dbesc($ret['nick']),
558                 dbesc($ret['photo']),
559                 dbesc($ret['pubkey']),
560                 dbesc($ret['notify']),
561                 dbesc($ret['poll']),
562                 1,
563                 2
564         );
565                  
566         // find the contact record we just created
567
568         $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
569
570         if(! $contact_record) {
571                 logger('diaspora_request: unable to locate newly created contact record.');
572                 return;
573         }
574
575         $g = q("select def_gid from user where uid = %d limit 1",
576                 intval($importer['uid'])
577         );
578         if($g && intval($g[0]['def_gid'])) {
579                 require_once('include/group.php');
580                 group_add_member($importer['uid'],'',$contact_record['id'],$g[0]['def_gid']);
581         }
582
583         if($importer['page-flags'] == PAGE_NORMAL) {
584
585                 $hash = random_string() . (string) time();   // Generate a confirm_key
586         
587                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
588                         VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
589                         intval($importer['uid']),
590                         intval($contact_record['id']),
591                         0,
592                         0,
593                         dbesc( t('Sharing notification from Diaspora network')),
594                         dbesc($hash),
595                         dbesc(datetime_convert())
596                 );
597         }
598         else {
599
600                 // automatic friend approval
601
602                 require_once('include/Photo.php');
603
604                 $photos = import_profile_photo($contact_record['photo'],$importer['uid'],$contact_record['id']);
605                 
606                 // technically they are sharing with us (CONTACT_IS_SHARING), 
607                 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
608                 // we are going to change the relationship and make them a follower.
609
610                 if($importer['page-flags'] == PAGE_FREELOVE)
611                         $new_relation = CONTACT_IS_FRIEND;
612                 else
613                         $new_relation = CONTACT_IS_FOLLOWER;
614
615                 $r = q("UPDATE `contact` SET 
616                         `photo` = '%s', 
617                         `thumb` = '%s',
618                         `micro` = '%s', 
619                         `rel` = %d, 
620                         `name-date` = '%s', 
621                         `uri-date` = '%s', 
622                         `avatar-date` = '%s', 
623                         `blocked` = 0, 
624                         `pending` = 0
625                         WHERE `id` = %d LIMIT 1
626                         ",
627                         dbesc($photos[0]),
628                         dbesc($photos[1]),
629                         dbesc($photos[2]),
630                         intval($new_relation),
631                         dbesc(datetime_convert()),
632                         dbesc(datetime_convert()),
633                         dbesc(datetime_convert()),
634                         intval($contact_record['id'])
635                 );
636
637                 $u = q("select * from user where uid = %d limit 1",intval($importer['uid']));
638                 if($u)
639                         $ret = diaspora_share($u[0],$contact_record);
640         }
641
642         return;
643 }
644
645 function diaspora_post_allow($importer,$contact) {
646         if(($contact['blocked']) || ($contact['readonly']))
647                 return false;
648         if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
649                 return true;
650         if($contact['rel'] == CONTACT_IS_FOLLOWER)
651                 if($importer['page-flags'] == PAGE_COMMUNITY)
652                         return true;
653         return false;
654 }
655
656
657 function diaspora_post($importer,$xml) {
658
659         $a = get_app();
660         $guid = notags(unxmlify($xml->guid));
661         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
662
663         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
664         if(! $contact)
665                 return;
666
667         if(! diaspora_post_allow($importer,$contact)) {
668                 logger('diaspora_post: Ignoring this author.');
669                 return 202;
670         }
671
672         $message_id = $diaspora_handle . ':' . $guid;
673         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
674                 intval($importer['uid']),
675                 dbesc($message_id),
676                 dbesc($guid)
677         );
678         if(count($r)) {
679                 logger('diaspora_post: message exists: ' . $guid);
680                 return;
681         }
682
683         // allocate a guid on our system - we aren't fixing any collisions.
684         // we're ignoring them
685
686         $g = q("select * from guid where guid = '%s' limit 1",
687                 dbesc($guid)
688         );
689         if(! count($g)) {
690                 q("insert into guid ( guid ) values ( '%s' )",
691                         dbesc($guid)
692                 );
693         }
694
695         $created = unxmlify($xml->created_at);
696         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
697
698         $body = diaspora2bb($xml->raw_message);
699
700         $datarray = array();
701
702         $str_tags = '';
703
704         $tags = get_tags($body);
705
706         if(count($tags)) {
707                 foreach($tags as $tag) {
708                         if(strpos($tag,'#') === 0) {
709                                 if(strpos($tag,'[url='))
710                                         continue;
711
712                                 // don't link tags that are already embedded in links
713
714                                 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
715                                         continue;
716                                 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
717                                         continue;
718
719                                 $basetag = str_replace('_',' ',substr($tag,1));
720                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
721                                 if(strlen($str_tags))
722                                         $str_tags .= ',';
723                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
724                                 continue;
725                         }
726                 }
727         }
728
729         $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
730         if($cnt) {
731                 foreach($matches as $mtch) {
732                         if(strlen($str_tags))
733                                 $str_tags .= ',';
734                         $str_tags .= '@[url=' . $mtch[1] . '[/url]';    
735                 }
736         }
737
738         $datarray['uid'] = $importer['uid'];
739         $datarray['contact-id'] = $contact['id'];
740         $datarray['wall'] = 0;
741         $datarray['guid'] = $guid;
742         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
743         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
744         $datarray['private'] = $private;
745         $datarray['parent'] = 0;
746         $datarray['owner-name'] = $contact['name'];
747         $datarray['owner-link'] = $contact['url'];
748         $datarray['owner-avatar'] = $contact['thumb'];
749         $datarray['author-name'] = $contact['name'];
750         $datarray['author-link'] = $contact['url'];
751         $datarray['author-avatar'] = $contact['thumb'];
752         $datarray['body'] = $body;
753         $datarray['tag'] = $str_tags;
754         $datarray['app']  = 'Diaspora';
755
756         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
757
758         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
759
760         $message_id = item_store($datarray);
761
762         if($message_id) {
763                 q("update item set plink = '%s' where id = %d limit 1",
764                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
765                         intval($message_id)
766                 );
767         }
768
769         return;
770
771 }
772
773 function diaspora_reshare($importer,$xml) {
774
775         logger('diaspora_reshare: init: ' . print_r($xml,true));
776
777         $a = get_app();
778         $guid = notags(unxmlify($xml->guid));
779         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
780
781
782         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
783         if(! $contact)
784                 return;
785
786         if(! diaspora_post_allow($importer,$contact)) {
787                 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
788                 return 202;
789         }
790
791         $message_id = $diaspora_handle . ':' . $guid;
792         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
793                 intval($importer['uid']),
794                 dbesc($message_id),
795                 dbesc($guid)
796         );
797         if(count($r)) {
798                 logger('diaspora_reshare: message exists: ' . $guid);
799                 return;
800         }
801
802         $orig_author = notags(unxmlify($xml->root_diaspora_id));
803         $orig_guid = notags(unxmlify($xml->root_guid));
804
805         $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
806         $x = fetch_url($source_url);
807         if(! $x)
808                 $x = fetch_url(str_replace('https://','http://',$source_url));
809         if(! $x) {
810                 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
811                 return;
812         }
813         logger('diaspora_reshare: source: ' . $x);
814
815         $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
816         $source_xml = parse_xml_string($x,false);
817
818         if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
819                 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
820                 $body = scale_external_images($body,false);
821         }
822         elseif($source_xml->post->asphoto->image_url) {
823                 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
824                 $body = scale_external_images($body);
825         }
826         elseif($source_xml->post->status_message) {
827                 $body = diaspora2bb($source_xml->post->status_message->raw_message);
828                 $body = scale_external_images($body);
829
830         }
831         else {
832                 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
833                 return;
834         }
835         if(! $body) {
836                 logger('diaspora_reshare: empty body: source= ' . $x);
837                 return;
838         }
839
840         $person = find_diaspora_person_by_handle($orig_author);
841
842         if(is_array($person) && x($person,'name') && x($person,'url'))
843                 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
844         else
845                 $details = $orig_author;
846         
847         $prefix = '&#x2672; ' . $details . "\n"; 
848
849
850         // allocate a guid on our system - we aren't fixing any collisions.
851         // we're ignoring them
852
853         $g = q("select * from guid where guid = '%s' limit 1",
854                 dbesc($guid)
855         );
856         if(! count($g)) {
857                 q("insert into guid ( guid ) values ( '%s' )",
858                         dbesc($guid)
859                 );
860         }
861
862         $created = unxmlify($xml->created_at);
863         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
864
865         $datarray = array();
866
867         $str_tags = '';
868
869         $tags = get_tags($body);
870
871         if(count($tags)) {
872                 foreach($tags as $tag) {
873                         if(strpos($tag,'#') === 0) {
874                                 if(strpos($tag,'[url='))
875                                         continue;
876
877                                 // don't link tags that are already embedded in links
878
879                                 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
880                                         continue;
881                                 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
882                                         continue;
883
884
885                                 $basetag = str_replace('_',' ',substr($tag,1));
886                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
887                                 if(strlen($str_tags))
888                                         $str_tags .= ',';
889                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
890                                 continue;
891                         }
892                 }
893         }
894         
895         $datarray['uid'] = $importer['uid'];
896         $datarray['contact-id'] = $contact['id'];
897         $datarray['wall'] = 0;
898         $datarray['guid'] = $guid;
899         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
900         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
901         $datarray['private'] = $private;
902         $datarray['parent'] = 0;
903         $datarray['owner-name'] = $contact['name'];
904         $datarray['owner-link'] = $contact['url'];
905         $datarray['owner-avatar'] = $contact['thumb'];
906         $datarray['author-name'] = $contact['name'];
907         $datarray['author-link'] = $contact['url'];
908         $datarray['author-avatar'] = $contact['thumb'];
909         $datarray['body'] = $prefix . $body;
910         $datarray['tag'] = $str_tags;
911         $datarray['app']  = 'Diaspora';
912
913         $message_id = item_store($datarray);
914
915         if($message_id) {
916                 q("update item set plink = '%s' where id = %d limit 1",
917                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
918                         intval($message_id)
919                 );
920         }
921
922         return;
923
924 }
925
926
927 function diaspora_asphoto($importer,$xml) {
928         logger('diaspora_asphoto called');
929
930         $a = get_app();
931         $guid = notags(unxmlify($xml->guid));
932         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
933
934         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
935         if(! $contact)
936                 return;
937
938         if(! diaspora_post_allow($importer,$contact)) {
939                 logger('diaspora_asphoto: Ignoring this author.');
940                 return 202;
941         }
942
943         $message_id = $diaspora_handle . ':' . $guid;
944         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
945                 intval($importer['uid']),
946                 dbesc($message_id),
947                 dbesc($guid)
948         );
949         if(count($r)) {
950                 logger('diaspora_asphoto: message exists: ' . $guid);
951                 return;
952         }
953
954         // allocate a guid on our system - we aren't fixing any collisions.
955         // we're ignoring them
956
957         $g = q("select * from guid where guid = '%s' limit 1",
958                 dbesc($guid)
959         );
960         if(! count($g)) {
961                 q("insert into guid ( guid ) values ( '%s' )",
962                         dbesc($guid)
963                 );
964         }
965
966         $created = unxmlify($xml->created_at);
967         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
968
969         if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
970                 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
971                 $body = scale_external_images($body,false);
972         }
973         elseif($xml->image_url) {
974                 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
975                 $body = scale_external_images($body);
976         }
977         else {
978                 logger('diaspora_asphoto: no photo url found.');
979                 return;
980         }
981
982         $datarray = array();
983
984         
985         $datarray['uid'] = $importer['uid'];
986         $datarray['contact-id'] = $contact['id'];
987         $datarray['wall'] = 0;
988         $datarray['guid'] = $guid;
989         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
990         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
991         $datarray['private'] = $private;
992         $datarray['parent'] = 0;
993         $datarray['owner-name'] = $contact['name'];
994         $datarray['owner-link'] = $contact['url'];
995         $datarray['owner-avatar'] = $contact['thumb'];
996         $datarray['author-name'] = $contact['name'];
997         $datarray['author-link'] = $contact['url'];
998         $datarray['author-avatar'] = $contact['thumb'];
999         $datarray['body'] = $body;
1000         
1001         $datarray['app']  = 'Diaspora/Cubbi.es';
1002
1003         $message_id = item_store($datarray);
1004
1005         if($message_id) {
1006                 q("update item set plink = '%s' where id = %d limit 1",
1007                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1008                         intval($message_id)
1009                 );
1010         }
1011
1012         return;
1013
1014 }
1015
1016
1017
1018
1019
1020
1021 function diaspora_comment($importer,$xml,$msg) {
1022
1023         $a = get_app();
1024         $guid = notags(unxmlify($xml->guid));
1025         $parent_guid = notags(unxmlify($xml->parent_guid));
1026         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1027         $target_type = notags(unxmlify($xml->target_type));
1028         $text = unxmlify($xml->text);
1029         $author_signature = notags(unxmlify($xml->author_signature));
1030
1031         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1032
1033         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1034         if(! $contact) {
1035                 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1036                 return;
1037         }
1038
1039         if(! diaspora_post_allow($importer,$contact)) {
1040                 logger('diaspora_comment: Ignoring this author.');
1041                 return 202;
1042         }
1043
1044         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1045                 intval($importer['uid']),
1046                 dbesc($guid)
1047         );
1048         if(count($r)) {
1049                 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1050                 return;
1051         }
1052
1053         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1054                 intval($importer['uid']),
1055                 dbesc($parent_guid)
1056         );
1057         if(! count($r)) {
1058                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1059                 return;
1060         }
1061         $parent_item = $r[0];
1062
1063
1064         /* How Diaspora performs comment signature checking:
1065
1066            - If an item has been sent by the comment author to the top-level post owner to relay on
1067              to the rest of the contacts on the top-level post, the top-level post owner should check
1068              the author_signature, then create a parent_author_signature before relaying the comment on
1069            - If an item has been relayed on by the top-level post owner, the contacts who receive it
1070              check only the parent_author_signature. Basically, they trust that the top-level post
1071              owner has already verified the authenticity of anything he/she sends out
1072            - In either case, the signature that get checked is the signature created by the person
1073              who sent the salmon
1074         */
1075
1076         $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1077         $key = $msg['key'];
1078
1079         if($parent_author_signature) {
1080                 // If a parent_author_signature exists, then we've received the comment
1081                 // relayed from the top-level post owner. There's no need to check the
1082                 // author_signature if the parent_author_signature is valid
1083
1084                 $parent_author_signature = base64_decode($parent_author_signature);
1085
1086                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1087                         logger('diaspora_comment: top-level owner verification failed.');
1088                         return;
1089                 }
1090         }
1091         else {
1092                 // If there's no parent_author_signature, then we've received the comment
1093                 // from the comment creator. In that case, the person is commenting on
1094                 // our post, so he/she must be a contact of ours and his/her public key
1095                 // should be in $msg['key']
1096
1097 /*              if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1098                         $person = $contact;
1099                         $key = $msg['key'];
1100                 }
1101                 else {
1102                         $person = find_diaspora_person_by_handle($diaspora_handle);     
1103
1104                         if(is_array($person) && x($person,'pubkey'))
1105                                 $key = $person['pubkey'];
1106                         else {
1107                                 logger('diaspora_comment: unable to find author details');
1108                                 return;
1109                         }
1110                 }*/
1111
1112                 $author_signature = base64_decode($author_signature);
1113
1114                 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1115                         logger('diaspora_comment: comment author verification failed.');
1116                         return;
1117                 }
1118         }
1119
1120         // Phew! Everything checks out. Now create an item.
1121
1122         $body = diaspora2bb($text);
1123
1124         $message_id = $diaspora_handle . ':' . $guid;
1125
1126         $datarray = array();
1127
1128         $str_tags = '';
1129
1130         $tags = get_tags($body);
1131
1132         if(count($tags)) {
1133                 foreach($tags as $tag) {
1134                         if(strpos($tag,'#') === 0) {
1135                                 if(strpos($tag,'[url='))
1136                                         continue;
1137
1138                                 // don't link tags that are already embedded in links
1139
1140                                 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
1141                                         continue;
1142                                 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
1143                                         continue;
1144
1145
1146                                 $basetag = str_replace('_',' ',substr($tag,1));
1147                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1148                                 if(strlen($str_tags))
1149                                         $str_tags .= ',';
1150                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1151                                 continue;
1152                         }
1153                 }
1154         }
1155
1156         $datarray['uid'] = $importer['uid'];
1157         $datarray['contact-id'] = $contact['id'];
1158         $datarray['wall'] = $parent_item['wall'];
1159         $datarray['gravity'] = GRAVITY_COMMENT;
1160         $datarray['guid'] = $guid;
1161         $datarray['uri'] = $message_id;
1162         $datarray['parent-uri'] = $parent_item['uri'];
1163
1164         // No timestamps for comments? OK, we'll the use current time.
1165         $datarray['created'] = $datarray['edited'] = datetime_convert();
1166         $datarray['private'] = $parent_item['private'];
1167
1168         $datarray['owner-name'] = $parent_item['owner-name'];
1169         $datarray['owner-link'] = $parent_item['owner-link'];
1170         $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1171
1172         $datarray['author-name'] = $person['name'];
1173         $datarray['author-link'] = $person['url'];
1174         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1175         $datarray['body'] = $body;
1176         $datarray['tag'] = $str_tags;
1177
1178         // We can't be certain what the original app is if the message is relayed.
1179         if(($parent_item['origin']) && (! $parent_author_signature)) 
1180                 $datarray['app']  = 'Diaspora';
1181
1182         $message_id = item_store($datarray);
1183
1184         if($message_id) {
1185                 q("update item set plink = '%s' where id = %d limit 1",
1186                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1187                         intval($message_id)
1188                 );
1189         }
1190
1191         if(($parent_item['origin']) && (! $parent_author_signature)) {
1192                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1193                         intval($message_id),
1194                         dbesc($author_signed_data),
1195                         dbesc(base64_encode($author_signature)),
1196                         dbesc($diaspora_handle)
1197                 );
1198
1199                 // if the message isn't already being relayed, notify others
1200                 // the existence of parent_author_signature means the parent_author or owner
1201                 // is already relaying.
1202
1203                 proc_run('php','include/notifier.php','comment',$message_id);
1204         }
1205
1206         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1207                 dbesc($parent_item['uri']),
1208                 intval($importer['uid'])
1209         );
1210
1211         if(count($myconv)) {
1212                 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1213
1214                 foreach($myconv as $conv) {
1215
1216                         // now if we find a match, it means we're in this conversation
1217         
1218                         if(! link_compare($conv['author-link'],$importer_url))
1219                                 continue;
1220
1221                         require_once('include/enotify.php');
1222                                                                 
1223                         $conv_parent = $conv['parent'];
1224
1225                         notification(array(
1226                                 'type'         => NOTIFY_COMMENT,
1227                                 'notify_flags' => $importer['notify-flags'],
1228                                 'language'     => $importer['language'],
1229                                 'to_name'      => $importer['username'],
1230                                 'to_email'     => $importer['email'],
1231                                 'uid'          => $importer['uid'],
1232                                 'item'         => $datarray,
1233                                 'link'             => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id,
1234                                 'source_name'  => $datarray['author-name'],
1235                                 'source_link'  => $datarray['author-link'],
1236                                 'source_photo' => $datarray['author-avatar'],
1237                                 'verb'         => ACTIVITY_POST,
1238                                 'otype'        => 'item',
1239                                 'parent'       => $conv_parent,
1240
1241                         ));
1242
1243                         // only send one notification
1244                         break;
1245                 }
1246         }
1247         return;
1248 }
1249
1250
1251
1252
1253 function diaspora_conversation($importer,$xml,$msg) {
1254
1255         $a = get_app();
1256
1257         $guid = notags(unxmlify($xml->guid));
1258         $subject = notags(unxmlify($xml->subject));
1259         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1260         $participant_handles = notags(unxmlify($xml->participant_handles));
1261         $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1262
1263         $parent_uri = $diaspora_handle . ':' . $guid;
1264  
1265         $messages = $xml->message;
1266
1267         if(! count($messages)) {
1268                 logger('diaspora_conversation: empty conversation');
1269                 return;
1270         }
1271
1272         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1273         if(! $contact) {
1274                 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1275                 return;
1276         }
1277
1278         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1279                 logger('diaspora_conversation: Ignoring this author.');
1280                 return 202;
1281         }
1282
1283         $conversation = null;
1284
1285         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1286                 intval($importer['uid']),
1287                 dbesc($guid)
1288         );
1289         if(count($c))
1290                 $conversation = $c[0];
1291         else {
1292                 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1293                         intval($importer['uid']),
1294                         dbesc($guid),
1295                         dbesc($diaspora_handle),
1296                         dbesc(datetime_convert('UTC','UTC',$created_at)),
1297                         dbesc(datetime_convert()),
1298                         dbesc($subject),
1299                         dbesc($participant_handles)
1300                 );
1301                 if($r)
1302                         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1303                 intval($importer['uid']),
1304             dbesc($guid)
1305         );
1306             if(count($c))
1307             $conversation = $c[0];
1308         }
1309         if(! $conversation) {
1310                 logger('diaspora_conversation: unable to create conversation.');
1311                 return;
1312         }
1313
1314         foreach($messages as $mesg) {
1315
1316                 $reply = 0;
1317
1318                 $msg_guid = notags(unxmlify($mesg->guid));
1319                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1320                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1321                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1322                 $msg_text = unxmlify($mesg->text);
1323                 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1324                 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1325                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1326                 if($msg_conversation_guid != $guid) {
1327                         logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1328                         continue;
1329                 }
1330
1331                 $body = diaspora2bb($msg_text);
1332                 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1333
1334                 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1335
1336                 $author_signature = base64_decode($msg_author_signature);
1337
1338                 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1339                         $person = $contact;
1340                         $key = $msg['key'];
1341                 }
1342                 else {
1343                         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1344
1345                         if(is_array($person) && x($person,'pubkey'))
1346                                 $key = $person['pubkey'];
1347                         else {
1348                                 logger('diaspora_conversation: unable to find author details');
1349                                 continue;
1350                         }
1351                 }
1352
1353                 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1354                         logger('diaspora_conversation: verification failed.');
1355                         continue;
1356                 }
1357
1358                 if($msg_parent_author_signature) {
1359                         $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1360
1361                         $parent_author_signature = base64_decode($msg_parent_author_signature);
1362
1363                         $key = $msg['key'];
1364
1365                         if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1366                                 logger('diaspora_conversation: owner verification failed.');
1367                                 continue;
1368                         }
1369                 }
1370
1371                 $r = q("select id from mail where `uri` = '%s' limit 1",
1372                         dbesc($message_id)
1373                 );
1374                 if(count($r)) {
1375                         logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1376                         continue;
1377                 }
1378
1379                 q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1380                         intval($importer['uid']),
1381                         dbesc($msg_guid),
1382                         intval($conversation['id']),
1383                         dbesc($person['name']),
1384                         dbesc($person['photo']),
1385                         dbesc($person['url']),
1386                         intval($contact['id']),  
1387                         dbesc($subject),
1388                         dbesc($body),
1389                         0,
1390                         0,
1391                         dbesc($message_id),
1392                         dbesc($parent_uri),
1393                         dbesc($msg_created_at)
1394                 );                      
1395
1396                 q("update conv set updated = '%s' where id = %d limit 1",
1397                         dbesc(datetime_convert()),
1398                         intval($conversation['id'])
1399                 );              
1400
1401                 require_once('include/enotify.php');
1402                 notification(array(                     
1403                         'type' => NOTIFY_MAIL,
1404                         'notify_flags' => $importer['notify-flags'],
1405                         'language' => $importer['language'],
1406                         'to_name' => $importer['username'],
1407                         'to_email' => $importer['email'],
1408                         'uid' =>$importer['importer_uid'],
1409                         'item' => array('subject' => $subject, 'body' => $body),
1410                         'source_name' => $person['name'],
1411                         'source_link' => $person['url'],
1412                         'source_photo' => $person['thumb'],
1413                         'verb' => ACTIVITY_POST,
1414                         'otype' => 'mail'
1415                 ));
1416         }       
1417
1418         return;
1419 }
1420
1421 function diaspora_message($importer,$xml,$msg) {
1422
1423         $a = get_app();
1424
1425         $msg_guid = notags(unxmlify($xml->guid));
1426         $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1427         $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1428         $msg_author_signature = notags(unxmlify($xml->author_signature));
1429         $msg_text = unxmlify($xml->text);
1430         $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1431         $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1432         $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1433
1434         $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1435  
1436         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1437         if(! $contact) {
1438                 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1439                 return;
1440         }
1441
1442         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1443                 logger('diaspora_message: Ignoring this author.');
1444                 return 202;
1445         }
1446
1447         $conversation = null;
1448
1449         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1450                 intval($importer['uid']),
1451                 dbesc($msg_conversation_guid)
1452         );
1453         if(count($c))
1454                 $conversation = $c[0];
1455         else {
1456                 logger('diaspora_message: conversation not available.');
1457                 return;
1458         }
1459
1460         $reply = 0;
1461                         
1462         $body = diaspora2bb($msg_text);
1463         $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1464
1465         $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1466
1467
1468         $author_signature = base64_decode($msg_author_signature);
1469
1470         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1471         if(is_array($person) && x($person,'pubkey'))
1472                 $key = $person['pubkey'];
1473         else {
1474                 logger('diaspora_message: unable to find author details');
1475                 return;
1476         }
1477
1478         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1479                 logger('diaspora_message: verification failed.');
1480                 return;
1481         }
1482
1483         $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1484                 dbesc($message_id),
1485                 intval($importer['uid'])
1486         );
1487         if(count($r)) {
1488                 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1489                 return;
1490         }
1491
1492         q("insert into mail ( `uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`) values ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1493                 intval($importer['uid']),
1494                 dbesc($msg_guid),
1495                 intval($conversation['id']),
1496                 dbesc($person['name']),
1497                 dbesc($person['photo']),
1498                 dbesc($person['url']),
1499                 intval($contact['id']),  
1500                 dbesc($conversation['subject']),
1501                 dbesc($body),
1502                 0,
1503                 1,
1504                 dbesc($message_id),
1505                 dbesc($parent_uri),
1506                 dbesc($msg_created_at)
1507         );                      
1508
1509         q("update conv set updated = '%s' where id = %d limit 1",
1510                 dbesc(datetime_convert()),
1511                 intval($conversation['id'])
1512         );              
1513         
1514         return;
1515 }
1516
1517
1518 function diaspora_photo($importer,$xml,$msg) {
1519
1520         $a = get_app();
1521
1522         logger('diaspora_photo: init',LOGGER_DEBUG);
1523
1524         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1525
1526         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1527
1528         $status_message_guid = notags(unxmlify($xml->status_message_guid));
1529
1530         $guid = notags(unxmlify($xml->guid));
1531
1532         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1533
1534         $public = notags(unxmlify($xml->public));
1535
1536         $created_at = notags(unxmlify($xml_created_at));
1537
1538         logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1539
1540         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1541         if(! $contact) {
1542                 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1543                 return;
1544         }
1545
1546         if(! diaspora_post_allow($importer,$contact)) {
1547                 logger('diaspora_photo: Ignoring this author.');
1548                 return 202;
1549         }
1550
1551         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1552                 intval($importer['uid']),
1553                 dbesc($status_message_guid)
1554         );
1555         if(! count($r)) {
1556                 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1557                 return;
1558         }
1559
1560         $parent_item = $r[0];
1561
1562         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1563
1564         $link_text = scale_external_images($link_text);
1565
1566         if(strpos($parent_item['body'],$link_text) === false) {
1567                 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1568                         dbesc($link_text . $parent_item['body']),
1569                         intval($parent_item['id']),
1570                         intval($parent_item['uid'])
1571                 );
1572         }
1573
1574         return;
1575 }
1576
1577
1578
1579
1580 function diaspora_like($importer,$xml,$msg) {
1581
1582         $a = get_app();
1583         $guid = notags(unxmlify($xml->guid));
1584         $parent_guid = notags(unxmlify($xml->parent_guid));
1585         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1586         $target_type = notags(unxmlify($xml->target_type));
1587         $positive = notags(unxmlify($xml->positive));
1588         $author_signature = notags(unxmlify($xml->author_signature));
1589
1590         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1591
1592         // likes on comments not supported here and likes on photos not supported by Diaspora
1593
1594         if($target_type !== 'Post')
1595                 return;
1596
1597         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1598         if(! $contact) {
1599                 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1600                 return;
1601         }
1602
1603         if(! diaspora_post_allow($importer,$contact)) {
1604                 logger('diaspora_like: Ignoring this author.');
1605                 return 202;
1606         }
1607
1608         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1609                 intval($importer['uid']),
1610                 dbesc($parent_guid)
1611         );
1612         if(! count($r)) {
1613                 logger('diaspora_like: parent item not found: ' . $guid);
1614                 return;
1615         }
1616
1617         $parent_item = $r[0];
1618
1619         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1620                 intval($importer['uid']),
1621                 dbesc($guid)
1622         );
1623         if(count($r)) {
1624                 if($positive === 'true') {
1625                         logger('diaspora_like: duplicate like: ' . $guid);
1626                         return;
1627                 } 
1628                 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1629                 // It looks like "RelayableRetractions" are used for "unlike" instead
1630                 if($positive === 'false') {
1631                         logger('diaspora_like: received a like with positive set to "false"...ignoring');
1632 /*                      q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1633                                 intval($r[0]['id']),
1634                                 intval($importer['uid'])
1635                         );*/
1636                         // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
1637                         //  send notification via proc_run()
1638                         return;
1639                 }
1640         }
1641         // Note: I don't think "Like" objects with positive = "false" are ever actually used
1642         // It looks like "RelayableRetractions" are used for "unlike" instead
1643         if($positive === 'false') {
1644                 logger('diaspora_like: received a like with positive set to "false"');
1645                 logger('diaspora_like: unlike received with no corresponding like...ignoring');
1646                 return; 
1647         }
1648
1649
1650         /* How Diaspora performs "like" signature checking:
1651
1652            - If an item has been sent by the like author to the top-level post owner to relay on
1653              to the rest of the contacts on the top-level post, the top-level post owner should check
1654              the author_signature, then create a parent_author_signature before relaying the like on
1655            - If an item has been relayed on by the top-level post owner, the contacts who receive it
1656              check only the parent_author_signature. Basically, they trust that the top-level post
1657              owner has already verified the authenticity of anything he/she sends out
1658            - In either case, the signature that get checked is the signature created by the person
1659              who sent the salmon
1660         */
1661
1662         $signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1663         $key = $msg['key'];
1664
1665         if($parent_author_signature) {
1666                 // If a parent_author_signature exists, then we've received the like
1667                 // relayed from the top-level post owner. There's no need to check the
1668                 // author_signature if the parent_author_signature is valid
1669
1670                 $parent_author_signature = base64_decode($parent_author_signature);
1671
1672                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1673                         logger('diaspora_like: top-level owner verification failed.');
1674                         return;
1675                 }
1676         }
1677         else {
1678                 // If there's no parent_author_signature, then we've received the like
1679                 // from the like creator. In that case, the person is "like"ing
1680                 // our post, so he/she must be a contact of ours and his/her public key
1681                 // should be in $msg['key']
1682
1683 /*              if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1684                         $person = $contact;
1685                         $key = $msg['key'];
1686                 }
1687                 else {
1688                         $person = find_diaspora_person_by_handle($diaspora_handle);     
1689                         if(is_array($person) && x($person,'pubkey'))
1690                                 $key = $person['pubkey'];
1691                         else {
1692                                 logger('diaspora_like: unable to find author details');
1693                                 return;
1694                         }
1695                 }*/
1696
1697                 $author_signature = base64_decode($author_signature);
1698
1699                 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1700                         logger('diaspora_like: like creator verification failed.');
1701                         return;
1702                 }
1703         }
1704
1705         // Phew! Everything checks out. Now create an item.
1706
1707         $uri = $diaspora_handle . ':' . $guid;
1708
1709         $activity = ACTIVITY_LIKE;
1710         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1711         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
1712         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1713         $body = $parent_item['body'];
1714
1715         $obj = <<< EOT
1716
1717         <object>
1718                 <type>$objtype</type>
1719                 <local>1</local>
1720                 <id>{$parent_item['uri']}</id>
1721                 <link>$link</link>
1722                 <title></title>
1723                 <content>$body</content>
1724         </object>
1725 EOT;
1726         $bodyverb = t('%1$s likes %2$s\'s %3$s');
1727
1728         $arr = array();
1729
1730         $arr['uri'] = $uri;
1731         $arr['uid'] = $importer['uid'];
1732         $arr['guid'] = $guid;
1733         $arr['contact-id'] = $contact['id'];
1734         $arr['type'] = 'activity';
1735         $arr['wall'] = $parent_item['wall'];
1736         $arr['gravity'] = GRAVITY_LIKE;
1737         $arr['parent'] = $parent_item['id'];
1738         $arr['parent-uri'] = $parent_item['uri'];
1739
1740         $arr['owner-name'] = $parent_item['name'];
1741         $arr['owner-link'] = $parent_item['url'];
1742         $arr['owner-avatar'] = $parent_item['thumb'];
1743
1744         $arr['author-name'] = $person['name'];
1745         $arr['author-link'] = $person['url'];
1746         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1747         
1748         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1749         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1750         $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1751         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
1752
1753         $arr['app']  = 'Diaspora';
1754
1755         $arr['private'] = $parent_item['private'];
1756         $arr['verb'] = $activity;
1757         $arr['object-type'] = $objtype;
1758         $arr['object'] = $obj;
1759         $arr['visible'] = 1;
1760         $arr['unseen'] = 1;
1761         $arr['last-child'] = 0;
1762
1763         $message_id = item_store($arr);
1764
1765
1766         if($message_id) {
1767                 q("update item set plink = '%s' where id = %d limit 1",
1768                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1769                         intval($message_id)
1770                 );
1771         }
1772
1773         if(! $parent_author_signature) {
1774                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1775                         intval($message_id),
1776                         dbesc($author_signed_data),
1777                         dbesc(base64_encode($author_signature)),
1778                         dbesc($diaspora_handle)
1779                 );
1780         }
1781
1782         // if the message isn't already being relayed, notify others
1783         // the existence of parent_author_signature means the parent_author or owner
1784         // is already relaying. The parent_item['origin'] indicates the message was created on our system
1785
1786         if(($parent_item['origin']) && (! $parent_author_signature))
1787                 proc_run('php','include/notifier.php','comment',$message_id);
1788
1789         return;
1790 }
1791
1792 function diaspora_retraction($importer,$xml) {
1793
1794
1795         $guid = notags(unxmlify($xml->guid));
1796         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1797         $type = notags(unxmlify($xml->type));
1798
1799         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1800         if(! $contact)
1801                 return;
1802
1803         if($type === 'Person') {
1804                 require_once('include/Contact.php');
1805                 contact_remove($contact['id']);
1806         }
1807         elseif($type === 'Post') {
1808                 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
1809                         dbesc('guid'),
1810                         intval($importer['uid'])
1811                 );
1812                 if(count($r)) {
1813                         if(link_compare($r[0]['author-link'],$contact['url'])) {
1814                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1815                                         dbesc(datetime_convert()),                      
1816                                         intval($r[0]['id'])
1817                                 );
1818                         }
1819                 }
1820         }
1821
1822         return 202;
1823         // NOTREACHED
1824 }
1825
1826 function diaspora_signed_retraction($importer,$xml,$msg) {
1827
1828
1829         $guid = notags(unxmlify($xml->target_guid));
1830         $diaspora_handle = notags(unxmlify($xml->sender_handle));
1831         $type = notags(unxmlify($xml->target_type));
1832         $sig = notags(unxmlify($xml->target_author_signature));
1833
1834         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1835
1836         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1837         if(! $contact) {
1838                 logger('diaspora_signed_retraction: no contact');
1839                 return;
1840         }
1841
1842
1843         $signed_data = $guid . ';' . $type ;
1844         $key = $msg['key'];
1845
1846         /* How Diaspora performs relayable_retraction signature checking:
1847
1848            - If an item has been sent by the item author to the top-level post owner to relay on
1849              to the rest of the contacts on the top-level post, the top-level post owner checks
1850              the author_signature, then creates a parent_author_signature before relaying the item on
1851            - If an item has been relayed on by the top-level post owner, the contacts who receive it
1852              check only the parent_author_signature. Basically, they trust that the top-level post
1853              owner has already verified the authenticity of anything he/she sends out
1854            - In either case, the signature that get checked is the signature created by the person
1855              who sent the salmon
1856         */
1857
1858         if($parent_author_signature) {
1859
1860                 $parent_author_signature = base64_decode($parent_author_signature);
1861
1862                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1863                         logger('diaspora_signed_retraction: top-level post owner verification failed');
1864                         return;
1865                 }
1866
1867         }
1868         else {
1869
1870 /*              if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1871                         $person = $contact;
1872                         $key = $msg['key'];
1873                 }
1874                 else {
1875                         $person = find_diaspora_person_by_handle($diaspora_handle);     
1876
1877                         if(is_array($person) && x($person,'pubkey'))
1878                                 $key = $person['pubkey'];
1879                         else {
1880                                 logger('diaspora_signed_retraction: unable to find author details');
1881                                 return;
1882                         }
1883                 }*/
1884
1885                 $sig_decode = base64_decode($sig);
1886
1887                 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
1888                         logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
1889                         return;
1890                 }
1891         }
1892
1893         if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
1894                 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
1895                         dbesc($guid),
1896                         intval($importer['uid'])
1897                 );
1898                 if(count($r)) {
1899                         if(link_compare($r[0]['author-link'],$contact['url'])) {
1900                                 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d limit 1",
1901                                         dbesc(datetime_convert()),                      
1902                                         dbesc(datetime_convert()),                      
1903                                         intval($r[0]['id'])
1904                                 );
1905         
1906                                 // Now check if the retraction needs to be relayed by us
1907                                 //
1908                                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
1909                                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
1910                                 // The only item with `parent` and `id` as the parent id is the parent item.
1911                                 $p = q("select origin from item where parent = %d and id = %d limit 1",
1912                                         $r[0]['parent'],
1913                                         $r[0]['parent']
1914                                 );
1915                                 if(count($p)) {
1916                                         if(($p[0]['origin']) && (! $parent_author_signature)) {
1917                                                 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1918                                                         $r[0]['id'],
1919                                                         dbesc($signed_data),
1920                                                         dbesc($sig),
1921                                                         dbesc($diaspora_handle)
1922                                                 );
1923
1924                                                 // the existence of parent_author_signature would have meant the parent_author or owner
1925                                                 // is already relaying.
1926                                                 logger('diaspora_signed_retraction: relaying relayable_retraction');
1927
1928                                                 proc_run('php','include/notifier.php','relayable_retraction',$r[0]['id']);
1929                                         }
1930                                 }
1931                         }
1932                 }
1933         }
1934         else
1935                 logger('diaspora_signed_retraction: unknown type: ' . $type);
1936
1937         return 202;
1938         // NOTREACHED
1939 }
1940
1941 function diaspora_profile($importer,$xml) {
1942
1943         $a = get_app();
1944         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1945
1946         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1947         if(! $contact)
1948                 return;
1949
1950         if($contact['blocked']) {
1951                 logger('diaspora_post: Ignoring this author.');
1952                 return 202;
1953         }
1954
1955         $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1956         $image_url = unxmlify($xml->image_url);
1957         $birthday = unxmlify($xml->birthday);
1958
1959         $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE  `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1960                 intval($importer['uid']),
1961                 intval($contact['id'])
1962         );
1963         $oldphotos = ((count($r)) ? $r : null);
1964
1965         require_once('include/Photo.php');
1966
1967         $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1968         
1969         // Generic birthday. We don't know the timezone. The year is irrelevant. 
1970
1971         $birthday = str_replace('1000','1901',$birthday);
1972
1973         $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1974
1975         // this is to prevent multiple birthday notifications in a single year
1976         // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1977
1978         if(substr($birthday,5) === substr($contact['bd'],5))
1979                 $birthday = $contact['bd'];
1980
1981         // TODO: update name on item['author-name'] if the name changed. See consume_feed()
1982         // Not doing this currently because D* protocol is scheduled for revision soon. 
1983
1984         $r = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' , `bd` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
1985                 dbesc($name),
1986                 dbesc(datetime_convert()),
1987                 dbesc($images[0]),
1988                 dbesc($images[1]),
1989                 dbesc($images[2]),
1990                 dbesc(datetime_convert()),
1991                 dbesc($birthday),
1992                 intval($contact['id']),
1993                 intval($importer['uid'])
1994         ); 
1995
1996         if($r) {
1997                 if($oldphotos) {
1998                         foreach($oldphotos as $ph) {
1999                                 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2000                                         intval($importer['uid']),
2001                                         intval($contact['id']),
2002                                         dbesc($ph['resource-id'])
2003                                 );
2004                         }
2005                 }
2006         }       
2007
2008         return;
2009
2010 }
2011
2012 function diaspora_share($me,$contact) {
2013         $a = get_app();
2014         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2015         $theiraddr = $contact['addr'];
2016
2017         $tpl = get_markup_template('diaspora_share.tpl');
2018         $msg = replace_macros($tpl, array(
2019                 '$sender' => $myaddr,
2020                 '$recipient' => $theiraddr
2021         ));
2022
2023         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2024
2025         return(diaspora_transmit($owner,$contact,$slap, false));
2026 }
2027
2028 function diaspora_unshare($me,$contact) {
2029
2030         $a = get_app();
2031         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2032
2033         $tpl = get_markup_template('diaspora_retract.tpl');
2034         $msg = replace_macros($tpl, array(
2035                 '$guid'   => $me['guid'],
2036                 '$type'   => 'Person',
2037                 '$handle' => $myaddr
2038         ));
2039
2040         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2041
2042         return(diaspora_transmit($owner,$contact,$slap, false));
2043
2044 }
2045
2046
2047
2048 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2049
2050         $a = get_app();
2051         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2052         $theiraddr = $contact['addr'];
2053
2054         $images = array();
2055
2056         $title = $item['title'];
2057         $body = $item['body'];
2058
2059 /*
2060         // We're trying to match Diaspora's split message/photo protocol but
2061         // all the photos are displayed on D* as links and not img's - even
2062         // though we're sending pretty much precisely what they send us when
2063         // doing the same operation.  
2064         // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2065         // which seems to get through intact.
2066
2067         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2068         if($cnt) {
2069                 foreach($matches as $mtch) {
2070                         $detail = array();
2071                         $detail['str'] = $mtch[0];
2072                         $detail['path'] = dirname($mtch[1]) . '/';
2073                         $detail['file'] = basename($mtch[1]);
2074                         $detail['guid'] = $item['guid'];
2075                         $detail['handle'] = $myaddr;
2076                         $images[] = $detail;
2077                         $body = str_replace($detail['str'],$mtch[1],$body);
2078                 }
2079         }       
2080 */
2081         $body = xmlify(html_entity_decode(bb2diaspora($body)));
2082
2083         if(strlen($title))
2084                 $body = xmlify('**' . html_entity_decode($title) . '**' . "\n") . $body;
2085
2086
2087         if($item['attach']) {
2088                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2089                 if(cnt) {
2090                         $body .= "\n" . t('Attachments:') . "\n";
2091                         foreach($matches as $mtch) {
2092                                 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2093                         }
2094                 }
2095         }       
2096
2097
2098         $public = (($item['private']) ? 'false' : 'true');
2099
2100         require_once('include/datetime.php');
2101         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2102
2103         $tpl = get_markup_template('diaspora_post.tpl');
2104         $msg = replace_macros($tpl, array(
2105                 '$body' => $body,
2106                 '$guid' => $item['guid'],
2107                 '$handle' => xmlify($myaddr),
2108                 '$public' => $public,
2109                 '$created' => $created
2110         ));
2111
2112         logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
2113
2114         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2115
2116         $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2117
2118         if(count($images)) {
2119                 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2120         }
2121
2122         return $return_code;
2123 }
2124
2125
2126 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2127         $a = get_app();
2128         if(! count($images))
2129                 return;
2130         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2131
2132         $tpl = get_markup_template('diaspora_photo.tpl');
2133         foreach($images as $image) {
2134                 if(! stristr($image['path'],$mysite))
2135                         continue;
2136                 $resource = str_replace('.jpg','',$image['file']);
2137                 $resource = substr($resource,0,strpos($resource,'-'));
2138
2139                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2140                         dbesc($resource),
2141                         intval($owner['uid'])
2142                 );
2143                 if(! count($r))
2144                         continue;
2145                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2146                 $msg = replace_macros($tpl,array(               
2147                         '$path' => xmlify($image['path']),
2148                         '$filename' => xmlify($image['file']),
2149                         '$msg_guid' => xmlify($image['guid']),
2150                         '$guid' => xmlify($r[0]['guid']),
2151                         '$handle' => xmlify($image['handle']),
2152                         '$public' => xmlify($public),
2153                         '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2154                 ));
2155
2156
2157                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2158                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2159
2160                 diaspora_transmit($owner,$contact,$slap,$public_batch);
2161         }
2162
2163 }
2164
2165 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2166
2167         $a = get_app();
2168         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2169         $theiraddr = $contact['addr'];
2170
2171         // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2172         // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2173         // The only item with `parent` and `id` as the parent id is the parent item.
2174         $p = q("select guid from item where parent = %d and id = %d limit 1",
2175                 intval($item['parent']),
2176                 intval($item['parent'])
2177         );
2178         if(count($p))
2179                 $parent_guid = $p[0]['guid'];
2180         else
2181                 return;
2182
2183         if($item['verb'] === ACTIVITY_LIKE) {
2184                 $tpl = get_markup_template('diaspora_like.tpl');
2185                 $like = true;
2186                 $target_type = 'Post';
2187 //              $positive = (($item['deleted']) ? 'false' : 'true');
2188                 $positive = 'true';
2189
2190                 if(($item['deleted']))
2191                         logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2192         }
2193         else {
2194                 $tpl = get_markup_template('diaspora_comment.tpl');
2195                 $like = false;
2196         }
2197
2198         $text = html_entity_decode(bb2diaspora($item['body']));
2199
2200         // sign it
2201
2202         if($like)
2203                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
2204         else
2205                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
2206
2207         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2208
2209         $msg = replace_macros($tpl,array(
2210                 '$guid' => xmlify($item['guid']),
2211                 '$parent_guid' => xmlify($parent_guid),
2212                 '$target_type' =>xmlify($target_type),
2213                 '$authorsig' => xmlify($authorsig),
2214                 '$body' => xmlify($text),
2215                 '$positive' => xmlify($positive),
2216                 '$handle' => xmlify($myaddr)
2217         ));
2218
2219         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2220
2221         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2222
2223         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2224 }
2225
2226
2227 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2228
2229
2230         $a = get_app();
2231         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2232         $theiraddr = $contact['addr'];
2233
2234
2235         // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2236         // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2237         // The only item with `parent` and `id` as the parent id is the parent item.
2238         $p = q("select guid from item where parent = %d and id = %d limit 1",
2239                 intval($item['parent']),
2240                 intval($item['parent'])
2241         );
2242         if(count($p))
2243                 $parent_guid = $p[0]['guid'];
2244         else
2245                 return;
2246
2247         $like = false;
2248         $relay_retract = false;
2249         $sql_sign_id = 'iid';
2250         if( $item['deleted']) {
2251                 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2252                 $relay_retract = true;
2253                 $sql_sign_id = 'retract_iid';
2254                 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2255         }
2256         elseif($item['verb'] === ACTIVITY_LIKE) {
2257                 $tpl = get_markup_template('diaspora_like_relay.tpl');
2258                 $like = true;
2259                 $target_type = 'Post';
2260 //              $positive = (($item['deleted']) ? 'false' : 'true');
2261                 $positive = 'true';
2262         }
2263         else {
2264                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2265         }
2266
2267         $body = $item['body'];
2268
2269         $text = html_entity_decode(bb2diaspora($body));
2270
2271
2272         // fetch the original signature if the relayable was created by a Diaspora
2273         // or DFRN user. Relayables for other networks are not supported.
2274
2275         $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2276                 intval($item['id'])
2277         );
2278         if(count($r)) { 
2279                 $orig_sign = $r[0];
2280                 $signed_text = $orig_sign['signed_text'];
2281                 $authorsig = $orig_sign['signature'];
2282                 $handle = $orig_sign['signer'];
2283         }
2284         else {
2285
2286                 // Author signature information (for likes, comments, and retractions of likes or comments,
2287                 // whether from Diaspora or Friendica) must be placed in the `sign` table before this 
2288                 // function is called
2289                 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2290                 return;
2291 /*
2292                 $itemcontact = q("select * from contact where `id` = %d limit 1",
2293                         intval($item['contact-id'])
2294                 );
2295                 if(count($itemcontact)) {
2296                         if(! $itemcontact[0]['self']) {
2297                                 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
2298                                         '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',  
2299                                         network_to_name($itemcontact['network'])) . "\n";
2300                                 // "$body" was assigned to "$text" above. It isn't used after that, so I don't think
2301                                 // the following change will do anything
2302                                 $body = $prefix . $body;
2303
2304                                 // I think this comment will fail upon reaching Diaspora, because "$signed_text" is not defined
2305                         }
2306                 }
2307                 else {
2308                 // I'm confused about this "else." Since it sets "$handle = $myaddr," it seems like it should be for the case
2309                 // where the top-level post owner commented on his own post, i.e. "$itemcontact[0]['self']" is true. But it's
2310                 // positioned to be for the case where "count($itemcontact)" is 0.
2311
2312                         $handle = $myaddr;
2313
2314                         if($like)
2315                                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $handle;
2316                         elseif($relay_retract)
2317                                 $signed_text = $item['guid'] . ';' . $target_type;
2318                         else
2319                                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $handle;
2320
2321                         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2322
2323                         q("insert into sign (`" . $sql_sign_id . "`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2324                                 intval($item['id']),
2325                                 dbesc($signed_text),
2326                                 dbesc($authorsig),
2327                                 dbesc($handle)
2328                         );
2329                 }
2330 */
2331         }
2332
2333         // sign it with the top-level owner's signature
2334
2335         $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2336
2337         $msg = replace_macros($tpl,array(
2338                 '$guid' => xmlify($item['guid']),
2339                 '$parent_guid' => xmlify($parent_guid),
2340                 '$target_type' =>xmlify($target_type),
2341                 '$authorsig' => xmlify($authorsig),
2342                 '$parentsig' => xmlify($parentauthorsig),
2343                 '$body' => xmlify($text),
2344                 '$positive' => xmlify($positive),
2345                 '$handle' => xmlify($handle)
2346         ));
2347
2348         logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2349
2350
2351         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2352
2353         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2354
2355 }
2356
2357
2358
2359 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2360
2361         $a = get_app();
2362         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2363
2364         // Check whether the retraction is for a top-level post or whether it's a relayable
2365         if( $item['uri'] !== $item['parent-uri'] ) {
2366
2367                 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2368                 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2369         }
2370         else {
2371                 
2372                 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2373                 $target_type = 'StatusMessage';
2374         }
2375
2376         $signed_text = $item['guid'] . ';' . $target_type;
2377
2378         $msg = replace_macros($tpl, array(
2379                 '$guid'   => xmlify($item['guid']),
2380                 '$type'   => xmlify($target_type),
2381                 '$handle' => xmlify($myaddr),
2382                 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2383         ));
2384
2385         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2386
2387         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2388 }
2389
2390 function diaspora_send_mail($item,$owner,$contact) {
2391
2392         $a = get_app();
2393         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2394
2395         $r = q("select * from conv where id = %d and uid = %d limit 1",
2396                 intval($item['convid']),
2397                 intval($item['uid'])
2398         );
2399
2400         if(! count($r)) {
2401                 logger('diaspora_send_mail: conversation not found.');
2402                 return;
2403         }
2404         $cnv = $r[0];
2405
2406         $conv = array(
2407                 'guid' => xmlify($cnv['guid']),
2408                 'subject' => xmlify($cnv['subject']),
2409                 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2410                 'diaspora_handle' => xmlify($cnv['creator']),
2411                 'participant_handles' => xmlify($cnv['recips'])
2412         );
2413
2414         $body = bb2diaspora($item['body']);
2415         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2416  
2417         $signed_text =  $item['guid'] . ';' . $cnv['guid'] . ';' . $body .  ';' 
2418                 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2419
2420         $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2421
2422         $msg = array(
2423                 'guid' => xmlify($item['guid']),
2424                 'parent_guid' => xmlify($cnv['guid']),
2425                 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2426                 'author_signature' => xmlify($sig),
2427                 'text' => xmlify($body),
2428                 'created_at' => xmlify($created),
2429                 'diaspora_handle' => xmlify($myaddr),
2430                 'conversation_guid' => xmlify($cnv['guid'])
2431         );
2432
2433         if($item['reply']) {
2434                 $tpl = get_markup_template('diaspora_message.tpl');
2435                 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2436         }
2437         else {
2438                 $conv['messages'] = array($msg);
2439                 $tpl = get_markup_template('diaspora_conversation.tpl');
2440                 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2441         }
2442
2443         logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2444
2445         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2446
2447         return(diaspora_transmit($owner,$contact,$slap,false));
2448
2449
2450 }
2451
2452 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
2453
2454         $enabled = intval(get_config('system','diaspora_enabled'));
2455         if(! $enabled) {
2456                 return 200;
2457         }
2458
2459         $a = get_app();
2460         $logid = random_string(4);
2461         $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2462         if(! $dest_url) {
2463                 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2464                 return 0;
2465         } 
2466
2467         logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2468
2469         if(was_recently_delayed($contact['id'])) {
2470                 $return_code = 0;
2471         }
2472         else {
2473                 if(! intval(get_config('system','diaspora_test'))) {
2474                         post_url($dest_url . '/', $slap);
2475                         $return_code = $a->get_curl_code();
2476                 }
2477                 else {
2478                         logger('diaspora_transmit: test_mode');
2479                         return 200;
2480                 }
2481         }
2482         
2483         logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2484
2485         if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2486                 logger('diaspora_transmit: queue message');
2487
2488                 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2489                         intval($contact['id']),
2490                         dbesc(NETWORK_DIASPORA),
2491                         dbesc($slap),
2492                         intval($public_batch)
2493                 );
2494                 if(count($r)) {
2495                         logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2496                 }
2497                 else {
2498                         // queue message for redelivery
2499                         add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2500                 }
2501         }
2502
2503
2504         return(($return_code) ? $return_code : (-1));
2505 }
2506
2507