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