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