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