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