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