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