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