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