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