]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
New option to enable and disable the "share" element
[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         if(($contact['blocked']) || ($contact['readonly']))
756                 return false;
757         if($contact['rel'] == CONTACT_IS_SHARING || $contact['rel'] == CONTACT_IS_FRIEND)
758                 return true;
759         if($contact['rel'] == CONTACT_IS_FOLLOWER)
760                 if($importer['page-flags'] == PAGE_COMMUNITY)
761                         return true;
762         return false;
763 }
764
765
766 function diaspora_post($importer,$xml,$msg) {
767
768         $a = get_app();
769         $guid = notags(unxmlify($xml->guid));
770         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
771
772         if($diaspora_handle != $msg['author']) {
773                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
774                 return 202;
775         }
776
777         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
778         if(! $contact)
779                 return;
780
781         if(! diaspora_post_allow($importer,$contact)) {
782                 logger('diaspora_post: Ignoring this author.');
783                 return 202;
784         }
785
786         $message_id = $diaspora_handle . ':' . $guid;
787         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
788                 intval($importer['uid']),
789                 dbesc($message_id),
790                 dbesc($guid)
791         );
792         if(count($r)) {
793                 logger('diaspora_post: message exists: ' . $guid);
794                 return;
795         }
796
797         // allocate a guid on our system - we aren't fixing any collisions.
798         // we're ignoring them
799
800         $g = q("select * from guid where guid = '%s' limit 1",
801                 dbesc($guid)
802         );
803         if(! count($g)) {
804                 q("insert into guid ( guid ) values ( '%s' )",
805                         dbesc($guid)
806                 );
807         }
808
809         $created = unxmlify($xml->created_at);
810         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
811
812         $body = diaspora2bb($xml->raw_message);
813
814         $datarray = array();
815
816         $str_tags = '';
817
818         $tags = get_tags($body);
819
820         if(count($tags)) {
821                 foreach($tags as $tag) {
822                         if(strpos($tag,'#') === 0) {
823                                 if(strpos($tag,'[url='))
824                                         continue;
825
826                                 // don't link tags that are already embedded in links
827
828                                 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
829                                         continue;
830                                 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
831                                         continue;
832
833                                 $basetag = str_replace('_',' ',substr($tag,1));
834                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
835                                 if(strlen($str_tags))
836                                         $str_tags .= ',';
837                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
838                                 continue;
839                         }
840                 }
841         }
842
843         $cnt = preg_match_all('/@\[url=(.*?)\[\/url\]/ism',$body,$matches,PREG_SET_ORDER);
844         if($cnt) {
845                 foreach($matches as $mtch) {
846                         if(strlen($str_tags))
847                                 $str_tags .= ',';
848                         $str_tags .= '@[url=' . $mtch[1] . '[/url]';    
849                 }
850         }
851
852         $datarray['uid'] = $importer['uid'];
853         $datarray['contact-id'] = $contact['id'];
854         $datarray['wall'] = 0;
855         $datarray['guid'] = $guid;
856         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
857         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
858         $datarray['private'] = $private;
859         $datarray['parent'] = 0;
860         $datarray['owner-name'] = $contact['name'];
861         $datarray['owner-link'] = $contact['url'];
862         //$datarray['owner-avatar'] = $contact['thumb'];
863         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
864         $datarray['author-name'] = $contact['name'];
865         $datarray['author-link'] = $contact['url'];
866         $datarray['author-avatar'] = $contact['thumb'];
867         $datarray['body'] = $body;
868         $datarray['tag'] = $str_tags;
869         $datarray['app']  = 'Diaspora';
870
871         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
872
873         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
874
875         $message_id = item_store($datarray);
876
877         if($message_id) {
878                 q("update item set plink = '%s' where id = %d limit 1",
879                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
880                         intval($message_id)
881                 );
882         }
883
884         return;
885
886 }
887
888 function diaspora_reshare($importer,$xml,$msg) {
889
890         logger('diaspora_reshare: init: ' . print_r($xml,true));
891
892         $a = get_app();
893         $guid = notags(unxmlify($xml->guid));
894         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
895
896
897         if($diaspora_handle != $msg['author']) {
898                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
899                 return 202;
900         }
901
902         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
903         if(! $contact)
904                 return;
905
906         if(! diaspora_post_allow($importer,$contact)) {
907                 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
908                 return 202;
909         }
910
911         $message_id = $diaspora_handle . ':' . $guid;
912         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
913                 intval($importer['uid']),
914                 dbesc($message_id),
915                 dbesc($guid)
916         );
917         if(count($r)) {
918                 logger('diaspora_reshare: message exists: ' . $guid);
919                 return;
920         }
921
922         $orig_author = notags(unxmlify($xml->root_diaspora_id));
923         $orig_guid = notags(unxmlify($xml->root_guid));
924
925         $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
926         $orig_url = 'https://'.substr($orig_author,strpos($orig_author,'@')+1).'/posts/'.$orig_guid;
927         $x = fetch_url($source_url);
928         if(! $x)
929                 $x = fetch_url(str_replace('https://','http://',$source_url));
930         if(! $x) {
931                 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
932                 return;
933         }
934         logger('diaspora_reshare: source: ' . $x);
935
936         $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
937         $source_xml = parse_xml_string($x,false);
938
939         if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
940                 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
941                 $body = scale_external_images($body,false);
942         }
943         elseif($source_xml->post->asphoto->image_url) {
944                 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
945                 $body = scale_external_images($body);
946         }
947         elseif($source_xml->post->status_message) {
948                 $body = diaspora2bb($source_xml->post->status_message->raw_message);
949                 $body = scale_external_images($body);
950
951         }
952         else {
953                 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
954                 return;
955         }
956         if(! $body) {
957                 logger('diaspora_reshare: empty body: source= ' . $x);
958                 return;
959         }
960
961         $person = find_diaspora_person_by_handle($orig_author);
962
963         /*if(is_array($person) && x($person,'name') && x($person,'url'))
964                 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
965         else
966                 $details = $orig_author;
967
968         $prefix = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8') . $details . "\n";*/
969
970
971         // allocate a guid on our system - we aren't fixing any collisions.
972         // we're ignoring them
973
974         $g = q("select * from guid where guid = '%s' limit 1",
975                 dbesc($guid)
976         );
977         if(! count($g)) {
978                 q("insert into guid ( guid ) values ( '%s' )",
979                         dbesc($guid)
980                 );
981         }
982
983         $created = unxmlify($xml->created_at);
984         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
985
986         $datarray = array();
987
988         $str_tags = '';
989
990         $tags = get_tags($body);
991
992         if(count($tags)) {
993                 foreach($tags as $tag) {
994                         if(strpos($tag,'#') === 0) {
995                                 if(strpos($tag,'[url='))
996                                         continue;
997
998                                 // don't link tags that are already embedded in links
999
1000                                 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
1001                                         continue;
1002                                 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
1003                                         continue;
1004
1005
1006                                 $basetag = str_replace('_',' ',substr($tag,1));
1007                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1008                                 if(strlen($str_tags))
1009                                         $str_tags .= ',';
1010                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1011                                 continue;
1012                         }
1013                 }
1014         }
1015
1016         $datarray['uid'] = $importer['uid'];
1017         $datarray['contact-id'] = $contact['id'];
1018         $datarray['wall'] = 0;
1019         $datarray['guid'] = $guid;
1020         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1021         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1022         $datarray['private'] = $private;
1023         $datarray['parent'] = 0;
1024         $datarray['owner-name'] = $contact['name'];
1025         $datarray['owner-link'] = $contact['url'];
1026         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1027         if (intval(get_config('system','new_share'))) {
1028                 $prefix = "[share author='".$person['name'].
1029                                 "' profile='".$person['url'].
1030                                 "' avatar='".((x($person,'thumb')) ? $person['thumb'] : $person['photo']).
1031                                 "' link='".$orig_url."']";
1032                 $datarray['author-name'] = $contact['name'];
1033                 $datarray['author-link'] = $contact['url'];
1034                 $datarray['author-avatar'] = $contact['thumb'];
1035                 $datarray['body'] = $prefix.$body."[/share]";
1036         } else {
1037                 // Let reshared messages look like wall-to-wall posts
1038                 $datarray['author-name'] = $person['name'];
1039                 $datarray['author-link'] = $person['url'];
1040                 $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1041                 $datarray['body'] = $body;
1042         }
1043
1044         $datarray['tag'] = $str_tags;
1045         $datarray['app']  = 'Diaspora';
1046
1047         $message_id = item_store($datarray);
1048
1049         if($message_id) {
1050                 q("update item set plink = '%s' where id = %d limit 1",
1051                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1052                         intval($message_id)
1053                 );
1054         }
1055
1056         return;
1057
1058 }
1059
1060
1061 function diaspora_asphoto($importer,$xml,$msg) {
1062         logger('diaspora_asphoto called');
1063
1064         $a = get_app();
1065         $guid = notags(unxmlify($xml->guid));
1066         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1067
1068         if($diaspora_handle != $msg['author']) {
1069                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
1070                 return 202;
1071         }
1072
1073         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1074         if(! $contact)
1075                 return;
1076
1077         if(! diaspora_post_allow($importer,$contact)) {
1078                 logger('diaspora_asphoto: Ignoring this author.');
1079                 return 202;
1080         }
1081
1082         $message_id = $diaspora_handle . ':' . $guid;
1083         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
1084                 intval($importer['uid']),
1085                 dbesc($message_id),
1086                 dbesc($guid)
1087         );
1088         if(count($r)) {
1089                 logger('diaspora_asphoto: message exists: ' . $guid);
1090                 return;
1091         }
1092
1093         // allocate a guid on our system - we aren't fixing any collisions.
1094         // we're ignoring them
1095
1096         $g = q("select * from guid where guid = '%s' limit 1",
1097                 dbesc($guid)
1098         );
1099         if(! count($g)) {
1100                 q("insert into guid ( guid ) values ( '%s' )",
1101                         dbesc($guid)
1102                 );
1103         }
1104
1105         $created = unxmlify($xml->created_at);
1106         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
1107
1108         if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
1109                 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
1110                 $body = scale_external_images($body,false);
1111         }
1112         elseif($xml->image_url) {
1113                 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
1114                 $body = scale_external_images($body);
1115         }
1116         else {
1117                 logger('diaspora_asphoto: no photo url found.');
1118                 return;
1119         }
1120
1121         $datarray = array();
1122
1123         
1124         $datarray['uid'] = $importer['uid'];
1125         $datarray['contact-id'] = $contact['id'];
1126         $datarray['wall'] = 0;
1127         $datarray['guid'] = $guid;
1128         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
1129         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
1130         $datarray['private'] = $private;
1131         $datarray['parent'] = 0;
1132         $datarray['owner-name'] = $contact['name'];
1133         $datarray['owner-link'] = $contact['url'];
1134         //$datarray['owner-avatar'] = $contact['thumb'];
1135         $datarray['owner-avatar'] = ((x($contact,'thumb')) ? $contact['thumb'] : $contact['photo']);
1136         $datarray['author-name'] = $contact['name'];
1137         $datarray['author-link'] = $contact['url'];
1138         $datarray['author-avatar'] = $contact['thumb'];
1139         $datarray['body'] = $body;
1140         
1141         $datarray['app']  = 'Diaspora/Cubbi.es';
1142
1143         $message_id = item_store($datarray);
1144
1145         if($message_id) {
1146                 q("update item set plink = '%s' where id = %d limit 1",
1147                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1148                         intval($message_id)
1149                 );
1150         }
1151
1152         return;
1153
1154 }
1155
1156
1157
1158
1159
1160
1161 function diaspora_comment($importer,$xml,$msg) {
1162
1163         $a = get_app();
1164         $guid = notags(unxmlify($xml->guid));
1165         $parent_guid = notags(unxmlify($xml->parent_guid));
1166         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1167         $target_type = notags(unxmlify($xml->target_type));
1168         $text = unxmlify($xml->text);
1169         $author_signature = notags(unxmlify($xml->author_signature));
1170
1171         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1172
1173         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1174         if(! $contact) {
1175                 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
1176                 return;
1177         }
1178
1179         if(! diaspora_post_allow($importer,$contact)) {
1180                 logger('diaspora_comment: Ignoring this author.');
1181                 return 202;
1182         }
1183
1184         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1185                 intval($importer['uid']),
1186                 dbesc($guid)
1187         );
1188         if(count($r)) {
1189                 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
1190                 return;
1191         }
1192
1193         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1194                 intval($importer['uid']),
1195                 dbesc($parent_guid)
1196         );
1197         if(! count($r)) {
1198                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1199                 return;
1200         }
1201         $parent_item = $r[0];
1202
1203
1204         /* How Diaspora performs comment signature checking:
1205
1206            - If an item has been sent by the comment author to the top-level post owner to relay on
1207              to the rest of the contacts on the top-level post, the top-level post owner should check
1208              the author_signature, then create a parent_author_signature before relaying the comment on
1209            - If an item has been relayed on by the top-level post owner, the contacts who receive it
1210              check only the parent_author_signature. Basically, they trust that the top-level post
1211              owner has already verified the authenticity of anything he/she sends out
1212            - In either case, the signature that get checked is the signature created by the person
1213              who sent the salmon
1214         */
1215
1216         $signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
1217         $key = $msg['key'];
1218
1219         if($parent_author_signature) {
1220                 // If a parent_author_signature exists, then we've received the comment
1221                 // relayed from the top-level post owner. There's no need to check the
1222                 // author_signature if the parent_author_signature is valid
1223
1224                 $parent_author_signature = base64_decode($parent_author_signature);
1225
1226                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1227                         logger('diaspora_comment: top-level owner verification failed.');
1228                         return;
1229                 }
1230         }
1231         else {
1232                 // If there's no parent_author_signature, then we've received the comment
1233                 // from the comment creator. In that case, the person is commenting on
1234                 // our post, so he/she must be a contact of ours and his/her public key
1235                 // should be in $msg['key']
1236
1237                 $author_signature = base64_decode($author_signature);
1238
1239                 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1240                         logger('diaspora_comment: comment author verification failed.');
1241                         return;
1242                 }
1243         }
1244
1245         // Phew! Everything checks out. Now create an item.
1246
1247         // Find the original comment author information.
1248         // We need this to make sure we display the comment author
1249         // information (name and avatar) correctly.
1250         if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1251                 $person = $contact;
1252         else {
1253                 $person = find_diaspora_person_by_handle($diaspora_handle);     
1254
1255                 if(! is_array($person)) {
1256                         logger('diaspora_comment: unable to find author details');
1257                         return;
1258                 }
1259         }
1260
1261         $body = diaspora2bb($text);
1262
1263         $message_id = $diaspora_handle . ':' . $guid;
1264
1265         $datarray = array();
1266
1267         $str_tags = '';
1268
1269         $tags = get_tags($body);
1270
1271         if(count($tags)) {
1272                 foreach($tags as $tag) {
1273                         if(strpos($tag,'#') === 0) {
1274                                 if(strpos($tag,'[url='))
1275                                         continue;
1276
1277                                 // don't link tags that are already embedded in links
1278
1279                                 if(preg_match('/\[(.*?)' . preg_quote($tag,'/') . '(.*?)\]/',$body))
1280                                         continue;
1281                                 if(preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag,'/') . '(.*?)\)/',$body))
1282                                         continue;
1283
1284
1285                                 $basetag = str_replace('_',' ',substr($tag,1));
1286                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
1287                                 if(strlen($str_tags))
1288                                         $str_tags .= ',';
1289                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1290                                 continue;
1291                         }
1292                 }
1293         }
1294
1295         $datarray['uid'] = $importer['uid'];
1296         $datarray['contact-id'] = $contact['id'];
1297         $datarray['type'] = 'remote-comment';
1298         $datarray['wall'] = $parent_item['wall'];
1299         $datarray['gravity'] = GRAVITY_COMMENT;
1300         $datarray['guid'] = $guid;
1301         $datarray['uri'] = $message_id;
1302         $datarray['parent-uri'] = $parent_item['uri'];
1303
1304         // No timestamps for comments? OK, we'll the use current time.
1305         $datarray['created'] = $datarray['edited'] = datetime_convert();
1306         $datarray['private'] = $parent_item['private'];
1307
1308         $datarray['owner-name'] = $parent_item['owner-name'];
1309         $datarray['owner-link'] = $parent_item['owner-link'];
1310         $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1311
1312         $datarray['author-name'] = $person['name'];
1313         $datarray['author-link'] = $person['url'];
1314         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1315         $datarray['body'] = $body;
1316         $datarray['tag'] = $str_tags;
1317
1318         // We can't be certain what the original app is if the message is relayed.
1319         if(($parent_item['origin']) && (! $parent_author_signature)) 
1320                 $datarray['app']  = 'Diaspora';
1321
1322         $message_id = item_store($datarray);
1323
1324         if($message_id) {
1325                 q("update item set plink = '%s' where id = %d limit 1",
1326                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1327                         intval($message_id)
1328                 );
1329         }
1330
1331         if(($parent_item['origin']) && (! $parent_author_signature)) {
1332                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1333                         intval($message_id),
1334                         dbesc($signed_data),
1335                         dbesc(base64_encode($author_signature)),
1336                         dbesc($diaspora_handle)
1337                 );
1338
1339                 // if the message isn't already being relayed, notify others
1340                 // the existence of parent_author_signature means the parent_author or owner
1341                 // is already relaying.
1342
1343                 proc_run('php','include/notifier.php','comment-import',$message_id);
1344         }
1345
1346         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0 ",
1347                 dbesc($parent_item['uri']),
1348                 intval($importer['uid'])
1349         );
1350
1351         if(count($myconv)) {
1352                 $importer_url = $a->get_baseurl() . '/profile/' . $importer['nickname'];
1353
1354                 foreach($myconv as $conv) {
1355
1356                         // now if we find a match, it means we're in this conversation
1357         
1358                         if(! link_compare($conv['author-link'],$importer_url))
1359                                 continue;
1360
1361                         require_once('include/enotify.php');
1362                                                                 
1363                         $conv_parent = $conv['parent'];
1364
1365                         notification(array(
1366                                 'type'         => NOTIFY_COMMENT,
1367                                 'notify_flags' => $importer['notify-flags'],
1368                                 'language'     => $importer['language'],
1369                                 'to_name'      => $importer['username'],
1370                                 'to_email'     => $importer['email'],
1371                                 'uid'          => $importer['uid'],
1372                                 'item'         => $datarray,
1373                                 'link'             => $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id,
1374                                 'source_name'  => $datarray['author-name'],
1375                                 'source_link'  => $datarray['author-link'],
1376                                 'source_photo' => $datarray['author-avatar'],
1377                                 'verb'         => ACTIVITY_POST,
1378                                 'otype'        => 'item',
1379                                 'parent'       => $conv_parent,
1380                                 'parent_uri'   => $parent_uri
1381                         ));
1382
1383                         // only send one notification
1384                         break;
1385                 }
1386         }
1387         return;
1388 }
1389
1390
1391
1392
1393 function diaspora_conversation($importer,$xml,$msg) {
1394
1395         $a = get_app();
1396
1397         $guid = notags(unxmlify($xml->guid));
1398         $subject = notags(unxmlify($xml->subject));
1399         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1400         $participant_handles = notags(unxmlify($xml->participant_handles));
1401         $created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1402
1403         $parent_uri = $diaspora_handle . ':' . $guid;
1404  
1405         $messages = $xml->message;
1406
1407         if(! count($messages)) {
1408                 logger('diaspora_conversation: empty conversation');
1409                 return;
1410         }
1411
1412         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1413         if(! $contact) {
1414                 logger('diaspora_conversation: cannot find contact: ' . $msg['author']);
1415                 return;
1416         }
1417
1418         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1419                 logger('diaspora_conversation: Ignoring this author.');
1420                 return 202;
1421         }
1422
1423         $conversation = null;
1424
1425         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1426                 intval($importer['uid']),
1427                 dbesc($guid)
1428         );
1429         if(count($c))
1430                 $conversation = $c[0];
1431         else {
1432                 $r = q("insert into conv (uid,guid,creator,created,updated,subject,recips) values(%d, '%s', '%s', '%s', '%s', '%s', '%s') ",
1433                         intval($importer['uid']),
1434                         dbesc($guid),
1435                         dbesc($diaspora_handle),
1436                         dbesc(datetime_convert('UTC','UTC',$created_at)),
1437                         dbesc(datetime_convert()),
1438                         dbesc($subject),
1439                         dbesc($participant_handles)
1440                 );
1441                 if($r)
1442                         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1443                 intval($importer['uid']),
1444             dbesc($guid)
1445         );
1446             if(count($c))
1447             $conversation = $c[0];
1448         }
1449         if(! $conversation) {
1450                 logger('diaspora_conversation: unable to create conversation.');
1451                 return;
1452         }
1453
1454         foreach($messages as $mesg) {
1455
1456                 $reply = 0;
1457
1458                 $msg_guid = notags(unxmlify($mesg->guid));
1459                 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1460                 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1461                 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1462                 $msg_text = unxmlify($mesg->text);
1463                 $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($mesg->created_at)));
1464                 $msg_diaspora_handle = notags(unxmlify($mesg->diaspora_handle));
1465                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1466                 if($msg_conversation_guid != $guid) {
1467                         logger('diaspora_conversation: message conversation guid does not belong to the current conversation. ' . $xml);
1468                         continue;
1469                 }
1470
1471                 $body = diaspora2bb($msg_text);
1472                 $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1473
1474                 $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1475
1476                 $author_signature = base64_decode($msg_author_signature);
1477
1478                 if(strcasecmp($msg_diaspora_handle,$msg['author']) == 0) {
1479                         $person = $contact;
1480                         $key = $msg['key'];
1481                 }
1482                 else {
1483                         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1484
1485                         if(is_array($person) && x($person,'pubkey'))
1486                                 $key = $person['pubkey'];
1487                         else {
1488                                 logger('diaspora_conversation: unable to find author details');
1489                                 continue;
1490                         }
1491                 }
1492
1493                 if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1494                         logger('diaspora_conversation: verification failed.');
1495                         continue;
1496                 }
1497
1498                 if($msg_parent_author_signature) {
1499                         $owner_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($mesg->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1500
1501                         $parent_author_signature = base64_decode($msg_parent_author_signature);
1502
1503                         $key = $msg['key'];
1504
1505                         if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1506                                 logger('diaspora_conversation: owner verification failed.');
1507                                 continue;
1508                         }
1509                 }
1510
1511                 $r = q("select id from mail where `uri` = '%s' limit 1",
1512                         dbesc($message_id)
1513                 );
1514                 if(count($r)) {
1515                         logger('diaspora_conversation: duplicate message already delivered.', LOGGER_DEBUG);
1516                         continue;
1517                 }
1518
1519                 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')",
1520                         intval($importer['uid']),
1521                         dbesc($msg_guid),
1522                         intval($conversation['id']),
1523                         dbesc($person['name']),
1524                         dbesc($person['photo']),
1525                         dbesc($person['url']),
1526                         intval($contact['id']),  
1527                         dbesc($subject),
1528                         dbesc($body),
1529                         0,
1530                         0,
1531                         dbesc($message_id),
1532                         dbesc($parent_uri),
1533                         dbesc($msg_created_at)
1534                 );                      
1535
1536                 q("update conv set updated = '%s' where id = %d limit 1",
1537                         dbesc(datetime_convert()),
1538                         intval($conversation['id'])
1539                 );              
1540
1541                 require_once('include/enotify.php');
1542                 notification(array(                     
1543                         'type' => NOTIFY_MAIL,
1544                         'notify_flags' => $importer['notify-flags'],
1545                         'language' => $importer['language'],
1546                         'to_name' => $importer['username'],
1547                         'to_email' => $importer['email'],
1548                         'uid' =>$importer['importer_uid'],
1549                         'item' => array('subject' => $subject, 'body' => $body),
1550                         'source_name' => $person['name'],
1551                         'source_link' => $person['url'],
1552                         'source_photo' => $person['thumb'],
1553                         'verb' => ACTIVITY_POST,
1554                         'otype' => 'mail'
1555                 ));
1556         }       
1557
1558         return;
1559 }
1560
1561 function diaspora_message($importer,$xml,$msg) {
1562
1563         $a = get_app();
1564
1565         $msg_guid = notags(unxmlify($xml->guid));
1566         $msg_parent_guid = notags(unxmlify($xml->parent_guid));
1567         $msg_parent_author_signature = notags(unxmlify($xml->parent_author_signature));
1568         $msg_author_signature = notags(unxmlify($xml->author_signature));
1569         $msg_text = unxmlify($xml->text);
1570         $msg_created_at = datetime_convert('UTC','UTC',notags(unxmlify($xml->created_at)));
1571         $msg_diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1572         $msg_conversation_guid = notags(unxmlify($xml->conversation_guid));
1573
1574         $parent_uri = $diaspora_handle . ':' . $msg_parent_guid;
1575  
1576         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg_diaspora_handle);
1577         if(! $contact) {
1578                 logger('diaspora_message: cannot find contact: ' . $msg_diaspora_handle);
1579                 return;
1580         }
1581
1582         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1583                 logger('diaspora_message: Ignoring this author.');
1584                 return 202;
1585         }
1586
1587         $conversation = null;
1588
1589         $c = q("select * from conv where uid = %d and guid = '%s' limit 1",
1590                 intval($importer['uid']),
1591                 dbesc($msg_conversation_guid)
1592         );
1593         if(count($c))
1594                 $conversation = $c[0];
1595         else {
1596                 logger('diaspora_message: conversation not available.');
1597                 return;
1598         }
1599
1600         $reply = 0;
1601                         
1602         $body = diaspora2bb($msg_text);
1603         $message_id = $msg_diaspora_handle . ':' . $msg_guid;
1604
1605         $author_signed_data = $msg_guid . ';' . $msg_parent_guid . ';' . $msg_text . ';' . unxmlify($xml->created_at) . ';' . $msg_diaspora_handle . ';' . $msg_conversation_guid;
1606
1607
1608         $author_signature = base64_decode($msg_author_signature);
1609
1610         $person = find_diaspora_person_by_handle($msg_diaspora_handle); 
1611         if(is_array($person) && x($person,'pubkey'))
1612                 $key = $person['pubkey'];
1613         else {
1614                 logger('diaspora_message: unable to find author details');
1615                 return;
1616         }
1617
1618         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1619                 logger('diaspora_message: verification failed.');
1620                 return;
1621         }
1622
1623         $r = q("select id from mail where `uri` = '%s' and uid = %d limit 1",
1624                 dbesc($message_id),
1625                 intval($importer['uid'])
1626         );
1627         if(count($r)) {
1628                 logger('diaspora_message: duplicate message already delivered.', LOGGER_DEBUG);
1629                 return;
1630         }
1631
1632         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')",
1633                 intval($importer['uid']),
1634                 dbesc($msg_guid),
1635                 intval($conversation['id']),
1636                 dbesc($person['name']),
1637                 dbesc($person['photo']),
1638                 dbesc($person['url']),
1639                 intval($contact['id']),  
1640                 dbesc($conversation['subject']),
1641                 dbesc($body),
1642                 0,
1643                 1,
1644                 dbesc($message_id),
1645                 dbesc($parent_uri),
1646                 dbesc($msg_created_at)
1647         );                      
1648
1649         q("update conv set updated = '%s' where id = %d limit 1",
1650                 dbesc(datetime_convert()),
1651                 intval($conversation['id'])
1652         );              
1653         
1654         return;
1655 }
1656
1657
1658 function diaspora_photo($importer,$xml,$msg) {
1659
1660         $a = get_app();
1661
1662         logger('diaspora_photo: init',LOGGER_DEBUG);
1663
1664         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1665
1666         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1667
1668         $status_message_guid = notags(unxmlify($xml->status_message_guid));
1669
1670         $guid = notags(unxmlify($xml->guid));
1671
1672         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1673
1674         $public = notags(unxmlify($xml->public));
1675
1676         $created_at = notags(unxmlify($xml_created_at));
1677
1678         logger('diaspora_photo: status_message_guid: ' . $status_message_guid, LOGGER_DEBUG);
1679
1680         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1681         if(! $contact) {
1682                 logger('diaspora_photo: contact record not found: ' . $msg['author'] . ' handle: ' . $diaspora_handle);
1683                 return;
1684         }
1685
1686         if(! diaspora_post_allow($importer,$contact)) {
1687                 logger('diaspora_photo: Ignoring this author.');
1688                 return 202;
1689         }
1690
1691         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1692                 intval($importer['uid']),
1693                 dbesc($status_message_guid)
1694         );
1695         if(! count($r)) {
1696                 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1697                 return;
1698         }
1699
1700         $parent_item = $r[0];
1701
1702         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1703
1704         $link_text = scale_external_images($link_text, true,
1705                                            array($remote_photo_name, 'scaled_full_' . $remote_photo_name));
1706
1707         if(strpos($parent_item['body'],$link_text) === false) {
1708                 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1709                         dbesc($link_text . $parent_item['body']),
1710                         intval($parent_item['id']),
1711                         intval($parent_item['uid'])
1712                 );
1713         }
1714
1715         return;
1716 }
1717
1718
1719
1720
1721 function diaspora_like($importer,$xml,$msg) {
1722
1723         $a = get_app();
1724         $guid = notags(unxmlify($xml->guid));
1725         $parent_guid = notags(unxmlify($xml->parent_guid));
1726         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1727         $target_type = notags(unxmlify($xml->target_type));
1728         $positive = notags(unxmlify($xml->positive));
1729         $author_signature = notags(unxmlify($xml->author_signature));
1730
1731         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1732
1733         // likes on comments not supported here and likes on photos not supported by Diaspora
1734
1735 //      if($target_type !== 'Post')
1736 //              return;
1737
1738         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1739         if(! $contact) {
1740                 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1741                 return;
1742         }
1743
1744         if(! diaspora_post_allow($importer,$contact)) {
1745                 logger('diaspora_like: Ignoring this author.');
1746                 return 202;
1747         }
1748
1749         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1750                 intval($importer['uid']),
1751                 dbesc($parent_guid)
1752         );
1753         if(! count($r)) {
1754                 logger('diaspora_like: parent item not found: ' . $guid);
1755                 return;
1756         }
1757
1758         $parent_item = $r[0];
1759
1760         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1761                 intval($importer['uid']),
1762                 dbesc($guid)
1763         );
1764         if(count($r)) {
1765                 if($positive === 'true') {
1766                         logger('diaspora_like: duplicate like: ' . $guid);
1767                         return;
1768                 } 
1769                 // Note: I don't think "Like" objects with positive = "false" are ever actually used
1770                 // It looks like "RelayableRetractions" are used for "unlike" instead
1771                 if($positive === 'false') {
1772                         logger('diaspora_like: received a like with positive set to "false"...ignoring');
1773 /*                      q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1774                                 intval($r[0]['id']),
1775                                 intval($importer['uid'])
1776                         );*/
1777                         // FIXME--actually don't unless it turns out that Diaspora does indeed send out "false" likes
1778                         //  send notification via proc_run()
1779                         return;
1780                 }
1781         }
1782         // Note: I don't think "Like" objects with positive = "false" are ever actually used
1783         // It looks like "RelayableRetractions" are used for "unlike" instead
1784         if($positive === 'false') {
1785                 logger('diaspora_like: received a like with positive set to "false"');
1786                 logger('diaspora_like: unlike received with no corresponding like...ignoring');
1787                 return; 
1788         }
1789
1790
1791         /* How Diaspora performs "like" signature checking:
1792
1793            - If an item has been sent by the like author to the top-level post owner to relay on
1794              to the rest of the contacts on the top-level post, the top-level post owner should check
1795              the author_signature, then create a parent_author_signature before relaying the like on
1796            - If an item has been relayed on by the top-level post owner, the contacts who receive it
1797              check only the parent_author_signature. Basically, they trust that the top-level post
1798              owner has already verified the authenticity of anything he/she sends out
1799            - In either case, the signature that get checked is the signature created by the person
1800              who sent the salmon
1801         */
1802
1803         $signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1804         $key = $msg['key'];
1805
1806         if($parent_author_signature) {
1807                 // If a parent_author_signature exists, then we've received the like
1808                 // relayed from the top-level post owner. There's no need to check the
1809                 // author_signature if the parent_author_signature is valid
1810
1811                 $parent_author_signature = base64_decode($parent_author_signature);
1812
1813                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
1814                         logger('diaspora_like: top-level owner verification failed.');
1815                         return;
1816                 }
1817         }
1818         else {
1819                 // If there's no parent_author_signature, then we've received the like
1820                 // from the like creator. In that case, the person is "like"ing
1821                 // our post, so he/she must be a contact of ours and his/her public key
1822                 // should be in $msg['key']
1823
1824                 $author_signature = base64_decode($author_signature);
1825
1826                 if(! rsa_verify($signed_data,$author_signature,$key,'sha256')) {
1827                         logger('diaspora_like: like creator verification failed.');
1828                         return;
1829                 }
1830         }
1831
1832         // Phew! Everything checks out. Now create an item.
1833
1834         // Find the original comment author information.
1835         // We need this to make sure we display the comment author
1836         // information (name and avatar) correctly.
1837         if(strcasecmp($diaspora_handle,$msg['author']) == 0)
1838                 $person = $contact;
1839         else {
1840                 $person = find_diaspora_person_by_handle($diaspora_handle);
1841
1842                 if(! is_array($person)) {
1843                         logger('diaspora_like: unable to find author details');
1844                         return;
1845                 }
1846         }
1847
1848         $uri = $diaspora_handle . ':' . $guid;
1849
1850         $activity = ACTIVITY_LIKE;
1851         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1852         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
1853         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1854         $body = $parent_item['body'];
1855
1856         $obj = <<< EOT
1857
1858         <object>
1859                 <type>$objtype</type>
1860                 <local>1</local>
1861                 <id>{$parent_item['uri']}</id>
1862                 <link>$link</link>
1863                 <title></title>
1864                 <content>$body</content>
1865         </object>
1866 EOT;
1867         $bodyverb = t('%1$s likes %2$s\'s %3$s');
1868
1869         $arr = array();
1870
1871         $arr['uri'] = $uri;
1872         $arr['uid'] = $importer['uid'];
1873         $arr['guid'] = $guid;
1874         $arr['contact-id'] = $contact['id'];
1875         $arr['type'] = 'activity';
1876         $arr['wall'] = $parent_item['wall'];
1877         $arr['gravity'] = GRAVITY_LIKE;
1878         $arr['parent'] = $parent_item['id'];
1879         $arr['parent-uri'] = $parent_item['uri'];
1880
1881         $arr['owner-name'] = $parent_item['name'];
1882         $arr['owner-link'] = $parent_item['url'];
1883         //$arr['owner-avatar'] = $parent_item['thumb'];
1884         $arr['owner-avatar'] = ((x($parent_item,'thumb')) ? $parent_item['thumb'] : $parent_item['photo']);
1885
1886         $arr['author-name'] = $person['name'];
1887         $arr['author-link'] = $person['url'];
1888         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1889         
1890         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1891         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1892         $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1893         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
1894
1895         $arr['app']  = 'Diaspora';
1896
1897         $arr['private'] = $parent_item['private'];
1898         $arr['verb'] = $activity;
1899         $arr['object-type'] = $objtype;
1900         $arr['object'] = $obj;
1901         $arr['visible'] = 1;
1902         $arr['unseen'] = 1;
1903         $arr['last-child'] = 0;
1904
1905         $message_id = item_store($arr);
1906
1907
1908         if($message_id) {
1909                 q("update item set plink = '%s' where id = %d limit 1",
1910                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1911                         intval($message_id)
1912                 );
1913         }
1914
1915         if(! $parent_author_signature) {
1916                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1917                         intval($message_id),
1918                         dbesc($signed_data),
1919                         dbesc(base64_encode($author_signature)),
1920                         dbesc($diaspora_handle)
1921                 );
1922         }
1923
1924         // if the message isn't already being relayed, notify others
1925         // the existence of parent_author_signature means the parent_author or owner
1926         // is already relaying. The parent_item['origin'] indicates the message was created on our system
1927
1928         if(($parent_item['origin']) && (! $parent_author_signature))
1929                 proc_run('php','include/notifier.php','comment-import',$message_id);
1930
1931         return;
1932 }
1933
1934 function diaspora_retraction($importer,$xml) {
1935
1936
1937         $guid = notags(unxmlify($xml->guid));
1938         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1939         $type = notags(unxmlify($xml->type));
1940
1941         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1942         if(! $contact)
1943                 return;
1944
1945         if($type === 'Person') {
1946                 require_once('include/Contact.php');
1947                 contact_remove($contact['id']);
1948         }
1949         elseif($type === 'Post') {
1950                 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
1951                         dbesc('guid'),
1952                         intval($importer['uid'])
1953                 );
1954                 if(count($r)) {
1955                         if(link_compare($r[0]['author-link'],$contact['url'])) {
1956                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1957                                         dbesc(datetime_convert()),                      
1958                                         intval($r[0]['id'])
1959                                 );
1960                         }
1961                 }
1962         }
1963
1964         return 202;
1965         // NOTREACHED
1966 }
1967
1968 function diaspora_signed_retraction($importer,$xml,$msg) {
1969
1970
1971         $guid = notags(unxmlify($xml->target_guid));
1972         $diaspora_handle = notags(unxmlify($xml->sender_handle));
1973         $type = notags(unxmlify($xml->target_type));
1974         $sig = notags(unxmlify($xml->target_author_signature));
1975
1976         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1977
1978         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1979         if(! $contact) {
1980                 logger('diaspora_signed_retraction: no contact ' . $diaspora_handle . ' for ' . $importer['uid']);
1981                 return;
1982         }
1983
1984
1985         $signed_data = $guid . ';' . $type ;
1986         $key = $msg['key'];
1987
1988         /* How Diaspora performs relayable_retraction signature checking:
1989
1990            - If an item has been sent by the item author to the top-level post owner to relay on
1991              to the rest of the contacts on the top-level post, the top-level post owner checks
1992              the author_signature, then creates a parent_author_signature before relaying the item on
1993            - If an item has been relayed on by the top-level post owner, the contacts who receive it
1994              check only the parent_author_signature. Basically, they trust that the top-level post
1995              owner has already verified the authenticity of anything he/she sends out
1996            - In either case, the signature that get checked is the signature created by the person
1997              who sent the salmon
1998         */
1999
2000         if($parent_author_signature) {
2001
2002                 $parent_author_signature = base64_decode($parent_author_signature);
2003
2004                 if(! rsa_verify($signed_data,$parent_author_signature,$key,'sha256')) {
2005                         logger('diaspora_signed_retraction: top-level post owner verification failed');
2006                         return;
2007                 }
2008
2009         }
2010         else {
2011
2012                 $sig_decode = base64_decode($sig);
2013
2014                 if(! rsa_verify($signed_data,$sig_decode,$key,'sha256')) {
2015                         logger('diaspora_signed_retraction: retraction owner verification failed.' . print_r($msg,true));
2016                         return;
2017                 }
2018         }
2019
2020         if($type === 'StatusMessage' || $type === 'Comment' || $type === 'Like') {
2021                 $r = q("select * from item where guid = '%s' and uid = %d and not file like '%%[%%' limit 1",
2022                         dbesc($guid),
2023                         intval($importer['uid'])
2024                 );
2025                 if(count($r)) {
2026                         if(link_compare($r[0]['author-link'],$contact['url'])) {
2027                                 q("update item set `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' where `id` = %d limit 1",
2028                                         dbesc(datetime_convert()),                      
2029                                         dbesc(datetime_convert()),                      
2030                                         intval($r[0]['id'])
2031                                 );
2032         
2033                                 // Now check if the retraction needs to be relayed by us
2034                                 //
2035                                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2036                                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2037                                 // The only item with `parent` and `id` as the parent id is the parent item.
2038                                 $p = q("select origin from item where parent = %d and id = %d limit 1",
2039                                         $r[0]['parent'],
2040                                         $r[0]['parent']
2041                                 );
2042                                 if(count($p)) {
2043                                         if(($p[0]['origin']) && (! $parent_author_signature)) {
2044                                                 q("insert into sign (`retract_iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
2045                                                         $r[0]['id'],
2046                                                         dbesc($signed_data),
2047                                                         dbesc($sig),
2048                                                         dbesc($diaspora_handle)
2049                                                 );
2050
2051                                                 // the existence of parent_author_signature would have meant the parent_author or owner
2052                                                 // is already relaying.
2053                                                 logger('diaspora_signed_retraction: relaying relayable_retraction');
2054
2055                                                 proc_run('php','include/notifier.php','drop',$r[0]['id']);
2056                                         }
2057                                 }
2058                         }
2059                 }
2060         }
2061         else
2062                 logger('diaspora_signed_retraction: unknown type: ' . $type);
2063
2064         return 202;
2065         // NOTREACHED
2066 }
2067
2068 function diaspora_profile($importer,$xml,$msg) {
2069
2070         $a = get_app();
2071         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
2072
2073
2074         if($diaspora_handle != $msg['author']) {
2075                 logger('diaspora_post: Potential forgery. Message handle is not the same as envelope sender.');
2076                 return 202;
2077         }
2078
2079         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
2080         if(! $contact)
2081                 return;
2082
2083         if($contact['blocked']) {
2084                 logger('diaspora_post: Ignoring this author.');
2085                 return 202;
2086         }
2087
2088         $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
2089         $image_url = unxmlify($xml->image_url);
2090         $birthday = unxmlify($xml->birthday);
2091
2092
2093         $handle_parts = explode("@", $diaspora_handle);
2094         if($name === '') {
2095                 $name = $handle_parts[0];
2096         }
2097         if(strpos($image_url, $handle_parts[1]) === false) {
2098                 $image_url = "http://" . $handle_parts[1] . $image_url;
2099         }
2100
2101 /*      $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE  `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
2102                 intval($importer['uid']),
2103                 intval($contact['id'])
2104         );
2105         $oldphotos = ((count($r)) ? $r : null);*/
2106
2107         require_once('include/Photo.php');
2108
2109         $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
2110         
2111         // Generic birthday. We don't know the timezone. The year is irrelevant. 
2112
2113         $birthday = str_replace('1000','1901',$birthday);
2114
2115         $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
2116
2117         // this is to prevent multiple birthday notifications in a single year
2118         // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2119
2120         if(substr($birthday,5) === substr($contact['bd'],5))
2121                 $birthday = $contact['bd'];
2122
2123         // TODO: update name on item['author-name'] if the name changed. See consume_feed()
2124         // Not doing this currently because D* protocol is scheduled for revision soon. 
2125
2126         $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",
2127                 dbesc($name),
2128                 dbesc(datetime_convert()),
2129                 dbesc($images[0]),
2130                 dbesc($images[1]),
2131                 dbesc($images[2]),
2132                 dbesc(datetime_convert()),
2133                 dbesc($birthday),
2134                 intval($contact['id']),
2135                 intval($importer['uid'])
2136         ); 
2137
2138 /*      if($r) {
2139                 if($oldphotos) {
2140                         foreach($oldphotos as $ph) {
2141                                 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
2142                                         intval($importer['uid']),
2143                                         intval($contact['id']),
2144                                         dbesc($ph['resource-id'])
2145                                 );
2146                         }
2147                 }
2148         }       */
2149
2150         return;
2151
2152 }
2153
2154 function diaspora_share($me,$contact) {
2155         $a = get_app();
2156         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2157         $theiraddr = $contact['addr'];
2158
2159         $tpl = get_markup_template('diaspora_share.tpl');
2160         $msg = replace_macros($tpl, array(
2161                 '$sender' => $myaddr,
2162                 '$recipient' => $theiraddr
2163         ));
2164
2165         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2166         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2167
2168         return(diaspora_transmit($owner,$contact,$slap, false));
2169 }
2170
2171 function diaspora_unshare($me,$contact) {
2172
2173         $a = get_app();
2174         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2175
2176         $tpl = get_markup_template('diaspora_retract.tpl');
2177         $msg = replace_macros($tpl, array(
2178                 '$guid'   => $me['guid'],
2179                 '$type'   => 'Person',
2180                 '$handle' => $myaddr
2181         ));
2182
2183         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
2184         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey']));
2185
2186         return(diaspora_transmit($owner,$contact,$slap, false));
2187
2188 }
2189
2190
2191 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
2192
2193         $a = get_app();
2194         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2195         $theiraddr = $contact['addr'];
2196
2197         $images = array();
2198
2199         $title = $item['title'];
2200         $body = $item['body'];
2201
2202 /*
2203         // We're trying to match Diaspora's split message/photo protocol but
2204         // all the photos are displayed on D* as links and not img's - even
2205         // though we're sending pretty much precisely what they send us when
2206         // doing the same operation.  
2207         // Commented out for now, we'll use bb2diaspora to convert photos to markdown
2208         // which seems to get through intact.
2209
2210         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
2211         if($cnt) {
2212                 foreach($matches as $mtch) {
2213                         $detail = array();
2214                         $detail['str'] = $mtch[0];
2215                         $detail['path'] = dirname($mtch[1]) . '/';
2216                         $detail['file'] = basename($mtch[1]);
2217                         $detail['guid'] = $item['guid'];
2218                         $detail['handle'] = $myaddr;
2219                         $images[] = $detail;
2220                         $body = str_replace($detail['str'],$mtch[1],$body);
2221                 }
2222         }
2223 */
2224
2225         //if(strlen($title))
2226         //      $body = "[b]".html_entity_decode($title)."[/b]\n\n".$body;
2227
2228         // convert to markdown
2229         $body = xmlify(html_entity_decode(bb2diaspora($body)));
2230         //$body = bb2diaspora($body);
2231
2232         // Adding the title
2233         if(strlen($title))
2234                 $body = "## ".html_entity_decode($title)."\n\n".$body;
2235
2236         if($item['attach']) {
2237                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
2238                 if(cnt) {
2239                         $body .= "\n" . t('Attachments:') . "\n";
2240                         foreach($matches as $mtch) {
2241                                 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
2242                         }
2243                 }
2244         }       
2245
2246
2247         $public = (($item['private']) ? 'false' : 'true');
2248
2249         require_once('include/datetime.php');
2250         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2251
2252         $tpl = get_markup_template('diaspora_post.tpl');
2253         $msg = replace_macros($tpl, array(
2254                 '$body' => $body,
2255                 '$guid' => $item['guid'],
2256                 '$handle' => xmlify($myaddr),
2257                 '$public' => $public,
2258                 '$created' => $created
2259         ));
2260
2261         logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
2262
2263         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2264         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2265
2266         $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
2267
2268         if(count($images)) {
2269                 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
2270         }
2271
2272         return $return_code;
2273 }
2274
2275
2276 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
2277         $a = get_app();
2278         if(! count($images))
2279                 return;
2280         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
2281
2282         $tpl = get_markup_template('diaspora_photo.tpl');
2283         foreach($images as $image) {
2284                 if(! stristr($image['path'],$mysite))
2285                         continue;
2286                 $resource = str_replace('.jpg','',$image['file']);
2287                 $resource = substr($resource,0,strpos($resource,'-'));
2288
2289                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
2290                         dbesc($resource),
2291                         intval($owner['uid'])
2292                 );
2293                 if(! count($r))
2294                         continue;
2295                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
2296                 $msg = replace_macros($tpl,array(               
2297                         '$path' => xmlify($image['path']),
2298                         '$filename' => xmlify($image['file']),
2299                         '$msg_guid' => xmlify($image['guid']),
2300                         '$guid' => xmlify($r[0]['guid']),
2301                         '$handle' => xmlify($image['handle']),
2302                         '$public' => xmlify($public),
2303                         '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
2304                 ));
2305
2306
2307                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
2308                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2309                 //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2310
2311                 diaspora_transmit($owner,$contact,$slap,$public_batch);
2312         }
2313
2314 }
2315
2316 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
2317
2318         $a = get_app();
2319         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2320 //      $theiraddr = $contact['addr'];
2321
2322         // Diaspora doesn't support threaded comments
2323         /*if($item['thr-parent']) {
2324                 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2325                         dbesc($item['thr-parent'])
2326                       );
2327         }
2328         else {*/
2329                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2330                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2331                 // The only item with `parent` and `id` as the parent id is the parent item.
2332                 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2333                         intval($item['parent']),
2334                         intval($item['parent'])
2335                 );
2336         //}
2337         if(count($p))
2338                 $parent = $p[0];
2339         else
2340                 return;
2341
2342         if($item['verb'] === ACTIVITY_LIKE) {
2343                 $tpl = get_markup_template('diaspora_like.tpl');
2344                 $like = true;
2345                 $target_type = ( $parent['uri'] === $parent['parent-uri']  ? 'Post' : 'Comment');
2346 //              $target_type = (strpos($parent['type'], 'comment') ? 'Comment' : 'Post');
2347 //              $positive = (($item['deleted']) ? 'false' : 'true');
2348                 $positive = 'true';
2349
2350                 if(($item['deleted']))
2351                         logger('diaspora_send_followup: received deleted "like". Those should go to diaspora_send_retraction');
2352         }
2353         else {
2354                 $tpl = get_markup_template('diaspora_comment.tpl');
2355                 $like = false;
2356         }
2357
2358         $text = html_entity_decode(bb2diaspora($item['body']));
2359
2360         // sign it
2361
2362         if($like)
2363                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $myaddr;
2364         else
2365                 $signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $myaddr;
2366
2367         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2368
2369         $msg = replace_macros($tpl,array(
2370                 '$guid' => xmlify($item['guid']),
2371                 '$parent_guid' => xmlify($parent['guid']),
2372                 '$target_type' =>xmlify($target_type),
2373                 '$authorsig' => xmlify($authorsig),
2374                 '$body' => xmlify($text),
2375                 '$positive' => xmlify($positive),
2376                 '$handle' => xmlify($myaddr)
2377         ));
2378
2379         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
2380
2381         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2382         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2383
2384         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2385 }
2386
2387
2388 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
2389
2390
2391         $a = get_app();
2392         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2393 //      $theiraddr = $contact['addr'];
2394
2395         $body = $item['body'];
2396         $text = html_entity_decode(bb2diaspora($body));
2397
2398         // Diaspora doesn't support threaded comments
2399         /*if($item['thr-parent']) {
2400                 $p = q("select guid, type, uri, `parent-uri` from item where uri = '%s' limit 1",
2401                         dbesc($item['thr-parent'])
2402                       );
2403         }
2404         else {*/
2405                 // The first item in the `item` table with the parent id is the parent. However, MySQL doesn't always
2406                 // return the items ordered by `item`.`id`, in which case the wrong item is chosen as the parent.
2407                 // The only item with `parent` and `id` as the parent id is the parent item.
2408                 $p = q("select guid, type, uri, `parent-uri` from item where parent = %d and id = %d limit 1",
2409                        intval($item['parent']),
2410                        intval($item['parent'])
2411                       );
2412         //}
2413         if(count($p))
2414                 $parent = $p[0];
2415         else
2416                 return;
2417
2418         $like = false;
2419         $relay_retract = false;
2420         $sql_sign_id = 'iid';
2421         if( $item['deleted']) {
2422                 $relay_retract = true;
2423
2424                 $target_type = ( ($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2425
2426                 $sql_sign_id = 'retract_iid';
2427                 $tpl = get_markup_template('diaspora_relayable_retraction.tpl');
2428         }
2429         elseif($item['verb'] === ACTIVITY_LIKE) {
2430                 $like = true;
2431
2432                 $target_type = ( $parent['uri'] === $parent['parent-uri']  ? 'Post' : 'Comment');
2433 //              $positive = (($item['deleted']) ? 'false' : 'true');
2434                 $positive = 'true';
2435
2436                 $tpl = get_markup_template('diaspora_like_relay.tpl');
2437         }
2438         else { // item is a comment
2439                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
2440         }
2441
2442
2443         // fetch the original signature if the relayable was created by a Diaspora
2444         // or DFRN user. Relayables for other networks are not supported.
2445
2446 /*      $r = q("select * from sign where " . $sql_sign_id . " = %d limit 1",
2447                 intval($item['id'])
2448         );
2449         if(count($r)) { 
2450                 $orig_sign = $r[0];
2451                 $signed_text = $orig_sign['signed_text'];
2452                 $authorsig = $orig_sign['signature'];
2453                 $handle = $orig_sign['signer'];
2454         }
2455         else {
2456
2457                 // Author signature information (for likes, comments, and retractions of likes or comments,
2458                 // whether from Diaspora or Friendica) must be placed in the `sign` table before this 
2459                 // function is called
2460                 logger('diaspora_send_relay: original author signature not found, cannot send relayable');
2461                 return;
2462         }*/
2463
2464         /* Since the author signature is only checked by the parent, not by the relay recipients,
2465          * I think it may not be necessary for us to do so much work to preserve all the original
2466          * signatures. The important thing that Diaspora DOES need is the original creator's handle.
2467          * Let's just generate that and forget about all the original author signature stuff.
2468          *
2469          * Note: this might be more of an problem if we want to support likes on comments for older
2470          * versions of Diaspora (diaspora-pistos), but since there are a number of problems with
2471          * doing that, let's ignore it for now.
2472          *
2473          * Currently, only DFRN contacts are supported. StatusNet shouldn't be hard, but it hasn't
2474          * been done yet
2475          */
2476
2477         $handle = diaspora_handle_from_contact($item['contact-id']);
2478         if(! $handle)
2479                 return;
2480
2481
2482         if($relay_retract)
2483                 $sender_signed_text = $item['guid'] . ';' . $target_type;
2484         elseif($like)
2485                 $sender_signed_text = $item['guid'] . ';' . $target_type . ';' . $parent['guid'] . ';' . $positive . ';' . $handle;
2486         else
2487                 $sender_signed_text = $item['guid'] . ';' . $parent['guid'] . ';' . $text . ';' . $handle;
2488
2489         // Sign the relayable with the top-level owner's signature
2490         //
2491         // We'll use the $sender_signed_text that we just created, instead of the $signed_text
2492         // stored in the database, because that provides the best chance that Diaspora will
2493         // be able to reconstruct the signed text the same way we did. This is particularly a
2494         // concern for the comment, whose signed text includes the text of the comment. The
2495         // smallest change in the text of the comment, including removing whitespace, will
2496         // make the signature verification fail. Since we translate from BB code to Diaspora's
2497         // markup at the top of this function, which is AFTER we placed the original $signed_text
2498         // in the database, it's hazardous to trust the original $signed_text.
2499
2500         $parentauthorsig = base64_encode(rsa_sign($sender_signed_text,$owner['uprvkey'],'sha256'));
2501
2502         $msg = replace_macros($tpl,array(
2503                 '$guid' => xmlify($item['guid']),
2504                 '$parent_guid' => xmlify($parent['guid']),
2505                 '$target_type' =>xmlify($target_type),
2506                 '$authorsig' => xmlify($authorsig),
2507                 '$parentsig' => xmlify($parentauthorsig),
2508                 '$body' => xmlify($text),
2509                 '$positive' => xmlify($positive),
2510                 '$handle' => xmlify($handle)
2511         ));
2512
2513         logger('diaspora_send_relay: base message: ' . $msg, LOGGER_DATA);
2514
2515
2516         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2517         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2518
2519         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2520
2521 }
2522
2523
2524
2525 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
2526
2527         $a = get_app();
2528         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2529
2530         // Check whether the retraction is for a top-level post or whether it's a relayable
2531         if( $item['uri'] !== $item['parent-uri'] ) {
2532
2533                 $tpl = get_markup_template('diaspora_relay_retraction.tpl');
2534                 $target_type = (($item['verb'] === ACTIVITY_LIKE) ? 'Like' : 'Comment');
2535         }
2536         else {
2537                 
2538                 $tpl = get_markup_template('diaspora_signed_retract.tpl');
2539                 $target_type = 'StatusMessage';
2540         }
2541
2542         $signed_text = $item['guid'] . ';' . $target_type;
2543
2544         $msg = replace_macros($tpl, array(
2545                 '$guid'   => xmlify($item['guid']),
2546                 '$type'   => xmlify($target_type),
2547                 '$handle' => xmlify($myaddr),
2548                 '$signature' => xmlify(base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')))
2549         ));
2550
2551         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
2552         //$slap = 'xml=' . urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch));
2553
2554         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
2555 }
2556
2557 function diaspora_send_mail($item,$owner,$contact) {
2558
2559         $a = get_app();
2560         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
2561
2562         $r = q("select * from conv where id = %d and uid = %d limit 1",
2563                 intval($item['convid']),
2564                 intval($item['uid'])
2565         );
2566
2567         if(! count($r)) {
2568                 logger('diaspora_send_mail: conversation not found.');
2569                 return;
2570         }
2571         $cnv = $r[0];
2572
2573         $conv = array(
2574                 'guid' => xmlify($cnv['guid']),
2575                 'subject' => xmlify($cnv['subject']),
2576                 'created_at' => xmlify(datetime_convert('UTC','UTC',$cnv['created'],'Y-m-d H:i:s \U\T\C')),
2577                 'diaspora_handle' => xmlify($cnv['creator']),
2578                 'participant_handles' => xmlify($cnv['recips'])
2579         );
2580
2581         $body = bb2diaspora($item['body']);
2582         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
2583  
2584         $signed_text =  $item['guid'] . ';' . $cnv['guid'] . ';' . $body .  ';' 
2585                 . $created . ';' . $myaddr . ';' . $cnv['guid'];
2586
2587         $sig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
2588
2589         $msg = array(
2590                 'guid' => xmlify($item['guid']),
2591                 'parent_guid' => xmlify($cnv['guid']),
2592                 'parent_author_signature' => (($item['reply']) ? null : xmlify($sig)),
2593                 'author_signature' => xmlify($sig),
2594                 'text' => xmlify($body),
2595                 'created_at' => xmlify($created),
2596                 'diaspora_handle' => xmlify($myaddr),
2597                 'conversation_guid' => xmlify($cnv['guid'])
2598         );
2599
2600         if($item['reply']) {
2601                 $tpl = get_markup_template('diaspora_message.tpl');
2602                 $xmsg = replace_macros($tpl, array('$msg' => $msg));
2603         }
2604         else {
2605                 $conv['messages'] = array($msg);
2606                 $tpl = get_markup_template('diaspora_conversation.tpl');
2607                 $xmsg = replace_macros($tpl, array('$conv' => $conv));
2608         }
2609
2610         logger('diaspora_conversation: ' . print_r($xmsg,true), LOGGER_DATA);
2611
2612         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false)));
2613         //$slap = 'xml=' . urlencode(diaspora_msg_build($xmsg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],false));
2614
2615         return(diaspora_transmit($owner,$contact,$slap,false));
2616
2617
2618 }
2619
2620 function diaspora_transmit($owner,$contact,$slap,$public_batch,$queue_run=false) {
2621
2622         $enabled = intval(get_config('system','diaspora_enabled'));
2623         if(! $enabled) {
2624                 return 200;
2625         }
2626
2627         $a = get_app();
2628         $logid = random_string(4);
2629         $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
2630         if(! $dest_url) {
2631                 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
2632                 return 0;
2633         } 
2634
2635         logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
2636
2637         if( (! $queue_run) && (was_recently_delayed($contact['id'])) ) {
2638                 $return_code = 0;
2639         }
2640         else {
2641                 if(! intval(get_config('system','diaspora_test'))) {
2642                         post_url($dest_url . '/', $slap);
2643                         $return_code = $a->get_curl_code();
2644                 }
2645                 else {
2646                         logger('diaspora_transmit: test_mode');
2647                         return 200;
2648                 }
2649         }
2650         
2651         logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
2652
2653         if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
2654                 logger('diaspora_transmit: queue message');
2655
2656                 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
2657                         intval($contact['id']),
2658                         dbesc(NETWORK_DIASPORA),
2659                         dbesc($slap),
2660                         intval($public_batch)
2661                 );
2662                 if(count($r)) {
2663                         logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
2664                 }
2665                 else {
2666                         // queue message for redelivery
2667                         add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
2668                 }
2669         }
2670
2671
2672         return(($return_code) ? $return_code : (-1));
2673 }
2674
2675