]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
85be13a30ce65cb75bbbf6140ae4eac50cbc223b
[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
9
10 function diaspora_dispatch_public($msg) {
11
12         $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN ( SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s' ) AND `account_expired` = 0 ",
13                 dbesc(NETWORK_DIASPORA),
14                 dbesc($msg['author'])
15         );
16         if(count($r)) {
17                 foreach($r as $rr) {
18                         logger('diaspora_public: delivering to: ' . $rr['username']);
19                         diaspora_dispatch($rr,$msg);
20                 }
21         }
22         else
23                 logger('diaspora_public: no subscribers');
24 }
25
26
27
28 function diaspora_dispatch($importer,$msg) {
29
30         $ret = 0;
31
32         // php doesn't like dashes in variable names
33
34         $msg['message'] = str_replace(
35                         array('<activity_streams-photo>','</activity_streams-photo>'),
36                         array('<asphoto>','</asphoto>'),
37                         $msg['message']);
38
39
40         $parsed_xml = parse_xml_string($msg['message'],false);
41
42         $xmlbase = $parsed_xml->post;
43
44         if($xmlbase->request) {
45                 $ret = diaspora_request($importer,$xmlbase->request);
46         }
47         elseif($xmlbase->status_message) {
48                 $ret = diaspora_post($importer,$xmlbase->status_message);
49         }
50         elseif($xmlbase->profile) {
51                 $ret = diaspora_profile($importer,$xmlbase->profile);
52         }
53         elseif($xmlbase->comment) {
54                 $ret = diaspora_comment($importer,$xmlbase->comment,$msg);
55         }
56         elseif($xmlbase->like) {
57                 $ret = diaspora_like($importer,$xmlbase->like,$msg);
58         }
59         elseif($xmlbase->asphoto) {
60                 $ret = diaspora_asphoto($importer,$xmlbase->asphoto);
61         }
62         elseif($xmlbase->reshare) {
63                 $ret = diaspora_reshare($importer,$xmlbase->reshare);
64         }
65         elseif($xmlbase->retraction) {
66                 $ret = diaspora_retraction($importer,$xmlbase->retraction,$msg);
67         }
68         elseif($xmlbase->signed_retraction) {
69                 $ret = diaspora_signed_retraction($importer,$xmlbase->retraction,$msg);
70         }
71         elseif($xmlbase->photo) {
72                 $ret = diaspora_photo($importer,$xmlbase->photo,$msg);
73         }
74         else {
75                 logger('diaspora_dispatch: unknown message type: ' . print_r($xmlbase,true));
76         }
77         return $ret;
78 }
79
80 function diaspora_get_contact_by_handle($uid,$handle) {
81         $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `addr` = '%s' LIMIT 1",
82                 dbesc(NETWORK_DIASPORA),
83                 intval($uid),
84                 dbesc($handle)
85         );
86         if($r && count($r))
87                 return $r[0];
88         return false;
89 }
90
91 function find_diaspora_person_by_handle($handle) {
92         $update = false;
93         $r = q("select * from fcontact where network = '%s' and addr = '%s' limit 1",
94                 dbesc(NETWORK_DIASPORA),
95                 dbesc($handle)
96         );
97         if(count($r)) {
98                 logger('find_diaspora_person_by handle: in cache ' . print_r($r,true), LOGGER_DEBUG);
99                 // update record occasionally so it doesn't get stale
100                 $d = strtotime($r[0]['updated'] . ' +00:00');
101                 if($d > strtotime('now - 14 days'))
102                         return $r[0];
103                 $update = true;
104         }
105         logger('find_diaspora_person_by_handle: refresh',LOGGER_DEBUG);
106         require_once('include/Scrape.php');
107         $r = probe_url($handle, PROBE_DIASPORA);
108         if((count($r)) && ($r['network'] === NETWORK_DIASPORA)) {
109                 add_fcontact($r,$update);
110                 return ($r);
111         }
112         return false;
113 }
114
115
116 function get_diaspora_key($uri) {
117         logger('Fetching diaspora key for: ' . $uri);
118
119         $r = find_diaspora_person_by_handle($uri);
120         if($r)
121                 return $r['pubkey'];
122         return '';
123 }
124
125
126 function diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey) {
127         $a = get_app();
128
129         logger('diaspora_pubmsg_build: ' . $msg, LOGGER_DATA);
130
131         
132         $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
133
134 //      $b64_data = base64_encode($msg);
135 //      $b64url_data = base64url_encode($b64_data);
136
137         $b64url_data = base64url_encode($msg);
138
139         $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
140
141         $type = 'application/xml';
142         $encoding = 'base64url';
143         $alg = 'RSA-SHA256';
144
145         $signable_data = $data  . '.' . base64url_encode($type) . '.' 
146                 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
147
148         $signature = rsa_sign($signable_data,$prvkey);
149         $sig = base64url_encode($signature);
150
151 $magic_env = <<< EOT
152 <?xml version='1.0' encoding='UTF-8'?>
153 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
154   <header>
155     <author_id>$handle</author_id>
156   </header>
157   <me:env>
158     <me:encoding>base64url</me:encoding>
159     <me:alg>RSA-SHA256</me:alg>
160     <me:data type="application/xml">$data</me:data>
161     <me:sig>$sig</me:sig>
162   </me:env>
163 </diaspora>
164 EOT;
165
166         logger('diaspora_pubmsg_build: magic_env: ' . $magic_env, LOGGER_DATA);
167         return $magic_env;
168
169 }
170
171
172
173
174 function diaspora_msg_build($msg,$user,$contact,$prvkey,$pubkey,$public = false) {
175         $a = get_app();
176
177         if($public)
178                 return diaspora_pubmsg_build($msg,$user,$contact,$prvkey,$pubkey);
179
180         logger('diaspora_msg_build: ' . $msg, LOGGER_DATA);
181
182         $inner_aes_key = random_string(32);
183         $b_inner_aes_key = base64_encode($inner_aes_key);
184         $inner_iv = random_string(16);
185         $b_inner_iv = base64_encode($inner_iv);
186
187         $outer_aes_key = random_string(32);
188         $b_outer_aes_key = base64_encode($outer_aes_key);
189         $outer_iv = random_string(16);
190         $b_outer_iv = base64_encode($outer_iv);
191         
192         $handle = $user['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
193
194         $padded_data = pkcs5_pad($msg,16);
195         $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
196
197         $b64_data = base64_encode($inner_encrypted);
198
199
200         $b64url_data = base64url_encode($b64_data);
201         $data = str_replace(array("\n","\r"," ","\t"),array('','','',''),$b64url_data);
202
203         $type = 'application/xml';
204         $encoding = 'base64url';
205         $alg = 'RSA-SHA256';
206
207         $signable_data = $data  . '.' . base64url_encode($type) . '.' 
208                 . base64url_encode($encoding) . '.' . base64url_encode($alg) ;
209
210         $signature = rsa_sign($signable_data,$prvkey);
211         $sig = base64url_encode($signature);
212
213 $decrypted_header = <<< EOT
214 <decrypted_header>
215   <iv>$b_inner_iv</iv>
216   <aes_key>$b_inner_aes_key</aes_key>
217   <author_id>$handle</author_id>
218 </decrypted_header>
219 EOT;
220
221         $decrypted_header = pkcs5_pad($decrypted_header,16);
222
223         $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
224
225         $outer_json = json_encode(array('iv' => $b_outer_iv,'key' => $b_outer_aes_key));
226
227         $encrypted_outer_key_bundle = '';
228         openssl_public_encrypt($outer_json,$encrypted_outer_key_bundle,$pubkey);
229
230         $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
231
232         logger('outer_bundle: ' . $b64_encrypted_outer_key_bundle . ' key: ' . $pubkey, LOGGER_DATA);
233
234         $encrypted_header_json_object = json_encode(array('aes_key' => base64_encode($encrypted_outer_key_bundle), 
235                 'ciphertext' => base64_encode($ciphertext)));
236         $cipher_json = base64_encode($encrypted_header_json_object);
237
238         $encrypted_header = '<encrypted_header>' . $cipher_json . '</encrypted_header>';
239
240 $magic_env = <<< EOT
241 <?xml version='1.0' encoding='UTF-8'?>
242 <diaspora xmlns="https://joindiaspora.com/protocol" xmlns:me="http://salmon-protocol.org/ns/magic-env" >
243   $encrypted_header
244   <me:env>
245     <me:encoding>base64url</me:encoding>
246     <me:alg>RSA-SHA256</me:alg>
247     <me:data type="application/xml">$data</me:data>
248     <me:sig>$sig</me:sig>
249   </me:env>
250 </diaspora>
251 EOT;
252
253         logger('diaspora_msg_build: magic_env: ' . $magic_env, LOGGER_DATA);
254         return $magic_env;
255
256 }
257
258 /**
259  *
260  * diaspora_decode($importer,$xml)
261  *   array $importer -> from user table
262  *   string $xml -> urldecoded Diaspora salmon 
263  *
264  * Returns array
265  * 'message' -> decoded Diaspora XML message
266  * 'author' -> author diaspora handle
267  * 'key' -> author public key (converted to pkcs#8)
268  *
269  * Author and key are used elsewhere to save a lookup for verifying replies and likes
270  */
271
272
273 function diaspora_decode($importer,$xml) {
274
275         $public = false;
276         $basedom = parse_xml_string($xml);
277
278         $children = $basedom->children('https://joindiaspora.com/protocol');
279
280         if($children->header) {
281                 $public = true;
282                 $author_link = str_replace('acct:','',$children->header->author_id);
283         }
284         else {
285
286                 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
287         
288                 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
289                 $ciphertext = base64_decode($encrypted_header->ciphertext);
290
291                 $outer_key_bundle = '';
292                 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
293
294                 $j_outer_key_bundle = json_decode($outer_key_bundle);
295
296                 $outer_iv = base64_decode($j_outer_key_bundle->iv);
297                 $outer_key = base64_decode($j_outer_key_bundle->key);
298
299                 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
300
301
302                 $decrypted = pkcs5_unpad($decrypted);
303
304                 /**
305                  * $decrypted now contains something like
306                  *
307                  *  <decrypted_header>
308                  *     <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
309                  *     <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
310
311 ***** OBSOLETE
312
313                  *     <author>
314                  *       <name>Ryan Hughes</name>
315                  *       <uri>acct:galaxor@diaspora.pirateship.org</uri>
316                  *     </author>
317
318 ***** CURRENT
319
320                  *     <author_id>galaxor@diaspora.priateship.org</author_id>
321
322 ***** END DIFFS
323
324                  *  </decrypted_header>
325                  */
326
327                 logger('decrypted: ' . $decrypted, LOGGER_DEBUG);
328                 $idom = parse_xml_string($decrypted,false);
329
330                 $inner_iv = base64_decode($idom->iv);
331                 $inner_aes_key = base64_decode($idom->aes_key);
332
333                 $author_link = str_replace('acct:','',$idom->author_id);
334
335         }
336
337         $dom = $basedom->children(NAMESPACE_SALMON_ME);
338
339         // figure out where in the DOM tree our data is hiding
340
341         if($dom->provenance->data)
342                 $base = $dom->provenance;
343         elseif($dom->env->data)
344                 $base = $dom->env;
345         elseif($dom->data)
346                 $base = $dom;
347         
348         if(! $base) {
349                 logger('mod-diaspora: unable to locate salmon data in xml ');
350                 http_status_exit(400);
351         }
352
353
354         // Stash the signature away for now. We have to find their key or it won't be good for anything.
355         $signature = base64url_decode($base->sig);
356
357         // unpack the  data
358
359         // strip whitespace so our data element will return to one big base64 blob
360         $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
361
362
363         // stash away some other stuff for later
364
365         $type = $base->data[0]->attributes()->type[0];
366         $keyhash = $base->sig[0]->attributes()->keyhash[0];
367         $encoding = $base->encoding;
368         $alg = $base->alg;
369
370
371         $signed_data = $data  . '.' . base64url_encode($type) . '.' . base64url_encode($encoding) . '.' . base64url_encode($alg);
372
373
374         // decode the data
375         $data = base64url_decode($data);
376
377
378         if($public) {
379                 $inner_decrypted = $data;
380         }
381         else {
382
383                 // Decode the encrypted blob
384
385                 $inner_encrypted = base64_decode($data);
386                 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
387                 $inner_decrypted = pkcs5_unpad($inner_decrypted);
388         }
389
390         if(! $author_link) {
391                 logger('mod-diaspora: Could not retrieve author URI.');
392                 http_status_exit(400);
393         }
394
395         // Once we have the author URI, go to the web and try to find their public key
396         // (first this will look it up locally if it is in the fcontact cache)
397         // This will also convert diaspora public key from pkcs#1 to pkcs#8
398
399         logger('mod-diaspora: Fetching key for ' . $author_link );
400         $key = get_diaspora_key($author_link);
401
402         if(! $key) {
403                 logger('mod-diaspora: Could not retrieve author key.');
404                 http_status_exit(400);
405         }
406
407         $verify = rsa_verify($signed_data,$signature,$key);
408
409         if(! $verify) {
410                 logger('mod-diaspora: Message did not verify. Discarding.');
411                 http_status_exit(400);
412         }
413
414         logger('mod-diaspora: Message verified.');
415
416         return array('message' => $inner_decrypted, 'author' => $author_link, 'key' => $key);
417
418 }
419
420         
421 function diaspora_request($importer,$xml) {
422
423         $sender_handle = unxmlify($xml->sender_handle);
424         $recipient_handle = unxmlify($xml->recipient_handle);
425
426         if(! $sender_handle || ! $recipient_handle)
427                 return;
428          
429         $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
430
431         if($contact) {
432
433                 // perhaps we were already sharing with this person. Now they're sharing with us.
434                 // That makes us friends.
435
436                 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
437                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
438                                 intval(CONTACT_IS_FRIEND),
439                                 intval($contact['id']),
440                                 intval($importer['uid'])
441                         );
442                 }
443                 // send notification?
444                 return;
445         }
446         
447         $ret = find_diaspora_person_by_handle($sender_handle);
448
449
450         if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
451                 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
452                 return;
453         }
454
455         $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
456
457         $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
458                 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
459                 intval($importer['uid']),
460                 dbesc($ret['network']),
461                 dbesc($ret['addr']),
462                 datetime_convert(),
463                 dbesc($ret['url']),
464                 dbesc(normalise_link($ret['url'])),
465                 dbesc($batch),
466                 dbesc($ret['name']),
467                 dbesc($ret['nick']),
468                 dbesc($ret['photo']),
469                 dbesc($ret['pubkey']),
470                 dbesc($ret['notify']),
471                 dbesc($ret['poll']),
472                 1,
473                 2
474         );
475                  
476         // find the contact record we just created
477
478         $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
479
480         $hash = random_string() . (string) time();   // Generate a confirm_key
481         
482         if($contact_record) {
483                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
484                         VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
485                         intval($importer['uid']),
486                         intval($contact_record['id']),
487                         0,
488                         0,
489                         dbesc( t('Sharing notification from Diaspora network')),
490                         dbesc($hash),
491                         dbesc(datetime_convert())
492                 );
493         }
494
495         return;
496 }
497
498 function diaspora_post($importer,$xml) {
499
500         $a = get_app();
501         $guid = notags(unxmlify($xml->guid));
502         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
503
504         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
505         if(! $contact)
506                 return;
507
508         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
509                 logger('diaspora_post: Ignoring this author.');
510                 return 202;
511         }
512
513         $message_id = $diaspora_handle . ':' . $guid;
514         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
515                 intval($importer['uid']),
516                 dbesc($message_id),
517                 dbesc($guid)
518         );
519         if(count($r)) {
520                 logger('diaspora_post: message exists: ' . $guid);
521                 return;
522         }
523
524     // allocate a guid on our system - we aren't fixing any collisions.
525         // we're ignoring them
526
527         $g = q("select * from guid where guid = '%s' limit 1",
528                 dbesc($guid)
529         );
530         if(! count($g)) {
531                 q("insert into guid ( guid ) values ( '%s' )",
532                         dbesc($guid)
533                 );
534         }
535
536         $created = unxmlify($xml->created_at);
537         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
538
539         $body = diaspora2bb($xml->raw_message);
540
541         $datarray = array();
542
543         $str_tags = '';
544
545         $tags = get_tags($body);
546
547         if(count($tags)) {
548                 foreach($tags as $tag) {
549                         if(strpos($tag,'#') === 0) {
550                                 if(strpos($tag,'[url='))
551                                         continue;
552                                 $basetag = str_replace('_',' ',substr($tag,1));
553                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
554                                 if(strlen($str_tags))
555                                         $str_tags .= ',';
556                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
557                                 continue;
558                         }
559                 }
560         }
561         
562         $datarray['uid'] = $importer['uid'];
563         $datarray['contact-id'] = $contact['id'];
564         $datarray['wall'] = 0;
565         $datarray['guid'] = $guid;
566         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
567         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
568         $datarray['private'] = $private;
569         $datarray['parent'] = 0;
570         $datarray['owner-name'] = $contact['name'];
571         $datarray['owner-link'] = $contact['url'];
572         $datarray['owner-avatar'] = $contact['thumb'];
573         $datarray['author-name'] = $contact['name'];
574         $datarray['author-link'] = $contact['url'];
575         $datarray['author-avatar'] = $contact['thumb'];
576         $datarray['body'] = $body;
577         $datarray['tag'] = $str_tags;
578         $datarray['app']  = 'Diaspora';
579
580         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
581
582         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
583
584         $message_id = item_store($datarray);
585
586         if($message_id) {
587                 q("update item set plink = '%s' where id = %d limit 1",
588                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
589                         intval($message_id)
590                 );
591         }
592
593         return;
594
595 }
596
597 function diaspora_reshare($importer,$xml) {
598
599         logger('diaspora_reshare: init: ' . print_r($xml,true));
600
601         $a = get_app();
602         $guid = notags(unxmlify($xml->guid));
603         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
604
605
606         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
607         if(! $contact)
608                 return;
609
610         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
611                 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
612                 return 202;
613         }
614
615         $message_id = $diaspora_handle . ':' . $guid;
616         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
617                 intval($importer['uid']),
618                 dbesc($message_id),
619                 dbesc($guid)
620         );
621         if(count($r)) {
622                 logger('diaspora_reshare: message exists: ' . $guid);
623                 return;
624         }
625
626         $orig_author = notags(unxmlify($xml->root_diaspora_id));
627         $orig_guid = notags(unxmlify($xml->root_guid));
628
629         $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
630         $x = fetch_url($source_url);
631         if(! $x)
632                 $x = fetch_url(str_replace('https://','http://',$source_url));
633         if(! $x) {
634                 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
635                 return;
636         }
637         logger('diaspora_reshare: source: ' . $x);
638
639         $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
640         $source_xml = parse_xml_string($x,false);
641
642         if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
643                 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
644                 $body = scale_diaspora_images($body,false);
645         }
646         elseif($source_xml->post->asphoto->image_url) {
647                 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
648                 $body = scale_diaspora_images($body);
649         }
650         elseif($source_xml->post->status_message) {
651                 $body = diaspora2bb($source_xml->post->status_message->raw_message);
652                 $body = scale_diaspora_images($body);
653
654         }
655         else {
656                 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
657                 return;
658         }
659         if(! $body) {
660                 logger('diaspora_reshare: empty body: source= ' . $x);
661                 return;
662         }
663
664         $person = find_diaspora_person_by_handle($orig_author);
665
666         if(is_array($person) && x($person,'name') && x($person,'url'))
667                 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
668         else
669                 $details = $orig_author;
670         
671         $prefix = '&#x2672; ' . $details . "\n"; 
672
673
674     // allocate a guid on our system - we aren't fixing any collisions.
675         // we're ignoring them
676
677         $g = q("select * from guid where guid = '%s' limit 1",
678                 dbesc($guid)
679         );
680         if(! count($g)) {
681                 q("insert into guid ( guid ) values ( '%s' )",
682                         dbesc($guid)
683                 );
684         }
685
686         $created = unxmlify($xml->created_at);
687         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
688
689         $datarray = array();
690
691         $str_tags = '';
692
693         $tags = get_tags($body);
694
695         if(count($tags)) {
696                 foreach($tags as $tag) {
697                         if(strpos($tag,'#') === 0) {
698                                 if(strpos($tag,'[url='))
699                                         continue;
700                                 $basetag = str_replace('_',' ',substr($tag,1));
701                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
702                                 if(strlen($str_tags))
703                                         $str_tags .= ',';
704                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
705                                 continue;
706                         }
707                 }
708         }
709         
710         $datarray['uid'] = $importer['uid'];
711         $datarray['contact-id'] = $contact['id'];
712         $datarray['wall'] = 0;
713         $datarray['guid'] = $guid;
714         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
715         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
716         $datarray['private'] = $private;
717         $datarray['parent'] = 0;
718         $datarray['owner-name'] = $contact['name'];
719         $datarray['owner-link'] = $contact['url'];
720         $datarray['owner-avatar'] = $contact['thumb'];
721         $datarray['author-name'] = $contact['name'];
722         $datarray['author-link'] = $contact['url'];
723         $datarray['author-avatar'] = $contact['thumb'];
724         $datarray['body'] = $prefix . $body;
725         $datarray['tag'] = $str_tags;
726         $datarray['app']  = 'Diaspora';
727
728         $message_id = item_store($datarray);
729
730         if($message_id) {
731                 q("update item set plink = '%s' where id = %d limit 1",
732                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
733                         intval($message_id)
734                 );
735         }
736
737         return;
738
739 }
740
741
742 function diaspora_asphoto($importer,$xml) {
743         logger('diaspora_asphoto called');
744
745         $a = get_app();
746         $guid = notags(unxmlify($xml->guid));
747         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
748
749         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
750         if(! $contact)
751                 return;
752
753         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
754                 logger('diaspora_asphoto: Ignoring this author.');
755                 return 202;
756         }
757
758         $message_id = $diaspora_handle . ':' . $guid;
759         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
760                 intval($importer['uid']),
761                 dbesc($message_id),
762                 dbesc($guid)
763         );
764         if(count($r)) {
765                 logger('diaspora_asphoto: message exists: ' . $guid);
766                 return;
767         }
768
769     // allocate a guid on our system - we aren't fixing any collisions.
770         // we're ignoring them
771
772         $g = q("select * from guid where guid = '%s' limit 1",
773                 dbesc($guid)
774         );
775         if(! count($g)) {
776                 q("insert into guid ( guid ) values ( '%s' )",
777                         dbesc($guid)
778                 );
779         }
780
781         $created = unxmlify($xml->created_at);
782         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
783
784         if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
785                 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
786                 $body = scale_diaspora_images($body,false);
787         }
788         elseif($xml->image_url) {
789                 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
790                 $body = scale_diaspora_images($body);
791         }
792         else {
793                 logger('diaspora_asphoto: no photo url found.');
794                 return;
795         }
796
797         $datarray = array();
798
799         
800         $datarray['uid'] = $importer['uid'];
801         $datarray['contact-id'] = $contact['id'];
802         $datarray['wall'] = 0;
803         $datarray['guid'] = $guid;
804         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
805         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
806         $datarray['private'] = $private;
807         $datarray['parent'] = 0;
808         $datarray['owner-name'] = $contact['name'];
809         $datarray['owner-link'] = $contact['url'];
810         $datarray['owner-avatar'] = $contact['thumb'];
811         $datarray['author-name'] = $contact['name'];
812         $datarray['author-link'] = $contact['url'];
813         $datarray['author-avatar'] = $contact['thumb'];
814         $datarray['body'] = $body;
815         
816         $datarray['app']  = 'Diaspora/Cubbi.es';
817
818         $message_id = item_store($datarray);
819
820         if($message_id) {
821                 q("update item set plink = '%s' where id = %d limit 1",
822                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
823                         intval($message_id)
824                 );
825         }
826
827         return;
828
829 }
830
831
832
833
834
835
836 function diaspora_comment($importer,$xml,$msg) {
837
838         $a = get_app();
839         $guid = notags(unxmlify($xml->guid));
840         $parent_guid = notags(unxmlify($xml->parent_guid));
841         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
842         $target_type = notags(unxmlify($xml->target_type));
843         $text = unxmlify($xml->text);
844         $author_signature = notags(unxmlify($xml->author_signature));
845
846         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
847
848         $text = $xml->text;
849
850         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
851         if(! $contact) {
852                 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
853                 return;
854         }
855
856         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
857                 logger('diaspora_comment: Ignoring this author.');
858                 return 202;
859         }
860
861         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
862                 intval($importer['uid']),
863                 dbesc($guid)
864         );
865         if(count($r)) {
866                 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
867                 return;
868         }
869
870         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
871                 intval($importer['uid']),
872                 dbesc($parent_guid)
873         );
874         if(! count($r)) {
875                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
876                 return;
877         }
878         $parent_item = $r[0];
879
880         $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
881
882         $author_signature = base64_decode($author_signature);
883
884         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
885                 $person = $contact;
886                 $key = $msg['key'];
887         }
888         else {
889                 $person = find_diaspora_person_by_handle($diaspora_handle);     
890
891                 if(is_array($person) && x($person,'pubkey'))
892                         $key = $person['pubkey'];
893                 else {
894                         logger('diaspora_comment: unable to find author details');
895                         return;
896                 }
897         }
898
899         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
900                 logger('diaspora_comment: verification failed.');
901                 return;
902         }
903
904         if($parent_author_signature) {
905                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
906
907                 $parent_author_signature = base64_decode($parent_author_signature);
908
909                 $key = $msg['key'];
910
911                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
912                         logger('diaspora_comment: owner verification failed.');
913                         return;
914                 }
915         }
916
917         // Phew! Everything checks out. Now create an item.
918
919         $body = diaspora2bb($text);
920
921         $message_id = $diaspora_handle . ':' . $guid;
922
923         $datarray = array();
924
925         $str_tags = '';
926
927         $tags = get_tags($body);
928
929         if(count($tags)) {
930                 foreach($tags as $tag) {
931                         if(strpos($tag,'#') === 0) {
932                                 if(strpos($tag,'[url='))
933                                         continue;
934                                 $basetag = str_replace('_',' ',substr($tag,1));
935                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
936                                 if(strlen($str_tags))
937                                         $str_tags .= ',';
938                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
939                                 continue;
940                         }
941                 }
942         }
943
944         $datarray['uid'] = $importer['uid'];
945         $datarray['contact-id'] = $contact['id'];
946         $datarray['wall'] = $parent_item['wall'];
947         $datarray['gravity'] = GRAVITY_COMMENT;
948         $datarray['guid'] = $guid;
949         $datarray['uri'] = $message_id;
950         $datarray['parent-uri'] = $parent_item['uri'];
951
952         // No timestamps for comments? OK, we'll the use current time.
953         $datarray['created'] = $datarray['edited'] = datetime_convert();
954         $datarray['private'] = $parent_item['private'];
955
956         $datarray['owner-name'] = $parent_item['owner-name'];
957         $datarray['owner-link'] = $parent_item['owner-link'];
958         $datarray['owner-avatar'] = $parent_item['owner-avatar'];
959
960         $datarray['author-name'] = $person['name'];
961         $datarray['author-link'] = $person['url'];
962         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
963         $datarray['body'] = $body;
964         $datarray['tag'] = $str_tags;
965
966         // We can't be certain what the original app is if the message is relayed.
967         if(($parent_item['origin']) && (! $parent_author_signature)) 
968                 $datarray['app']  = 'Diaspora';
969
970         $message_id = item_store($datarray);
971
972         if($message_id) {
973                 q("update item set plink = '%s' where id = %d limit 1",
974                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
975                         intval($message_id)
976                 );
977         }
978
979         if(($parent_item['origin']) && (! $parent_author_signature)) {
980                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
981                         intval($message_id),
982                         dbesc($author_signed_data),
983                         dbesc(base64_encode($author_signature)),
984                         dbesc($diaspora_handle)
985                 );
986
987                 // if the message isn't already being relayed, notify others
988                 // the existence of parent_author_signature means the parent_author or owner
989                 // is already relaying.
990
991                 proc_run('php','include/notifier.php','comment',$message_id);
992         }
993         return;
994 }
995
996 function diaspora_photo($importer,$xml,$msg) {
997
998         $a = get_app();
999         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1000
1001         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1002
1003         $status_message_guid = notags(unxmlify($xml->status_message_guid));
1004
1005         $guid = notags(unxmlify($xml->guid));
1006
1007         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1008
1009         $public = notags(unxmlify($xml->public));
1010
1011         $created_at = notags(unxmlify($xml_created_at));
1012
1013
1014         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1015         if(! $contact)
1016                 return;
1017
1018         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1019                 logger('diaspora_photo: Ignoring this author.');
1020                 return 202;
1021         }
1022
1023         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1024                 intval($importer['uid']),
1025                 dbesc($status_message_guid)
1026         );
1027         if(! count($r)) {
1028                 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1029                 return;
1030         }
1031         $parent_item = $r[0];
1032
1033         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1034
1035         $link_text = scale_diaspora_images($link_text);
1036
1037         if(strpos($parent_item['body'],$link_text) === false) {
1038                 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1039                         dbesc($link_text . $parent_item['body']),
1040                         intval($parent_item['id']),
1041                         intval($parent_item['uid'])
1042                 );
1043         }
1044
1045         return;
1046 }
1047
1048
1049
1050
1051 function diaspora_like($importer,$xml,$msg) {
1052
1053         $a = get_app();
1054         $guid = notags(unxmlify($xml->guid));
1055         $parent_guid = notags(unxmlify($xml->parent_guid));
1056         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1057         $target_type = notags(unxmlify($xml->target_type));
1058         $positive = notags(unxmlify($xml->positive));
1059         $author_signature = notags(unxmlify($xml->author_signature));
1060
1061         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1062
1063         // likes on comments not supported here and likes on photos not supported by Diaspora
1064
1065         if($target_type !== 'Post')
1066                 return;
1067
1068         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1069         if(! $contact) {
1070                 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1071                 return;
1072         }
1073
1074         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1075                 logger('diaspora_like: Ignoring this author.');
1076                 return 202;
1077         }
1078
1079         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1080                 intval($importer['uid']),
1081                 dbesc($parent_guid)
1082         );
1083         if(! count($r)) {
1084                 logger('diaspora_like: parent item not found: ' . $guid);
1085                 return;
1086         }
1087
1088         $parent_item = $r[0];
1089
1090         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1091                 intval($importer['uid']),
1092                 dbesc($guid)
1093         );
1094         if(count($r)) {
1095                 if($positive === 'true') {
1096                         logger('diaspora_like: duplicate like: ' . $guid);
1097                         return;
1098                 } 
1099                 if($positive === 'false') {
1100                         q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1101                                 intval($r[0]['id']),
1102                                 intval($importer['uid'])
1103                         );
1104                         // FIXME
1105                         //  send notification via proc_run()
1106                         return;
1107                 }
1108         }
1109         if($positive === 'false') {
1110                 logger('diaspora_like: unlike received with no corresponding like');
1111                 return; 
1112         }
1113
1114         $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1115
1116         $author_signature = base64_decode($author_signature);
1117
1118         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1119                 $person = $contact;
1120                 $key = $msg['key'];
1121         }
1122         else {
1123                 $person = find_diaspora_person_by_handle($diaspora_handle);     
1124                 if(is_array($person) && x($person,'pubkey'))
1125                         $key = $person['pubkey'];
1126                 else {
1127                         logger('diaspora_like: unable to find author details');
1128                         return;
1129                 }
1130         }
1131
1132         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1133                 logger('diaspora_like: verification failed.');
1134                 return;
1135         }
1136
1137         if($parent_author_signature) {
1138
1139                 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1140
1141                 $parent_author_signature = base64_decode($parent_author_signature);
1142
1143                 $key = $msg['key'];
1144
1145                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1146                         logger('diaspora_like: owner verification failed.');
1147                         return;
1148                 }
1149         }
1150
1151         // Phew! Everything checks out. Now create an item.
1152
1153         $uri = $diaspora_handle . ':' . $guid;
1154
1155         $activity = ACTIVITY_LIKE;
1156         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1157         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
1158         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1159         $body = $parent_item['body'];
1160
1161         $obj = <<< EOT
1162
1163         <object>
1164                 <type>$objtype</type>
1165                 <local>1</local>
1166                 <id>{$parent_item['uri']}</id>
1167                 <link>$link</link>
1168                 <title></title>
1169                 <content>$body</content>
1170         </object>
1171 EOT;
1172         $bodyverb = t('%1$s likes %2$s\'s %3$s');
1173
1174         $arr = array();
1175
1176         $arr['uri'] = $uri;
1177         $arr['uid'] = $importer['uid'];
1178         $arr['guid'] = $guid;
1179         $arr['contact-id'] = $contact['id'];
1180         $arr['type'] = 'activity';
1181         $arr['wall'] = $parent_item['wall'];
1182         $arr['gravity'] = GRAVITY_LIKE;
1183         $arr['parent'] = $parent_item['id'];
1184         $arr['parent-uri'] = $parent_item['uri'];
1185
1186         $arr['owner-name'] = $parent_item['name'];
1187         $arr['owner-link'] = $parent_item['url'];
1188         $arr['owner-avatar'] = $parent_item['thumb'];
1189
1190         $arr['author-name'] = $person['name'];
1191         $arr['author-link'] = $person['url'];
1192         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1193         
1194         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1195         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1196         $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1197         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
1198
1199         $arr['app']  = 'Diaspora';
1200
1201         $arr['private'] = $parent_item['private'];
1202         $arr['verb'] = $activity;
1203         $arr['object-type'] = $objtype;
1204         $arr['object'] = $obj;
1205         $arr['visible'] = 1;
1206         $arr['unseen'] = 1;
1207         $arr['last-child'] = 0;
1208
1209         $message_id = item_store($arr);
1210
1211
1212         if($message_id) {
1213                 q("update item set plink = '%s' where id = %d limit 1",
1214                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1215                         intval($message_id)
1216                 );
1217         }
1218
1219         if(! $parent_author_signature) {
1220                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1221                         intval($message_id),
1222                         dbesc($author_signed_data),
1223                         dbesc(base64_encode($author_signature)),
1224                         dbesc($diaspora_handle)
1225                 );
1226         }
1227
1228         // if the message isn't already being relayed, notify others
1229         // the existence of parent_author_signature means the parent_author or owner
1230         // is already relaying. The parent_item['origin'] indicates the message was created on our system
1231
1232         if(($parent_item['origin']) && (! $parent_author_signature))
1233                 proc_run('php','include/notifier.php','comment',$message_id);
1234
1235         return;
1236 }
1237
1238 function diaspora_retraction($importer,$xml) {
1239
1240         $guid = notags(unxmlify($xml->guid));
1241         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1242         $type = notags(unxmlify($xml->type));
1243
1244         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1245         if(! $contact)
1246                 return;
1247
1248         if($type === 'Person') {
1249                 contact_remove($contact['id']);
1250         }
1251         elseif($type === 'Post') {
1252                 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1253                         dbesc('guid'),
1254                         intval($importer['uid'])
1255                 );
1256                 if(count($r)) {
1257                         if(link_compare($r[0]['author-link'],$contact['url'])) {
1258                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1259                                         dbesc(datetime_convert()),                      
1260                                         intval($r[0]['id'])
1261                                 );
1262                         }
1263                 }
1264         }
1265
1266         return 202;
1267         // NOTREACHED
1268 }
1269
1270 function diaspora_signed_retraction($importer,$xml) {
1271
1272         $guid = notags(unxmlify($xml->target_guid));
1273         $diaspora_handle = notags(unxmlify($xml->sender_handle));
1274         $type = notags(unxmlify($xml->target_type));
1275         $sig = notags(unxmlify($xml->target_author_signature));
1276
1277         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1278         if(! $contact)
1279                 return;
1280
1281         // this may not yet work for comments. Need to see how the relaying works
1282         // and figure out who signs it.
1283
1284
1285         $signed_data = $guid . ';' . $type ;
1286
1287         $sig = base64_decode($sig);
1288
1289         $key = $msg['key'];
1290
1291         if(! rsa_verify($signed_data,$sig,$key,'sha256')) {
1292                 logger('diaspora_signed_retraction: owner verification failed.' . print_r($msg,true));
1293                 return;
1294         }
1295
1296         if($type === 'StatusMessage') {
1297                 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1298                         dbesc('guid'),
1299                         intval($importer['uid'])
1300                 );
1301                 if(count($r)) {
1302                         if(link_compare($r[0]['author-link'],$contact['url'])) {
1303                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1304                                         dbesc(datetime_convert()),                      
1305                                         intval($r[0]['id'])
1306                                 );
1307                         }
1308                 }
1309         }
1310
1311         return 202;
1312         // NOTREACHED
1313 }
1314
1315 function diaspora_profile($importer,$xml) {
1316
1317         $a = get_app();
1318         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1319
1320         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1321         if(! $contact)
1322                 return;
1323
1324         if($contact['blocked']) {
1325                 logger('diaspora_post: Ignoring this author.');
1326                 return 202;
1327         }
1328
1329         $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1330         $image_url = unxmlify($xml->image_url);
1331         $birthday = unxmlify($xml->birthday);
1332
1333         $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE  `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1334                 intval($importer['uid']),
1335                 intval($contact['id'])
1336         );
1337         $oldphotos = ((count($r)) ? $r : null);
1338
1339         require_once('include/Photo.php');
1340
1341         $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1342         
1343         // Generic birthday. We don't know the timezone. The year is irrelevant. 
1344
1345         $birthday = str_replace('1000','1901',$birthday);
1346
1347         $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1348
1349         $r = q("UPDATE `contact` SET `name` = '%s', `name-date` = '%s', `photo` = '%s', `thumb` = '%s', `micro` = '%s', `avatar-date` = '%s' , `bd` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1",
1350                 dbesc($name),
1351                 dbesc(datetime_convert()),
1352                 dbesc($images[0]),
1353                 dbesc($images[1]),
1354                 dbesc($images[2]),
1355                 dbesc(datetime_convert()),
1356                 dbesc($birthday),
1357                 intval($contact['id']),
1358                 intval($importer['uid'])
1359         ); 
1360
1361         if($r) {
1362                 if($oldphotos) {
1363                         foreach($oldphotos as $ph) {
1364                                 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1365                                         intval($importer['uid']),
1366                                         intval($contact['id']),
1367                                         dbesc($ph['resource-id'])
1368                                 );
1369                         }
1370                 }
1371         }       
1372
1373         return;
1374
1375 }
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398 function diaspora_share($me,$contact) {
1399         $a = get_app();
1400         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1401         $theiraddr = $contact['addr'];
1402
1403         $tpl = get_markup_template('diaspora_share.tpl');
1404         $msg = replace_macros($tpl, array(
1405                 '$sender' => $myaddr,
1406                 '$recipient' => $theiraddr
1407         ));
1408
1409         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1410
1411         return(diaspora_transmit($owner,$contact,$slap, false));
1412 }
1413
1414 function diaspora_unshare($me,$contact) {
1415
1416         $a = get_app();
1417         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1418
1419         $tpl = get_markup_template('diaspora_retract.tpl');
1420         $msg = replace_macros($tpl, array(
1421                 '$guid'   => $me['guid'],
1422                 '$type'   => 'Person',
1423                 '$handle' => $myaddr
1424         ));
1425
1426         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1427
1428         return(diaspora_transmit($owner,$contact,$slap, false));
1429
1430 }
1431
1432
1433
1434 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1435
1436         $a = get_app();
1437         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1438         $theiraddr = $contact['addr'];
1439
1440         $images = array();
1441
1442         $body = $item['body'];
1443
1444 /*
1445         // We're trying to match Diaspora's split message/photo protocol but
1446         // all the photos are displayed on D* as links and not img's - even
1447         // though we're sending pretty much precisely what they send us when
1448         // doing the same operation.  
1449         // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1450         // which seems to get through intact.
1451
1452         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1453         if($cnt) {
1454                 foreach($matches as $mtch) {
1455                         $detail = array();
1456                         $detail['str'] = $mtch[0];
1457                         $detail['path'] = dirname($mtch[1]) . '/';
1458                         $detail['file'] = basename($mtch[1]);
1459                         $detail['guid'] = $item['guid'];
1460                         $detail['handle'] = $myaddr;
1461                         $images[] = $detail;
1462                         $body = str_replace($detail['str'],$mtch[1],$body);
1463                 }
1464         }       
1465 */
1466
1467         $body = xmlify(html_entity_decode(bb2diaspora($body)));
1468
1469         if($item['attach']) {
1470                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1471                 if(cnt) {
1472                         $body .= "\n" . t('Attachments:') . "\n";
1473                         foreach($matches as $mtch) {
1474                                 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1475                         }
1476                 }
1477         }       
1478
1479
1480         $public = (($item['private']) ? 'false' : 'true');
1481
1482         require_once('include/datetime.php');
1483         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1484
1485         $tpl = get_markup_template('diaspora_post.tpl');
1486         $msg = replace_macros($tpl, array(
1487                 '$body' => $body,
1488                 '$guid' => $item['guid'],
1489                 '$handle' => xmlify($myaddr),
1490                 '$public' => $public,
1491                 '$created' => $created
1492         ));
1493
1494         logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1495
1496         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1497
1498         $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1499
1500         if(count($images)) {
1501                 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1502         }
1503
1504         return $return_code;
1505 }
1506
1507
1508 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1509         $a = get_app();
1510         if(! count($images))
1511                 return;
1512         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1513
1514         $tpl = get_markup_template('diaspora_photo.tpl');
1515         foreach($images as $image) {
1516                 if(! stristr($image['path'],$mysite))
1517                         continue;
1518                 $resource = str_replace('.jpg','',$image['file']);
1519                 $resource = substr($resource,0,strpos($resource,'-'));
1520
1521                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1522                         dbesc($resource),
1523                         intval($owner['uid'])
1524                 );
1525                 if(! count($r))
1526                         continue;
1527                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1528                 $msg = replace_macros($tpl,array(               
1529                         '$path' => xmlify($image['path']),
1530                         '$filename' => xmlify($image['file']),
1531                         '$msg_guid' => xmlify($image['guid']),
1532                         '$guid' => xmlify($r[0]['guid']),
1533                         '$handle' => xmlify($image['handle']),
1534                         '$public' => xmlify($public),
1535                         '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1536                 ));
1537
1538
1539                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1540                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1541
1542                 diaspora_transmit($owner,$contact,$slap,$public_batch);
1543         }
1544
1545 }
1546
1547 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1548
1549         $a = get_app();
1550         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1551         $theiraddr = $contact['addr'];
1552
1553         $p = q("select guid from item where parent = %d limit 1",
1554                 $item['parent']
1555         );
1556         if(count($p))
1557                 $parent_guid = $p[0]['guid'];
1558         else
1559                 return;
1560
1561         if($item['verb'] === ACTIVITY_LIKE) {
1562                 $tpl = get_markup_template('diaspora_like.tpl');
1563                 $like = true;
1564                 $target_type = 'Post';
1565                 $positive = (($item['deleted']) ? 'false' : 'true');
1566         }
1567         else {
1568                 $tpl = get_markup_template('diaspora_comment.tpl');
1569                 $like = false;
1570         }
1571
1572         $text = html_entity_decode(bb2diaspora($item['body']));
1573
1574         // sign it
1575
1576         if($like)
1577                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1578         else
1579                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1580
1581         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1582
1583         $msg = replace_macros($tpl,array(
1584                 '$guid' => xmlify($item['guid']),
1585                 '$parent_guid' => xmlify($parent_guid),
1586                 '$target_type' =>xmlify($target_type),
1587                 '$authorsig' => xmlify($authorsig),
1588                 '$body' => xmlify($text),
1589                 '$positive' => xmlify($positive),
1590                 '$handle' => xmlify($myaddr)
1591         ));
1592
1593         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1594
1595         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1596
1597         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1598 }
1599
1600
1601 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1602
1603
1604         $a = get_app();
1605         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1606         $theiraddr = $contact['addr'];
1607
1608
1609         $p = q("select guid from item where parent = %d limit 1",
1610                 $item['parent']
1611         );
1612         if(count($p))
1613                 $parent_guid = $p[0]['guid'];
1614         else
1615                 return;
1616
1617         if($item['verb'] === ACTIVITY_LIKE) {
1618                 $tpl = get_markup_template('diaspora_like_relay.tpl');
1619                 $like = true;
1620                 $target_type = 'Post';
1621                 $positive = (($item['deleted']) ? 'false' : 'true');
1622         }
1623         else {
1624                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1625                 $like = false;
1626         }
1627
1628         $body = $item['body'];
1629
1630         $text = html_entity_decode(bb2diaspora($body));
1631
1632         // fetch the original signature if somebody sent the post to us to relay
1633         // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1634         // action. It wasn't needed. In that case create the original signature and the 
1635         // owner (parent author) signature
1636         // comments from other networks will be relayed under our name, with a brief 
1637         // preamble to describe what's happening and noting the real author
1638
1639         $r = q("select * from sign where iid = %d limit 1",
1640                 intval($item['id'])
1641         );
1642         if(count($r)) { 
1643                 $orig_sign = $r[0];
1644                 $signed_text = $orig_sign['signed_text'];
1645                 $authorsig = $orig_sign['signature'];
1646                 $handle = $orig_sign['signer'];
1647         }
1648         else {
1649
1650                 $itemcontact = q("select * from contact where `id` = %d limit 1",
1651                         intval($item['contact-id'])
1652                 );
1653                 if(count($itemcontact)) {
1654                         if(! $itemcontact[0]['self']) {
1655                                 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1656                                         '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',  
1657                                         network_to_name($itemcontact['network'])) . "\n";
1658                                 $body = $prefix . $body;
1659                         }
1660                 }
1661                 else {
1662
1663                         if($like)
1664                                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1665                         else
1666                                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1667
1668                         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1669
1670                         q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1671                                 intval($item['id']),
1672                                 dbesc($signed_text),
1673                                 dbesc(base64_encode($authorsig)),
1674                                 dbesc($myaddr)
1675                         );
1676                         $handle = $myaddr;
1677                 }
1678         }
1679
1680         // sign it
1681
1682         $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1683
1684         $msg = replace_macros($tpl,array(
1685                 '$guid' => xmlify($item['guid']),
1686                 '$parent_guid' => xmlify($parent_guid),
1687                 '$target_type' =>xmlify($target_type),
1688                 '$authorsig' => xmlify($orig_sign['signature']),
1689                 '$parentsig' => xmlify($parentauthorsig),
1690                 '$body' => xmlify($text),
1691                 '$positive' => xmlify($positive),
1692                 '$handle' => xmlify($handle)
1693         ));
1694
1695         logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1696
1697         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1698
1699         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1700
1701 }
1702
1703
1704
1705 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1706
1707         $a = get_app();
1708         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1709
1710         $signed_text = $item['guid'] . ';' . 'StatusMessage';
1711
1712         $tpl = get_markup_template('diaspora_signed_retract.tpl');
1713         $msg = replace_macros($tpl, array(
1714                 '$guid'   => $item['guid'],
1715                 '$type'   => 'StatusMessage',
1716                 '$handle' => $myaddr,
1717                 '$signature' => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'))
1718         ));
1719
1720         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1721
1722         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1723 }
1724
1725
1726
1727 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
1728
1729         $a = get_app();
1730         $logid = random_string(4);
1731         logger('diaspora_transmit: ' . $logid . ' ' . (($public_batch) ? $contact['batch'] : $contact['notify']));
1732         post_url((($public_batch) ? $contact['batch'] : $contact['notify']) . '/',$slap);
1733         $return_code = $a->get_curl_code();
1734         logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
1735
1736         if((! $return_code) || (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
1737                 logger('diaspora_transmit: queue message');
1738                 // queue message for redelivery
1739                 add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
1740         }
1741
1742
1743         return(($return_code) ? $return_code : (-1));
1744 }