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