]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
add uid variable to b8 classes
[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                 $u = q("select * from user where id = %d limit 1",intval($importer['uid']));
615                 if($u)
616                         $ret = diaspora_share($u[0],$contact_record);
617         }
618
619         return;
620 }
621
622 function diaspora_post($importer,$xml) {
623
624         $a = get_app();
625         $guid = notags(unxmlify($xml->guid));
626         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
627
628         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
629         if(! $contact)
630                 return;
631
632         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
633                 logger('diaspora_post: Ignoring this author.');
634                 return 202;
635         }
636
637         $message_id = $diaspora_handle . ':' . $guid;
638         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
639                 intval($importer['uid']),
640                 dbesc($message_id),
641                 dbesc($guid)
642         );
643         if(count($r)) {
644                 logger('diaspora_post: message exists: ' . $guid);
645                 return;
646         }
647
648     // allocate a guid on our system - we aren't fixing any collisions.
649         // we're ignoring them
650
651         $g = q("select * from guid where guid = '%s' limit 1",
652                 dbesc($guid)
653         );
654         if(! count($g)) {
655                 q("insert into guid ( guid ) values ( '%s' )",
656                         dbesc($guid)
657                 );
658         }
659
660         $created = unxmlify($xml->created_at);
661         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
662
663         $body = diaspora2bb($xml->raw_message);
664
665         $datarray = array();
666
667         $str_tags = '';
668
669         $tags = get_tags($body);
670
671         if(count($tags)) {
672                 foreach($tags as $tag) {
673                         if(strpos($tag,'#') === 0) {
674                                 if(strpos($tag,'[url='))
675                                         continue;
676                                 $basetag = str_replace('_',' ',substr($tag,1));
677                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
678                                 if(strlen($str_tags))
679                                         $str_tags .= ',';
680                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
681                                 continue;
682                         }
683                 }
684         }
685
686         $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
687         if($cnt) {
688                 foreach($matches as $mtch) {
689                         if(strlen($str_tags))
690                                 $str_tags .= ',';
691                         $str_tags .= '@[url=' . $mtch[1] . '[/url]';    
692                 }
693         }
694
695         $datarray['uid'] = $importer['uid'];
696         $datarray['contact-id'] = $contact['id'];
697         $datarray['wall'] = 0;
698         $datarray['guid'] = $guid;
699         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
700         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
701         $datarray['private'] = $private;
702         $datarray['parent'] = 0;
703         $datarray['owner-name'] = $contact['name'];
704         $datarray['owner-link'] = $contact['url'];
705         $datarray['owner-avatar'] = $contact['thumb'];
706         $datarray['author-name'] = $contact['name'];
707         $datarray['author-link'] = $contact['url'];
708         $datarray['author-avatar'] = $contact['thumb'];
709         $datarray['body'] = $body;
710         $datarray['tag'] = $str_tags;
711         $datarray['app']  = 'Diaspora';
712
713         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
714
715         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
716
717         $message_id = item_store($datarray);
718
719         if($message_id) {
720                 q("update item set plink = '%s' where id = %d limit 1",
721                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
722                         intval($message_id)
723                 );
724         }
725
726         return;
727
728 }
729
730 function diaspora_reshare($importer,$xml) {
731
732         logger('diaspora_reshare: init: ' . print_r($xml,true));
733
734         $a = get_app();
735         $guid = notags(unxmlify($xml->guid));
736         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
737
738
739         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
740         if(! $contact)
741                 return;
742
743         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
744                 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
745                 return 202;
746         }
747
748         $message_id = $diaspora_handle . ':' . $guid;
749         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
750                 intval($importer['uid']),
751                 dbesc($message_id),
752                 dbesc($guid)
753         );
754         if(count($r)) {
755                 logger('diaspora_reshare: message exists: ' . $guid);
756                 return;
757         }
758
759         $orig_author = notags(unxmlify($xml->root_diaspora_id));
760         $orig_guid = notags(unxmlify($xml->root_guid));
761
762         $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
763         $x = fetch_url($source_url);
764         if(! $x)
765                 $x = fetch_url(str_replace('https://','http://',$source_url));
766         if(! $x) {
767                 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
768                 return;
769         }
770         logger('diaspora_reshare: source: ' . $x);
771
772         $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
773         $source_xml = parse_xml_string($x,false);
774
775         if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
776                 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
777                 $body = scale_diaspora_images($body,false);
778         }
779         elseif($source_xml->post->asphoto->image_url) {
780                 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
781                 $body = scale_diaspora_images($body);
782         }
783         elseif($source_xml->post->status_message) {
784                 $body = diaspora2bb($source_xml->post->status_message->raw_message);
785                 $body = scale_diaspora_images($body);
786
787         }
788         else {
789                 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
790                 return;
791         }
792         if(! $body) {
793                 logger('diaspora_reshare: empty body: source= ' . $x);
794                 return;
795         }
796
797         $person = find_diaspora_person_by_handle($orig_author);
798
799         if(is_array($person) && x($person,'name') && x($person,'url'))
800                 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
801         else
802                 $details = $orig_author;
803         
804         $prefix = '&#x2672; ' . $details . "\n"; 
805
806
807     // allocate a guid on our system - we aren't fixing any collisions.
808         // we're ignoring them
809
810         $g = q("select * from guid where guid = '%s' limit 1",
811                 dbesc($guid)
812         );
813         if(! count($g)) {
814                 q("insert into guid ( guid ) values ( '%s' )",
815                         dbesc($guid)
816                 );
817         }
818
819         $created = unxmlify($xml->created_at);
820         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
821
822         $datarray = array();
823
824         $str_tags = '';
825
826         $tags = get_tags($body);
827
828         if(count($tags)) {
829                 foreach($tags as $tag) {
830                         if(strpos($tag,'#') === 0) {
831                                 if(strpos($tag,'[url='))
832                                         continue;
833                                 $basetag = str_replace('_',' ',substr($tag,1));
834                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
835                                 if(strlen($str_tags))
836                                         $str_tags .= ',';
837                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
838                                 continue;
839                         }
840                 }
841         }
842         
843         $datarray['uid'] = $importer['uid'];
844         $datarray['contact-id'] = $contact['id'];
845         $datarray['wall'] = 0;
846         $datarray['guid'] = $guid;
847         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
848         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
849         $datarray['private'] = $private;
850         $datarray['parent'] = 0;
851         $datarray['owner-name'] = $contact['name'];
852         $datarray['owner-link'] = $contact['url'];
853         $datarray['owner-avatar'] = $contact['thumb'];
854         $datarray['author-name'] = $contact['name'];
855         $datarray['author-link'] = $contact['url'];
856         $datarray['author-avatar'] = $contact['thumb'];
857         $datarray['body'] = $prefix . $body;
858         $datarray['tag'] = $str_tags;
859         $datarray['app']  = 'Diaspora';
860
861         $message_id = item_store($datarray);
862
863         if($message_id) {
864                 q("update item set plink = '%s' where id = %d limit 1",
865                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
866                         intval($message_id)
867                 );
868         }
869
870         return;
871
872 }
873
874
875 function diaspora_asphoto($importer,$xml) {
876         logger('diaspora_asphoto called');
877
878         $a = get_app();
879         $guid = notags(unxmlify($xml->guid));
880         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
881
882         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
883         if(! $contact)
884                 return;
885
886         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
887                 logger('diaspora_asphoto: Ignoring this author.');
888                 return 202;
889         }
890
891         $message_id = $diaspora_handle . ':' . $guid;
892         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
893                 intval($importer['uid']),
894                 dbesc($message_id),
895                 dbesc($guid)
896         );
897         if(count($r)) {
898                 logger('diaspora_asphoto: message exists: ' . $guid);
899                 return;
900         }
901
902     // allocate a guid on our system - we aren't fixing any collisions.
903         // we're ignoring them
904
905         $g = q("select * from guid where guid = '%s' limit 1",
906                 dbesc($guid)
907         );
908         if(! count($g)) {
909                 q("insert into guid ( guid ) values ( '%s' )",
910                         dbesc($guid)
911                 );
912         }
913
914         $created = unxmlify($xml->created_at);
915         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
916
917         if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
918                 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
919                 $body = scale_diaspora_images($body,false);
920         }
921         elseif($xml->image_url) {
922                 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
923                 $body = scale_diaspora_images($body);
924         }
925         else {
926                 logger('diaspora_asphoto: no photo url found.');
927                 return;
928         }
929
930         $datarray = array();
931
932         
933         $datarray['uid'] = $importer['uid'];
934         $datarray['contact-id'] = $contact['id'];
935         $datarray['wall'] = 0;
936         $datarray['guid'] = $guid;
937         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
938         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
939         $datarray['private'] = $private;
940         $datarray['parent'] = 0;
941         $datarray['owner-name'] = $contact['name'];
942         $datarray['owner-link'] = $contact['url'];
943         $datarray['owner-avatar'] = $contact['thumb'];
944         $datarray['author-name'] = $contact['name'];
945         $datarray['author-link'] = $contact['url'];
946         $datarray['author-avatar'] = $contact['thumb'];
947         $datarray['body'] = $body;
948         
949         $datarray['app']  = 'Diaspora/Cubbi.es';
950
951         $message_id = item_store($datarray);
952
953         if($message_id) {
954                 q("update item set plink = '%s' where id = %d limit 1",
955                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
956                         intval($message_id)
957                 );
958         }
959
960         return;
961
962 }
963
964
965
966
967
968
969 function diaspora_comment($importer,$xml,$msg) {
970
971         $a = get_app();
972         $guid = notags(unxmlify($xml->guid));
973         $parent_guid = notags(unxmlify($xml->parent_guid));
974         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
975         $target_type = notags(unxmlify($xml->target_type));
976         $text = unxmlify($xml->text);
977         $author_signature = notags(unxmlify($xml->author_signature));
978
979         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
980
981         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
982         if(! $contact) {
983                 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
984                 return;
985         }
986
987         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
988                 logger('diaspora_comment: Ignoring this author.');
989                 return 202;
990         }
991
992         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
993                 intval($importer['uid']),
994                 dbesc($guid)
995         );
996         if(count($r)) {
997                 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
998                 return;
999         }
1000
1001         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1002                 intval($importer['uid']),
1003                 dbesc($parent_guid)
1004         );
1005         if(! count($r)) {
1006                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1007                 return;
1008         }
1009         $parent_item = $r[0];
1010
1011         $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1012
1013         $author_signature = base64_decode($author_signature);
1014
1015         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1016                 $person = $contact;
1017                 $key = $msg['key'];
1018         }
1019         else {
1020                 $person = find_diaspora_person_by_handle($diaspora_handle);     
1021
1022                 if(is_array($person) && x($person,'pubkey'))
1023                         $key = $person['pubkey'];
1024                 else {
1025                         logger('diaspora_comment: unable to find author details');
1026                         return;
1027                 }
1028         }
1029
1030         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1031                 logger('diaspora_comment: verification failed.');
1032                 return;
1033         }
1034
1035         if($parent_author_signature) {
1036                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1037
1038                 $parent_author_signature = base64_decode($parent_author_signature);
1039
1040                 $key = $msg['key'];
1041
1042                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1043                         logger('diaspora_comment: owner verification failed.');
1044                         return;
1045                 }
1046         }
1047
1048         // Phew! Everything checks out. Now create an item.
1049
1050         $body = diaspora2bb($text);
1051
1052         $message_id = $diaspora_handle . ':' . $guid;
1053
1054         $datarray = array();
1055
1056         $str_tags = '';
1057
1058         $tags = get_tags($body);
1059
1060         if(count($tags)) {
1061                 foreach($tags as $tag) {
1062                         if(strpos($tag,'#') === 0) {
1063                                 if(strpos($tag,'[url='))
1064                                         continue;
1065                                 $basetag = str_replace('_',' ',substr($tag,1));
1066                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1067                                 if(strlen($str_tags))
1068                                         $str_tags .= ',';
1069                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1070                                 continue;
1071                         }
1072                 }
1073         }
1074
1075         $datarray['uid'] = $importer['uid'];
1076         $datarray['contact-id'] = $contact['id'];
1077         $datarray['wall'] = $parent_item['wall'];
1078         $datarray['gravity'] = GRAVITY_COMMENT;
1079         $datarray['guid'] = $guid;
1080         $datarray['uri'] = $message_id;
1081         $datarray['parent-uri'] = $parent_item['uri'];
1082
1083         // No timestamps for comments? OK, we'll the use current time.
1084         $datarray['created'] = $datarray['edited'] = datetime_convert();
1085         $datarray['private'] = $parent_item['private'];
1086
1087         $datarray['owner-name'] = $parent_item['owner-name'];
1088         $datarray['owner-link'] = $parent_item['owner-link'];
1089         $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1090
1091         $datarray['author-name'] = $person['name'];
1092         $datarray['author-link'] = $person['url'];
1093         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1094         $datarray['body'] = $body;
1095         $datarray['tag'] = $str_tags;
1096
1097         // We can't be certain what the original app is if the message is relayed.
1098         if(($parent_item['origin']) && (! $parent_author_signature)) 
1099                 $datarray['app']  = 'Diaspora';
1100
1101         $message_id = item_store($datarray);
1102
1103         if($message_id) {
1104                 q("update item set plink = '%s' where id = %d limit 1",
1105                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1106                         intval($message_id)
1107                 );
1108         }
1109
1110         if(($parent_item['origin']) && (! $parent_author_signature)) {
1111                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1112                         intval($message_id),
1113                         dbesc($author_signed_data),
1114                         dbesc(base64_encode($author_signature)),
1115                         dbesc($diaspora_handle)
1116                 );
1117
1118                 // if the message isn't already being relayed, notify others
1119                 // the existence of parent_author_signature means the parent_author or owner
1120                 // is already relaying.
1121
1122                 proc_run('php','include/notifier.php','comment',$message_id);
1123         }
1124         return;
1125 }
1126
1127
1128
1129
1130 function diaspora_conversation($importer,$xml,$msg) {
1131
1132         $a = get_app();
1133
1134         $guid = notags(unxmlify($xml->guid));
1135         $subject = notags(unxmlify($xml->subject));
1136         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1137         $participant_handles = notags(unxmlify($xml->participant_handles));
1138         $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1139
1140         $parent_uri = $diaspora_handle . ':' . $guid;
1141  
1142         $messages = $xml->message;
1143
1144         if(! count($messages)) {
1145                 logger('diaspora_conversation: empty conversation');
1146                 return;
1147         }
1148
1149         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1150         if(! $contact) {
1151                 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1152                 return;
1153         }
1154
1155         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1156                 logger('diaspora_conversation: Ignoring this author.');
1157                 return 202;
1158         }
1159
1160         $conversation = null;
1161
1162         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1163                 intval($importer['uid']),
1164                 dbesc($guid)
1165         );
1166         if(count($c))
1167                 $conversation = $c[0];
1168         else {
1169                 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1170                         intval($importer['uid']),
1171                         dbesc($guid),
1172                         dbesc($diaspora_handle),
1173                         dbesc(datetime_convert('UTC','UTC',$created_at)),
1174                         dbesc(datetime_convert()),
1175                         dbesc($subject),
1176                         dbesc($participant_handles)
1177                 );
1178                 if($r)
1179                         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1180                 intval($importer['uid']),
1181             dbesc($guid)
1182         );
1183             if(count($c))
1184             $conversation = $c[0];
1185         }
1186         if(! $conversation) {
1187                 logger('diaspora_conversation: unable to create conversation.');
1188                 return;
1189         }
1190
1191         foreach($messages as $mesg) {
1192
1193                 $reply = 0;
1194
1195                 $msg_guid = notags(unxmlify($mesg->guid));
1196                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1197                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1198                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1199                 $msg_text = unxmlify($mesg->text);
1200                 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1201                 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1202                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1203                 if($msg_conversation_guid != $guid) {
1204                         logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1205                         continue;
1206                 }
1207
1208                 $body = diaspora2bb($msg_text);
1209                 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1210
1211                 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1212
1213                 $author_signature = base64_decode($msg_author_signature);
1214
1215                 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1216                         $person = $contact;
1217                         $key = $msg['key'];
1218                 }
1219                 else {
1220                         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1221
1222                         if(is_array($person) && x($person,'pubkey'))
1223                                 $key = $person['pubkey'];
1224                         else {
1225                                 logger('diaspora_conversation: unable to find author details');
1226                                 continue;
1227                         }
1228                 }
1229
1230                 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1231                         logger('diaspora_conversation: verification failed.');
1232                         continue;
1233                 }
1234
1235                 if($msg_parent_author_signature) {
1236                         $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1237
1238                         $parent_author_signature = base64_decode($msg_parent_author_signature);
1239
1240                         $key = $msg['key'];
1241
1242                         if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1243                                 logger('diaspora_conversation: owner verification failed.');
1244                                 continue;
1245                         }
1246                 }
1247
1248                 $r = q("select id from mail where `uri` = '%s' limit 1",
1249                         dbesc($message_id)
1250                 );
1251                 if(count($r)) {
1252                         logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1253                         continue;
1254                 }
1255
1256                 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')",
1257                         intval($importer['uid']),
1258                         dbesc($msg_guid),
1259                         intval($conversation['id']),
1260                         dbesc($person['name']),
1261                         dbesc($person['photo']),
1262                         dbesc($person['url']),
1263                         intval($contact['id']),  
1264                         dbesc($subject),
1265                         dbesc($body),
1266                         0,
1267                         0,
1268                         dbesc($message_id),
1269                         dbesc($parent_uri),
1270                         dbesc($msg_created_at)
1271                 );                      
1272
1273                 q("update conv set updated = '%s' where id = %d limit 1",
1274                         dbesc(datetime_convert()),
1275                         intval($conversation['id'])
1276                 );              
1277
1278                 require_once('include/enotify.php');
1279                 notification(array(                     
1280                         'type' => NOTIFY_MAIL,
1281                         'notify_flags' => $importer['notify-flags'],
1282                         'language' => $importer['language'],
1283                         'to_name' => $importer['username'],
1284                         'to_email' => $importer['email'],
1285                         'item' => array('subject' => $subject, 'body' => $body),
1286                         'source_name' => $person['name'],
1287                         'source_link' => $person['url'],
1288                         'source_photo' => $person['thumb'],
1289                         'verb' => ACTIVITY_POST,
1290                         'otype' => 'mail'
1291                 ));
1292         }       
1293
1294         return;
1295 }
1296
1297 function diaspora_message($importer,$xml,$msg) {
1298
1299         $a = get_app();
1300
1301         $msg_guid = notags(unxmlify($xml->guid));
1302         $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1303         $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1304         $msg_author_signature = notags(unxmlify($xml->author_signature));
1305         $msg_text = unxmlify($xml->text);
1306         $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1307         $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1308         $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1309
1310         $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1311  
1312         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1313         if(! $contact) {
1314                 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1315                 return;
1316         }
1317
1318         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1319                 logger('diaspora_message: Ignoring this author.');
1320                 return 202;
1321         }
1322
1323         $conversation = null;
1324
1325         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1326                 intval($importer['uid']),
1327                 dbesc($msg_conversation_guid)
1328         );
1329         if(count($c))
1330                 $conversation = $c[0];
1331         else {
1332                 logger('diaspora_message: conversation not available.');
1333                 return;
1334         }
1335
1336         $reply = 0;
1337                         
1338         $body = diaspora2bb($msg_text);
1339         $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1340
1341         $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1342
1343
1344         $author_signature = base64_decode($msg_author_signature);
1345
1346         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1347         if(is_array($person) && x($person,'pubkey'))
1348                 $key = $person['pubkey'];
1349         else {
1350                 logger('diaspora_message: unable to find author details');
1351                 return;
1352         }
1353
1354         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1355                 logger('diaspora_message: verification failed.');
1356                 return;
1357         }
1358
1359         $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1360                 dbesc($message_id),
1361                 intval($importer['uid'])
1362         );
1363         if(count($r)) {
1364                 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1365                 return;
1366         }
1367
1368         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')",
1369                 intval($importer['uid']),
1370                 dbesc($msg_guid),
1371                 intval($conversation['id']),
1372                 dbesc($person['name']),
1373                 dbesc($person['photo']),
1374                 dbesc($person['url']),
1375                 intval($contact['id']),  
1376                 dbesc($conversation['subject']),
1377                 dbesc($body),
1378                 0,
1379                 1,
1380                 dbesc($message_id),
1381                 dbesc($parent_uri),
1382                 dbesc($msg_created_at)
1383         );                      
1384
1385         q("update conv set updated = '%s' where id = %d limit 1",
1386                 dbesc(datetime_convert()),
1387                 intval($conversation['id'])
1388         );              
1389         
1390         return;
1391 }
1392
1393
1394 function diaspora_photo($importer,$xml,$msg) {
1395
1396         $a = get_app();
1397
1398         logger('diaspora_photo: init',LOGGER_DEBUG);
1399
1400         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1401
1402         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1403
1404         $status_message_guid = notags(unxmlify($xml->status_message_guid));
1405
1406         $guid = notags(unxmlify($xml->guid));
1407
1408         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1409
1410         $public = notags(unxmlify($xml->public));
1411
1412         $created_at = notags(unxmlify($xml_created_at));
1413
1414         logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1415
1416         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1417         if(! $contact) {
1418                 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1419                 return;
1420         }
1421
1422         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1423                 logger('diaspora_photo: Ignoring this author.');
1424                 return 202;
1425         }
1426
1427         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1428                 intval($importer['uid']),
1429                 dbesc($status_message_guid)
1430         );
1431         if(! count($r)) {
1432                 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1433                 return;
1434         }
1435
1436         $parent_item = $r[0];
1437
1438         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1439
1440         $link_text = scale_diaspora_images($link_text);
1441
1442         if(strpos($parent_item['body'],$link_text) === false) {
1443                 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1444                         dbesc($link_text . $parent_item['body']),
1445                         intval($parent_item['id']),
1446                         intval($parent_item['uid'])
1447                 );
1448         }
1449
1450         return;
1451 }
1452
1453
1454
1455
1456 function diaspora_like($importer,$xml,$msg) {
1457
1458         $a = get_app();
1459         $guid = notags(unxmlify($xml->guid));
1460         $parent_guid = notags(unxmlify($xml->parent_guid));
1461         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1462         $target_type = notags(unxmlify($xml->target_type));
1463         $positive = notags(unxmlify($xml->positive));
1464         $author_signature = notags(unxmlify($xml->author_signature));
1465
1466         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1467
1468         // likes on comments not supported here and likes on photos not supported by Diaspora
1469
1470         if($target_type !== 'Post')
1471                 return;
1472
1473         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1474         if(! $contact) {
1475                 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1476                 return;
1477         }
1478
1479         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1480                 logger('diaspora_like: Ignoring this author.');
1481                 return 202;
1482         }
1483
1484         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1485                 intval($importer['uid']),
1486                 dbesc($parent_guid)
1487         );
1488         if(! count($r)) {
1489                 logger('diaspora_like: parent item not found: ' . $guid);
1490                 return;
1491         }
1492
1493         $parent_item = $r[0];
1494
1495         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1496                 intval($importer['uid']),
1497                 dbesc($guid)
1498         );
1499         if(count($r)) {
1500                 if($positive === 'true') {
1501                         logger('diaspora_like: duplicate like: ' . $guid);
1502                         return;
1503                 } 
1504                 if($positive === 'false') {
1505                         q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1506                                 intval($r[0]['id']),
1507                                 intval($importer['uid'])
1508                         );
1509                         // FIXME
1510                         //  send notification via proc_run()
1511                         return;
1512                 }
1513         }
1514         if($positive === 'false') {
1515                 logger('diaspora_like: unlike received with no corresponding like');
1516                 return; 
1517         }
1518
1519         $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1520
1521         $author_signature = base64_decode($author_signature);
1522
1523         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1524                 $person = $contact;
1525                 $key = $msg['key'];
1526         }
1527         else {
1528                 $person = find_diaspora_person_by_handle($diaspora_handle);     
1529                 if(is_array($person) && x($person,'pubkey'))
1530                         $key = $person['pubkey'];
1531                 else {
1532                         logger('diaspora_like: unable to find author details');
1533                         return;
1534                 }
1535         }
1536
1537         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1538                 logger('diaspora_like: verification failed.');
1539                 return;
1540         }
1541
1542         if($parent_author_signature) {
1543
1544                 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1545
1546                 $parent_author_signature = base64_decode($parent_author_signature);
1547
1548                 $key = $msg['key'];
1549
1550                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1551                         logger('diaspora_like: owner verification failed.');
1552                         return;
1553                 }
1554         }
1555
1556         // Phew! Everything checks out. Now create an item.
1557
1558         $uri = $diaspora_handle . ':' . $guid;
1559
1560         $activity = ACTIVITY_LIKE;
1561         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1562         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
1563         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1564         $body = $parent_item['body'];
1565
1566         $obj = <<< EOT
1567
1568         <object>
1569                 <type>$objtype</type>
1570                 <local>1</local>
1571                 <id>{$parent_item['uri']}</id>
1572                 <link>$link</link>
1573                 <title></title>
1574                 <content>$body</content>
1575         </object>
1576 EOT;
1577         $bodyverb = t('%1$s likes %2$s\'s %3$s');
1578
1579         $arr = array();
1580
1581         $arr['uri'] = $uri;
1582         $arr['uid'] = $importer['uid'];
1583         $arr['guid'] = $guid;
1584         $arr['contact-id'] = $contact['id'];
1585         $arr['type'] = 'activity';
1586         $arr['wall'] = $parent_item['wall'];
1587         $arr['gravity'] = GRAVITY_LIKE;
1588         $arr['parent'] = $parent_item['id'];
1589         $arr['parent-uri'] = $parent_item['uri'];
1590
1591         $arr['owner-name'] = $parent_item['name'];
1592         $arr['owner-link'] = $parent_item['url'];
1593         $arr['owner-avatar'] = $parent_item['thumb'];
1594
1595         $arr['author-name'] = $person['name'];
1596         $arr['author-link'] = $person['url'];
1597         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1598         
1599         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1600         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1601         $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1602         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
1603
1604         $arr['app']  = 'Diaspora';
1605
1606         $arr['private'] = $parent_item['private'];
1607         $arr['verb'] = $activity;
1608         $arr['object-type'] = $objtype;
1609         $arr['object'] = $obj;
1610         $arr['visible'] = 1;
1611         $arr['unseen'] = 1;
1612         $arr['last-child'] = 0;
1613
1614         $message_id = item_store($arr);
1615
1616
1617         if($message_id) {
1618                 q("update item set plink = '%s' where id = %d limit 1",
1619                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1620                         intval($message_id)
1621                 );
1622         }
1623
1624         if(! $parent_author_signature) {
1625                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1626                         intval($message_id),
1627                         dbesc($author_signed_data),
1628                         dbesc(base64_encode($author_signature)),
1629                         dbesc($diaspora_handle)
1630                 );
1631         }
1632
1633         // if the message isn't already being relayed, notify others
1634         // the existence of parent_author_signature means the parent_author or owner
1635         // is already relaying. The parent_item['origin'] indicates the message was created on our system
1636
1637         if(($parent_item['origin']) && (! $parent_author_signature))
1638                 proc_run('php','include/notifier.php','comment',$message_id);
1639
1640         return;
1641 }
1642
1643 function diaspora_retraction($importer,$xml) {
1644
1645
1646         $guid = notags(unxmlify($xml->guid));
1647         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1648         $type = notags(unxmlify($xml->type));
1649
1650         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1651         if(! $contact)
1652                 return;
1653
1654         if($type === 'Person') {
1655                 require_once('include/Contact.php');
1656                 contact_remove($contact['id']);
1657         }
1658         elseif($type === 'Post') {
1659                 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1660                         dbesc('guid'),
1661                         intval($importer['uid'])
1662                 );
1663                 if(count($r)) {
1664                         if(link_compare($r[0]['author-link'],$contact['url'])) {
1665                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1666                                         dbesc(datetime_convert()),                      
1667                                         intval($r[0]['id'])
1668                                 );
1669                         }
1670                 }
1671         }
1672
1673         return 202;
1674         // NOTREACHED
1675 }
1676
1677 function diaspora_signed_retraction($importer,$xml,$msg) {
1678
1679
1680         $guid = notags(unxmlify($xml->target_guid));
1681         $diaspora_handle = notags(unxmlify($xml->sender_handle));
1682         $type = notags(unxmlify($xml->target_type));
1683         $sig = notags(unxmlify($xml->target_author_signature));
1684
1685         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1686         if(! $contact) {
1687                 logger('diaspora_signed_retraction: no contact');
1688                 return;
1689         }
1690
1691         // this may not yet work for comments. Need to see how the relaying works
1692         // and figure out who signs it.
1693
1694
1695         $signed_data = $guid . ';' . $type ;
1696
1697         $sig = base64_decode($sig);
1698
1699         $key = $msg['key'];
1700
1701         if(! rsa_verify($signed_data,$sig,$key,'sha256')) {
1702                 logger('diaspora_signed_retraction: owner verification failed.' . print_r($msg,true));
1703                 return;
1704         }
1705
1706         if($type === 'StatusMessage') {
1707                 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1708                         dbesc($guid),
1709                         intval($importer['uid'])
1710                 );
1711                 if(count($r)) {
1712                         if(link_compare($r[0]['author-link'],$contact['url'])) {
1713                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1714                                         dbesc(datetime_convert()),                      
1715                                         intval($r[0]['id'])
1716                                 );
1717                         }
1718                 }
1719         }
1720         else
1721                 logger('diaspora_signed_retraction: unknown type: ' . $type);
1722
1723         return 202;
1724         // NOTREACHED
1725 }
1726
1727 function diaspora_profile($importer,$xml) {
1728
1729         $a = get_app();
1730         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1731
1732         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1733         if(! $contact)
1734                 return;
1735
1736         if($contact['blocked']) {
1737                 logger('diaspora_post: Ignoring this author.');
1738                 return 202;
1739         }
1740
1741         $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1742         $image_url = unxmlify($xml->image_url);
1743         $birthday = unxmlify($xml->birthday);
1744
1745         $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE  `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1746                 intval($importer['uid']),
1747                 intval($contact['id'])
1748         );
1749         $oldphotos = ((count($r)) ? $r : null);
1750
1751         require_once('include/Photo.php');
1752
1753         $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1754         
1755         // Generic birthday. We don't know the timezone. The year is irrelevant. 
1756
1757         $birthday = str_replace('1000','1901',$birthday);
1758
1759         $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1760
1761         // this is to prevent multiple birthday notifications in a single year
1762         // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1763
1764         if(substr($birthday,5) === substr($contact['bd'],5))
1765                 $birthday = $contact['bd'];
1766
1767         $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",
1768                 dbesc($name),
1769                 dbesc(datetime_convert()),
1770                 dbesc($images[0]),
1771                 dbesc($images[1]),
1772                 dbesc($images[2]),
1773                 dbesc(datetime_convert()),
1774                 dbesc($birthday),
1775                 intval($contact['id']),
1776                 intval($importer['uid'])
1777         ); 
1778
1779         if($r) {
1780                 if($oldphotos) {
1781                         foreach($oldphotos as $ph) {
1782                                 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1783                                         intval($importer['uid']),
1784                                         intval($contact['id']),
1785                                         dbesc($ph['resource-id'])
1786                                 );
1787                         }
1788                 }
1789         }       
1790
1791         return;
1792
1793 }
1794
1795 function diaspora_share($me,$contact) {
1796         $a = get_app();
1797         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1798         $theiraddr = $contact['addr'];
1799
1800         $tpl = get_markup_template('diaspora_share.tpl');
1801         $msg = replace_macros($tpl, array(
1802                 '$sender' => $myaddr,
1803                 '$recipient' => $theiraddr
1804         ));
1805
1806         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1807
1808         return(diaspora_transmit($owner,$contact,$slap, false));
1809 }
1810
1811 function diaspora_unshare($me,$contact) {
1812
1813         $a = get_app();
1814         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1815
1816         $tpl = get_markup_template('diaspora_retract.tpl');
1817         $msg = replace_macros($tpl, array(
1818                 '$guid'   => $me['guid'],
1819                 '$type'   => 'Person',
1820                 '$handle' => $myaddr
1821         ));
1822
1823         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1824
1825         return(diaspora_transmit($owner,$contact,$slap, false));
1826
1827 }
1828
1829
1830
1831 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1832
1833         $a = get_app();
1834         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1835         $theiraddr = $contact['addr'];
1836
1837         $images = array();
1838
1839         $body = $item['body'];
1840
1841 /*
1842         // We're trying to match Diaspora's split message/photo protocol but
1843         // all the photos are displayed on D* as links and not img's - even
1844         // though we're sending pretty much precisely what they send us when
1845         // doing the same operation.  
1846         // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1847         // which seems to get through intact.
1848
1849         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1850         if($cnt) {
1851                 foreach($matches as $mtch) {
1852                         $detail = array();
1853                         $detail['str'] = $mtch[0];
1854                         $detail['path'] = dirname($mtch[1]) . '/';
1855                         $detail['file'] = basename($mtch[1]);
1856                         $detail['guid'] = $item['guid'];
1857                         $detail['handle'] = $myaddr;
1858                         $images[] = $detail;
1859                         $body = str_replace($detail['str'],$mtch[1],$body);
1860                 }
1861         }       
1862 */
1863
1864         $body = xmlify(html_entity_decode(bb2diaspora($body)));
1865
1866         if($item['attach']) {
1867                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1868                 if(cnt) {
1869                         $body .= "\n" . t('Attachments:') . "\n";
1870                         foreach($matches as $mtch) {
1871                                 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1872                         }
1873                 }
1874         }       
1875
1876
1877         $public = (($item['private']) ? 'false' : 'true');
1878
1879         require_once('include/datetime.php');
1880         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1881
1882         $tpl = get_markup_template('diaspora_post.tpl');
1883         $msg = replace_macros($tpl, array(
1884                 '$body' => $body,
1885                 '$guid' => $item['guid'],
1886                 '$handle' => xmlify($myaddr),
1887                 '$public' => $public,
1888                 '$created' => $created
1889         ));
1890
1891         logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1892
1893         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1894
1895         $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1896
1897         if(count($images)) {
1898                 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1899         }
1900
1901         return $return_code;
1902 }
1903
1904
1905 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1906         $a = get_app();
1907         if(! count($images))
1908                 return;
1909         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1910
1911         $tpl = get_markup_template('diaspora_photo.tpl');
1912         foreach($images as $image) {
1913                 if(! stristr($image['path'],$mysite))
1914                         continue;
1915                 $resource = str_replace('.jpg','',$image['file']);
1916                 $resource = substr($resource,0,strpos($resource,'-'));
1917
1918                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1919                         dbesc($resource),
1920                         intval($owner['uid'])
1921                 );
1922                 if(! count($r))
1923                         continue;
1924                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1925                 $msg = replace_macros($tpl,array(               
1926                         '$path' => xmlify($image['path']),
1927                         '$filename' => xmlify($image['file']),
1928                         '$msg_guid' => xmlify($image['guid']),
1929                         '$guid' => xmlify($r[0]['guid']),
1930                         '$handle' => xmlify($image['handle']),
1931                         '$public' => xmlify($public),
1932                         '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1933                 ));
1934
1935
1936                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1937                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1938
1939                 diaspora_transmit($owner,$contact,$slap,$public_batch);
1940         }
1941
1942 }
1943
1944 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1945
1946         $a = get_app();
1947         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1948         $theiraddr = $contact['addr'];
1949
1950         $p = q("select guid from item where parent = %d limit 1",
1951                 $item['parent']
1952         );
1953         if(count($p))
1954                 $parent_guid = $p[0]['guid'];
1955         else
1956                 return;
1957
1958         if($item['verb'] === ACTIVITY_LIKE) {
1959                 $tpl = get_markup_template('diaspora_like.tpl');
1960                 $like = true;
1961                 $target_type = 'Post';
1962                 $positive = (($item['deleted']) ? 'false' : 'true');
1963         }
1964         else {
1965                 $tpl = get_markup_template('diaspora_comment.tpl');
1966                 $like = false;
1967         }
1968
1969         $text = html_entity_decode(bb2diaspora($item['body']));
1970
1971         // sign it
1972
1973         if($like)
1974                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1975         else
1976                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1977
1978         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1979
1980         $msg = replace_macros($tpl,array(
1981                 '$guid' => xmlify($item['guid']),
1982                 '$parent_guid' => xmlify($parent_guid),
1983                 '$target_type' =>xmlify($target_type),
1984                 '$authorsig' => xmlify($authorsig),
1985                 '$body' => xmlify($text),
1986                 '$positive' => xmlify($positive),
1987                 '$handle' => xmlify($myaddr)
1988         ));
1989
1990         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1991
1992         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1993
1994         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1995 }
1996
1997
1998 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1999
2000
2001         $a = get_app();
2002         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2003         $theiraddr = $contact['addr'];
2004
2005
2006         $p = q("select guid from item where parent = %d limit 1",
2007                 $item['parent']
2008         );
2009         if(count($p))
2010                 $parent_guid = $p[0]['guid'];
2011         else
2012                 return;
2013
2014         if($item['verb'] === ACTIVITY_LIKE) {
2015                 $tpl = get_markup_template('diaspora_like_relay.tpl');
2016                 $like = true;
2017                 $target_type = 'Post';
2018                 $positive = (($item['deleted']) ? 'false' : 'true');
2019         }
2020         else {
2021                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2022                 $like = false;
2023         }
2024
2025         $body = $item['body'];
2026
2027         $text = html_entity_decode(bb2diaspora($body));
2028
2029         // fetch the original signature if somebody sent the post to us to relay
2030         // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
2031         // action. It wasn't needed. In that case create the original signature and the 
2032         // owner (parent author) signature
2033         // comments from other networks will be relayed under our name, with a brief 
2034         // preamble to describe what's happening and noting the real author
2035
2036         $r = q("select * from sign where iid = %d limit 1",
2037                 intval($item['id'])
2038         );
2039         if(count($r)) { 
2040                 $orig_sign = $r[0];
2041                 $signed_text = $orig_sign['signed_text'];
2042                 $authorsig = $orig_sign['signature'];
2043                 $handle = $orig_sign['signer'];
2044         }
2045         else {
2046
2047                 $itemcontact = q("select * from contact where `id` = %d limit 1",
2048                         intval($item['contact-id'])
2049                 );
2050                 if(count($itemcontact)) {
2051                         if(! $itemcontact[0]['self']) {
2052                                 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
2053                                         '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',  
2054                                         network_to_name($itemcontact['network'])) . "\n";
2055                                 $body = $prefix . $body;
2056                         }
2057                 }
2058                 else {
2059
2060                         if($like)
2061                                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
2062                         else
2063                                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
2064
2065                         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2066
2067                         q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2068                                 intval($item['id']),
2069                                 dbesc($signed_text),
2070                                 dbesc(base64_encode($authorsig)),
2071                                 dbesc($myaddr)
2072                         );
2073                         $handle = $myaddr;
2074                 }
2075         }
2076
2077         // sign it
2078
2079         $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2080
2081         $msg = replace_macros($tpl,array(
2082                 '$guid' => xmlify($item['guid']),
2083                 '$parent_guid' => xmlify($parent_guid),
2084                 '$target_type' =>xmlify($target_type),
2085                 '$authorsig' => xmlify($orig_sign['signature']),
2086                 '$parentsig' => xmlify($parentauthorsig),
2087                 '$body' => xmlify($text),
2088                 '$positive' => xmlify($positive),
2089                 '$handle' => xmlify($handle)
2090         ));
2091
2092         logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
2093
2094         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2095
2096         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2097
2098 }
2099
2100
2101
2102 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2103
2104         $a = get_app();
2105         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2106
2107         $signed_text = $item['guid'] . ';' . 'StatusMessage';
2108
2109         $tpl = get_markup_template('diaspora_signed_retract.tpl');
2110         $msg = replace_macros($tpl, array(
2111                 '$guid'   => $item['guid'],
2112                 '$type'   => 'StatusMessage',
2113                 '$handle' => $myaddr,
2114                 '$signature' => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'))
2115         ));
2116
2117         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2118
2119         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2120 }
2121
2122 function diaspora_send_mail($item,$owner,$contact) {
2123
2124         $a = get_app();
2125         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2126
2127         $r = q("select * from conv where id = %d and uid = %d limit 1",
2128                 intval($item['convid']),
2129                 intval($item['uid'])
2130         );
2131
2132         if(! count($r)) {
2133                 logger('diaspora_send_mail: conversation not found.');
2134                 return;
2135         }
2136         $cnv = $r[0];
2137
2138         $conv = array(
2139                 'guid' => xmlify($cnv['guid']),
2140                 'subject' => xmlify($cnv['subject']),
2141                 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2142                 'diaspora_handle' => xmlify($cnv['creator']),
2143                 'participant_handles' => xmlify($cnv['recips'])
2144         );
2145
2146         $body = bb2diaspora($item['body']);
2147         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2148  
2149         $signed_text =  $item['guid'] . ';' . $cnv['guid'] . ';' . $body .  ';' 
2150                 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2151
2152         $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2153
2154         $msg = array(
2155                 'guid' => xmlify($item['guid']),
2156                 'parent_guid' => xmlify($cnv['guid']),
2157                 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2158                 'author_signature' => xmlify($sig),
2159                 'text' => xmlify($body),
2160                 'created_at' => xmlify($created),
2161                 'diaspora_handle' => xmlify($myaddr),
2162                 'conversation_guid' => xmlify($cnv['guid'])
2163         );
2164
2165         if($item['reply']) {
2166                 $tpl = get_markup_template('diaspora_message.tpl');
2167                 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2168         }
2169         else {
2170                 $conv['messages'] = array($msg);
2171                 $tpl = get_markup_template('diaspora_conversation.tpl');
2172                 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2173         }
2174
2175         logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2176
2177         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2178
2179         return(diaspora_transmit($owner,$contact,$slap,false));
2180
2181
2182 }
2183
2184 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
2185
2186         $a = get_app();
2187         $logid = random_string(4);
2188         $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2189         if(! $dest_url) {
2190                 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2191                 return 0;
2192         } 
2193
2194         logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2195
2196         if(! intval(get_config('system','diaspora_test')))
2197                 post_url($dest_url . '/', $slap);
2198         else {
2199                 logger('diaspora_transmit: test_mode');
2200                 return 200;
2201         }
2202
2203         $return_code = $a->get_curl_code();
2204         logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2205
2206         if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2207                 logger('diaspora_transmit: queue message');
2208
2209                 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2210                         intval($contact['id']),
2211                         dbesc(NETWORK_DIASPORA),
2212                         dbesc($slap),
2213                         intval($public_batch)
2214                 );
2215                 if(count($r)) {
2216                         logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2217                 }
2218                 else {
2219                         // queue message for redelivery
2220                         add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2221                 }
2222         }
2223
2224
2225         return(($return_code) ? $return_code : (-1));
2226 }