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