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