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