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