]> git.mxchange.org Git - friendica.git/blob - include/diaspora.php
Merge branch 'master' into groups
[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         $a = get_app();
424
425         $sender_handle = unxmlify($xml->sender_handle);
426         $recipient_handle = unxmlify($xml->recipient_handle);
427
428         if(! $sender_handle || ! $recipient_handle)
429                 return;
430          
431         $contact = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
432
433         if($contact) {
434
435                 // perhaps we were already sharing with this person. Now they're sharing with us.
436                 // That makes us friends.
437
438                 if($contact['rel'] == CONTACT_IS_FOLLOWER) {
439                         q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
440                                 intval(CONTACT_IS_FRIEND),
441                                 intval($contact['id']),
442                                 intval($importer['uid'])
443                         );
444                 }
445                 // send notification
446
447                 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
448                         intval($importer['uid'])
449                 );
450
451                 if((count($r)) && ($r[0]['hide-friends'] == 0)) {
452                         require_once('include/items.php');
453
454                         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
455                                 intval($importer['uid'])
456                         );
457
458                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
459
460                         if(count($self) && $contact['rel'] == CONTACT_IS_FOLLOWER) {
461
462                                 $arr = array();
463                                 $arr['uri'] = $arr['parent-uri'] = item_new_uri($a->get_hostname(), $importer['uid']); 
464                                 $arr['uid'] = $importer['uid'];
465                                 $arr['contact-id'] = $self[0]['id'];
466                                 $arr['wall'] = 1;
467                                 $arr['type'] = 'wall';
468                                 $arr['gravity'] = 0;
469                                 $arr['origin'] = 1;
470                                 $arr['author-name'] = $arr['owner-name'] = $self[0]['name'];
471                                 $arr['author-link'] = $arr['owner-link'] = $self[0]['url'];
472                                 $arr['author-avatar'] = $arr['owner-avatar'] = $self[0]['thumb'];
473                                 $arr['verb'] = ACTIVITY_FRIEND;
474                                 $arr['object-type'] = ACTIVITY_OBJ_PERSON;
475                                 
476                                 $A = '[url=' . $self[0]['url'] . ']' . $self[0]['name'] . '[/url]';
477                                 $B = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
478                                 $BPhoto = '[url=' . $contact['url'] . ']' . '[img]' . $contact['thumb'] . '[/img][/url]';
479                                 $arr['body'] =  sprintf( t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$Bphoto;
480
481                                 $arr['object'] = '<object><type>' . ACTIVITY_OBJ_PERSON . '</type><title>' . $contact['name'] . '</title>'
482                                         . '<id>' . $contact['url'] . '/' . $contact['name'] . '</id>';
483                                 $arr['object'] .= '<link>' . xmlify('<link rel="alternate" type="text/html" href="' . $contact['url'] . '" />' . "\n");
484                                 $arr['object'] .= xmlify('<link rel="photo" type="image/jpeg" href="' . $contact['thumb'] . '" />' . "\n");
485                                 $arr['object'] .= '</link></object>' . "\n";
486                                 $arr['last-child'] = 1;
487
488                                 $arr['allow_cid'] = $user[0]['allow_cid'];
489                                 $arr['allow_gid'] = $user[0]['allow_gid'];
490                                 $arr['deny_cid']  = $user[0]['deny_cid'];
491                                 $arr['deny_gid']  = $user[0]['deny_gid'];
492
493                                 $i = item_store($arr);
494                                 if($i)
495                                 proc_run('php',"include/notifier.php","activity","$i");
496
497                         }
498
499                 }
500
501                 return;
502         }
503         
504         $ret = find_diaspora_person_by_handle($sender_handle);
505
506
507         if((! count($ret)) || ($ret['network'] != NETWORK_DIASPORA)) {
508                 logger('diaspora_request: Cannot resolve diaspora handle ' . $sender_handle . ' for ' . $recipient_handle);
509                 return;
510         }
511
512         $batch = (($ret['batch']) ? $ret['batch'] : implode('/', array_slice(explode('/',$ret['url']),0,3)) . '/receive/public');
513
514         $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
515                 VALUES ( %d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d) ",
516                 intval($importer['uid']),
517                 dbesc($ret['network']),
518                 dbesc($ret['addr']),
519                 datetime_convert(),
520                 dbesc($ret['url']),
521                 dbesc(normalise_link($ret['url'])),
522                 dbesc($batch),
523                 dbesc($ret['name']),
524                 dbesc($ret['nick']),
525                 dbesc($ret['photo']),
526                 dbesc($ret['pubkey']),
527                 dbesc($ret['notify']),
528                 dbesc($ret['poll']),
529                 1,
530                 2
531         );
532                  
533         // find the contact record we just created
534
535         $contact_record = diaspora_get_contact_by_handle($importer['uid'],$sender_handle);
536
537         $hash = random_string() . (string) time();   // Generate a confirm_key
538         
539         if($contact_record) {
540                 $ret = q("INSERT INTO `intro` ( `uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime` )
541                         VALUES ( %d, %d, %d, %d, '%s', '%s', '%s' )",
542                         intval($importer['uid']),
543                         intval($contact_record['id']),
544                         0,
545                         0,
546                         dbesc( t('Sharing notification from Diaspora network')),
547                         dbesc($hash),
548                         dbesc(datetime_convert())
549                 );
550         }
551
552         return;
553 }
554
555 function diaspora_post($importer,$xml) {
556
557         $a = get_app();
558         $guid = notags(unxmlify($xml->guid));
559         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
560
561         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
562         if(! $contact)
563                 return;
564
565         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
566                 logger('diaspora_post: Ignoring this author.');
567                 return 202;
568         }
569
570         $message_id = $diaspora_handle . ':' . $guid;
571         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
572                 intval($importer['uid']),
573                 dbesc($message_id),
574                 dbesc($guid)
575         );
576         if(count($r)) {
577                 logger('diaspora_post: message exists: ' . $guid);
578                 return;
579         }
580
581     // allocate a guid on our system - we aren't fixing any collisions.
582         // we're ignoring them
583
584         $g = q("select * from guid where guid = '%s' limit 1",
585                 dbesc($guid)
586         );
587         if(! count($g)) {
588                 q("insert into guid ( guid ) values ( '%s' )",
589                         dbesc($guid)
590                 );
591         }
592
593         $created = unxmlify($xml->created_at);
594         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
595
596         $body = diaspora2bb($xml->raw_message);
597
598         $datarray = array();
599
600         $str_tags = '';
601
602         $tags = get_tags($body);
603
604         if(count($tags)) {
605                 foreach($tags as $tag) {
606                         if(strpos($tag,'#') === 0) {
607                                 if(strpos($tag,'[url='))
608                                         continue;
609                                 $basetag = str_replace('_',' ',substr($tag,1));
610                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
611                                 if(strlen($str_tags))
612                                         $str_tags .= ',';
613                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
614                                 continue;
615                         }
616                 }
617         }
618         
619         $datarray['uid'] = $importer['uid'];
620         $datarray['contact-id'] = $contact['id'];
621         $datarray['wall'] = 0;
622         $datarray['guid'] = $guid;
623         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
624         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
625         $datarray['private'] = $private;
626         $datarray['parent'] = 0;
627         $datarray['owner-name'] = $contact['name'];
628         $datarray['owner-link'] = $contact['url'];
629         $datarray['owner-avatar'] = $contact['thumb'];
630         $datarray['author-name'] = $contact['name'];
631         $datarray['author-link'] = $contact['url'];
632         $datarray['author-avatar'] = $contact['thumb'];
633         $datarray['body'] = $body;
634         $datarray['tag'] = $str_tags;
635         $datarray['app']  = 'Diaspora';
636
637         // if empty content it might be a photo that hasn't arrived yet. If a photo arrives, we'll make it visible.
638
639         $datarray['visible'] = ((strlen($body)) ? 1 : 0);
640
641         $message_id = item_store($datarray);
642
643         if($message_id) {
644                 q("update item set plink = '%s' where id = %d limit 1",
645                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
646                         intval($message_id)
647                 );
648         }
649
650         return;
651
652 }
653
654 function diaspora_reshare($importer,$xml) {
655
656         logger('diaspora_reshare: init: ' . print_r($xml,true));
657
658         $a = get_app();
659         $guid = notags(unxmlify($xml->guid));
660         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
661
662
663         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
664         if(! $contact)
665                 return;
666
667         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
668                 logger('diaspora_reshare: Ignoring this author: ' . $diaspora_handle . ' ' . print_r($xml,true));
669                 return 202;
670         }
671
672         $message_id = $diaspora_handle . ':' . $guid;
673         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
674                 intval($importer['uid']),
675                 dbesc($message_id),
676                 dbesc($guid)
677         );
678         if(count($r)) {
679                 logger('diaspora_reshare: message exists: ' . $guid);
680                 return;
681         }
682
683         $orig_author = notags(unxmlify($xml->root_diaspora_id));
684         $orig_guid = notags(unxmlify($xml->root_guid));
685
686         $source_url = 'https://' . substr($orig_author,strpos($orig_author,'@')+1) . '/p/' . $orig_guid . '.xml';
687         $x = fetch_url($source_url);
688         if(! $x)
689                 $x = fetch_url(str_replace('https://','http://',$source_url));
690         if(! $x) {
691                 logger('diaspora_reshare: unable to fetch source url ' . $source_url);
692                 return;
693         }
694         logger('diaspora_reshare: source: ' . $x);
695
696         $x = str_replace(array('<activity_streams-photo>','</activity_streams-photo>'),array('<asphoto>','</asphoto>'),$x);
697         $source_xml = parse_xml_string($x,false);
698
699         if(strlen($source_xml->post->asphoto->objectId) && ($source_xml->post->asphoto->objectId != 0) && ($source_xml->post->asphoto->image_url)) {
700                 $body = '[url=' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '][img]' . notags(unxmlify($source_xml->post->asphoto->objectId)) . '[/img][/url]' . "\n";
701                 $body = scale_diaspora_images($body,false);
702         }
703         elseif($source_xml->post->asphoto->image_url) {
704                 $body = '[img]' . notags(unxmlify($source_xml->post->asphoto->image_url)) . '[/img]' . "\n";
705                 $body = scale_diaspora_images($body);
706         }
707         elseif($source_xml->post->status_message) {
708                 $body = diaspora2bb($source_xml->post->status_message->raw_message);
709                 $body = scale_diaspora_images($body);
710
711         }
712         else {
713                 logger('diaspora_reshare: no reshare content found: ' . print_r($source_xml,true));
714                 return;
715         }
716         if(! $body) {
717                 logger('diaspora_reshare: empty body: source= ' . $x);
718                 return;
719         }
720
721         $person = find_diaspora_person_by_handle($orig_author);
722
723         if(is_array($person) && x($person,'name') && x($person,'url'))
724                 $details = '[url=' . $person['url'] . ']' . $person['name'] . '[/url]';
725         else
726                 $details = $orig_author;
727         
728         $prefix = '&#x2672; ' . $details . "\n"; 
729
730
731     // allocate a guid on our system - we aren't fixing any collisions.
732         // we're ignoring them
733
734         $g = q("select * from guid where guid = '%s' limit 1",
735                 dbesc($guid)
736         );
737         if(! count($g)) {
738                 q("insert into guid ( guid ) values ( '%s' )",
739                         dbesc($guid)
740                 );
741         }
742
743         $created = unxmlify($xml->created_at);
744         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
745
746         $datarray = array();
747
748         $str_tags = '';
749
750         $tags = get_tags($body);
751
752         if(count($tags)) {
753                 foreach($tags as $tag) {
754                         if(strpos($tag,'#') === 0) {
755                                 if(strpos($tag,'[url='))
756                                         continue;
757                                 $basetag = str_replace('_',' ',substr($tag,1));
758                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
759                                 if(strlen($str_tags))
760                                         $str_tags .= ',';
761                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
762                                 continue;
763                         }
764                 }
765         }
766         
767         $datarray['uid'] = $importer['uid'];
768         $datarray['contact-id'] = $contact['id'];
769         $datarray['wall'] = 0;
770         $datarray['guid'] = $guid;
771         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
772         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
773         $datarray['private'] = $private;
774         $datarray['parent'] = 0;
775         $datarray['owner-name'] = $contact['name'];
776         $datarray['owner-link'] = $contact['url'];
777         $datarray['owner-avatar'] = $contact['thumb'];
778         $datarray['author-name'] = $contact['name'];
779         $datarray['author-link'] = $contact['url'];
780         $datarray['author-avatar'] = $contact['thumb'];
781         $datarray['body'] = $prefix . $body;
782         $datarray['tag'] = $str_tags;
783         $datarray['app']  = 'Diaspora';
784
785         $message_id = item_store($datarray);
786
787         if($message_id) {
788                 q("update item set plink = '%s' where id = %d limit 1",
789                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
790                         intval($message_id)
791                 );
792         }
793
794         return;
795
796 }
797
798
799 function diaspora_asphoto($importer,$xml) {
800         logger('diaspora_asphoto called');
801
802         $a = get_app();
803         $guid = notags(unxmlify($xml->guid));
804         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
805
806         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
807         if(! $contact)
808                 return;
809
810         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
811                 logger('diaspora_asphoto: Ignoring this author.');
812                 return 202;
813         }
814
815         $message_id = $diaspora_handle . ':' . $guid;
816         $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `guid` = '%s' LIMIT 1",
817                 intval($importer['uid']),
818                 dbesc($message_id),
819                 dbesc($guid)
820         );
821         if(count($r)) {
822                 logger('diaspora_asphoto: message exists: ' . $guid);
823                 return;
824         }
825
826     // allocate a guid on our system - we aren't fixing any collisions.
827         // we're ignoring them
828
829         $g = q("select * from guid where guid = '%s' limit 1",
830                 dbesc($guid)
831         );
832         if(! count($g)) {
833                 q("insert into guid ( guid ) values ( '%s' )",
834                         dbesc($guid)
835                 );
836         }
837
838         $created = unxmlify($xml->created_at);
839         $private = ((unxmlify($xml->public) == 'false') ? 1 : 0);
840
841         if(strlen($xml->objectId) && ($xml->objectId != 0) && ($xml->image_url)) {
842                 $body = '[url=' . notags(unxmlify($xml->image_url)) . '][img]' . notags(unxmlify($xml->objectId)) . '[/img][/url]' . "\n";
843                 $body = scale_diaspora_images($body,false);
844         }
845         elseif($xml->image_url) {
846                 $body = '[img]' . notags(unxmlify($xml->image_url)) . '[/img]' . "\n";
847                 $body = scale_diaspora_images($body);
848         }
849         else {
850                 logger('diaspora_asphoto: no photo url found.');
851                 return;
852         }
853
854         $datarray = array();
855
856         
857         $datarray['uid'] = $importer['uid'];
858         $datarray['contact-id'] = $contact['id'];
859         $datarray['wall'] = 0;
860         $datarray['guid'] = $guid;
861         $datarray['uri'] = $datarray['parent-uri'] = $message_id;
862         $datarray['created'] = $datarray['edited'] = datetime_convert('UTC','UTC',$created);
863         $datarray['private'] = $private;
864         $datarray['parent'] = 0;
865         $datarray['owner-name'] = $contact['name'];
866         $datarray['owner-link'] = $contact['url'];
867         $datarray['owner-avatar'] = $contact['thumb'];
868         $datarray['author-name'] = $contact['name'];
869         $datarray['author-link'] = $contact['url'];
870         $datarray['author-avatar'] = $contact['thumb'];
871         $datarray['body'] = $body;
872         
873         $datarray['app']  = 'Diaspora/Cubbi.es';
874
875         $message_id = item_store($datarray);
876
877         if($message_id) {
878                 q("update item set plink = '%s' where id = %d limit 1",
879                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
880                         intval($message_id)
881                 );
882         }
883
884         return;
885
886 }
887
888
889
890
891
892
893 function diaspora_comment($importer,$xml,$msg) {
894
895         $a = get_app();
896         $guid = notags(unxmlify($xml->guid));
897         $parent_guid = notags(unxmlify($xml->parent_guid));
898         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
899         $target_type = notags(unxmlify($xml->target_type));
900         $text = unxmlify($xml->text);
901         $author_signature = notags(unxmlify($xml->author_signature));
902
903         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
904
905         $text = $xml->text;
906
907         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
908         if(! $contact) {
909                 logger('diaspora_comment: cannot find contact: ' . $msg['author']);
910                 return;
911         }
912
913         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
914                 logger('diaspora_comment: Ignoring this author.');
915                 return 202;
916         }
917
918         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
919                 intval($importer['uid']),
920                 dbesc($guid)
921         );
922         if(count($r)) {
923                 logger('diaspora_comment: our comment just got relayed back to us (or there was a guid collision) : ' . $guid);
924                 return;
925         }
926
927         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
928                 intval($importer['uid']),
929                 dbesc($parent_guid)
930         );
931         if(! count($r)) {
932                 logger('diaspora_comment: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
933                 return;
934         }
935         $parent_item = $r[0];
936
937         $author_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
938
939         $author_signature = base64_decode($author_signature);
940
941         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
942                 $person = $contact;
943                 $key = $msg['key'];
944         }
945         else {
946                 $person = find_diaspora_person_by_handle($diaspora_handle);     
947
948                 if(is_array($person) && x($person,'pubkey'))
949                         $key = $person['pubkey'];
950                 else {
951                         logger('diaspora_comment: unable to find author details');
952                         return;
953                 }
954         }
955
956         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
957                 logger('diaspora_comment: verification failed.');
958                 return;
959         }
960
961         if($parent_author_signature) {
962                 $owner_signed_data = $guid . ';' . $parent_guid . ';' . $text . ';' . $diaspora_handle;
963
964                 $parent_author_signature = base64_decode($parent_author_signature);
965
966                 $key = $msg['key'];
967
968                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
969                         logger('diaspora_comment: owner verification failed.');
970                         return;
971                 }
972         }
973
974         // Phew! Everything checks out. Now create an item.
975
976         $body = diaspora2bb($text);
977
978         $message_id = $diaspora_handle . ':' . $guid;
979
980         $datarray = array();
981
982         $str_tags = '';
983
984         $tags = get_tags($body);
985
986         if(count($tags)) {
987                 foreach($tags as $tag) {
988                         if(strpos($tag,'#') === 0) {
989                                 if(strpos($tag,'[url='))
990                                         continue;
991                                 $basetag = str_replace('_',' ',substr($tag,1));
992                                 $body = str_replace($tag,'#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]',$body);
993                                 if(strlen($str_tags))
994                                         $str_tags .= ',';
995                                 $str_tags .= '#[url=' . $a->get_baseurl() . '/search?search=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
996                                 continue;
997                         }
998                 }
999         }
1000
1001         $datarray['uid'] = $importer['uid'];
1002         $datarray['contact-id'] = $contact['id'];
1003         $datarray['wall'] = $parent_item['wall'];
1004         $datarray['gravity'] = GRAVITY_COMMENT;
1005         $datarray['guid'] = $guid;
1006         $datarray['uri'] = $message_id;
1007         $datarray['parent-uri'] = $parent_item['uri'];
1008
1009         // No timestamps for comments? OK, we'll the use current time.
1010         $datarray['created'] = $datarray['edited'] = datetime_convert();
1011         $datarray['private'] = $parent_item['private'];
1012
1013         $datarray['owner-name'] = $parent_item['owner-name'];
1014         $datarray['owner-link'] = $parent_item['owner-link'];
1015         $datarray['owner-avatar'] = $parent_item['owner-avatar'];
1016
1017         $datarray['author-name'] = $person['name'];
1018         $datarray['author-link'] = $person['url'];
1019         $datarray['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1020         $datarray['body'] = $body;
1021         $datarray['tag'] = $str_tags;
1022
1023         // We can't be certain what the original app is if the message is relayed.
1024         if(($parent_item['origin']) && (! $parent_author_signature)) 
1025                 $datarray['app']  = 'Diaspora';
1026
1027         $message_id = item_store($datarray);
1028
1029         if($message_id) {
1030                 q("update item set plink = '%s' where id = %d limit 1",
1031                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1032                         intval($message_id)
1033                 );
1034         }
1035
1036         if(($parent_item['origin']) && (! $parent_author_signature)) {
1037                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1038                         intval($message_id),
1039                         dbesc($author_signed_data),
1040                         dbesc(base64_encode($author_signature)),
1041                         dbesc($diaspora_handle)
1042                 );
1043
1044                 // if the message isn't already being relayed, notify others
1045                 // the existence of parent_author_signature means the parent_author or owner
1046                 // is already relaying.
1047
1048                 proc_run('php','include/notifier.php','comment',$message_id);
1049         }
1050         return;
1051 }
1052
1053 function diaspora_photo($importer,$xml,$msg) {
1054
1055         $a = get_app();
1056         $remote_photo_path = notags(unxmlify($xml->remote_photo_path));
1057
1058         $remote_photo_name = notags(unxmlify($xml->remote_photo_name));
1059
1060         $status_message_guid = notags(unxmlify($xml->status_message_guid));
1061
1062         $guid = notags(unxmlify($xml->guid));
1063
1064         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1065
1066         $public = notags(unxmlify($xml->public));
1067
1068         $created_at = notags(unxmlify($xml_created_at));
1069
1070
1071         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1072         if(! $contact)
1073                 return;
1074
1075         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1076                 logger('diaspora_photo: Ignoring this author.');
1077                 return 202;
1078         }
1079
1080         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1081                 intval($importer['uid']),
1082                 dbesc($status_message_guid)
1083         );
1084         if(! count($r)) {
1085                 logger('diaspora_photo: parent item not found: parent: ' . $parent_guid . ' item: ' . $guid);
1086                 return;
1087         }
1088         $parent_item = $r[0];
1089
1090         $link_text = '[img]' . $remote_photo_path . $remote_photo_name . '[/img]' . "\n";
1091
1092         $link_text = scale_diaspora_images($link_text);
1093
1094         if(strpos($parent_item['body'],$link_text) === false) {
1095                 $r = q("update item set `body` = '%s', `visible` = 1 where `id` = %d and `uid` = %d limit 1",
1096                         dbesc($link_text . $parent_item['body']),
1097                         intval($parent_item['id']),
1098                         intval($parent_item['uid'])
1099                 );
1100         }
1101
1102         return;
1103 }
1104
1105
1106
1107
1108 function diaspora_like($importer,$xml,$msg) {
1109
1110         $a = get_app();
1111         $guid = notags(unxmlify($xml->guid));
1112         $parent_guid = notags(unxmlify($xml->parent_guid));
1113         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1114         $target_type = notags(unxmlify($xml->target_type));
1115         $positive = notags(unxmlify($xml->positive));
1116         $author_signature = notags(unxmlify($xml->author_signature));
1117
1118         $parent_author_signature = (($xml->parent_author_signature) ? notags(unxmlify($xml->parent_author_signature)) : '');
1119
1120         // likes on comments not supported here and likes on photos not supported by Diaspora
1121
1122         if($target_type !== 'Post')
1123                 return;
1124
1125         $contact = diaspora_get_contact_by_handle($importer['uid'],$msg['author']);
1126         if(! $contact) {
1127                 logger('diaspora_like: cannot find contact: ' . $msg['author']);
1128                 return;
1129         }
1130
1131         if(($contact['rel'] == CONTACT_IS_FOLLOWER) || ($contact['blocked']) || ($contact['readonly'])) { 
1132                 logger('diaspora_like: Ignoring this author.');
1133                 return 202;
1134         }
1135
1136         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1137                 intval($importer['uid']),
1138                 dbesc($parent_guid)
1139         );
1140         if(! count($r)) {
1141                 logger('diaspora_like: parent item not found: ' . $guid);
1142                 return;
1143         }
1144
1145         $parent_item = $r[0];
1146
1147         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1148                 intval($importer['uid']),
1149                 dbesc($guid)
1150         );
1151         if(count($r)) {
1152                 if($positive === 'true') {
1153                         logger('diaspora_like: duplicate like: ' . $guid);
1154                         return;
1155                 } 
1156                 if($positive === 'false') {
1157                         q("UPDATE `item` SET `deleted` = 1 WHERE `id` = %d AND `uid` = %d LIMIT 1",
1158                                 intval($r[0]['id']),
1159                                 intval($importer['uid'])
1160                         );
1161                         // FIXME
1162                         //  send notification via proc_run()
1163                         return;
1164                 }
1165         }
1166         if($positive === 'false') {
1167                 logger('diaspora_like: unlike received with no corresponding like');
1168                 return; 
1169         }
1170
1171         $author_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1172
1173         $author_signature = base64_decode($author_signature);
1174
1175         if(strcasecmp($diaspora_handle,$msg['author']) == 0) {
1176                 $person = $contact;
1177                 $key = $msg['key'];
1178         }
1179         else {
1180                 $person = find_diaspora_person_by_handle($diaspora_handle);     
1181                 if(is_array($person) && x($person,'pubkey'))
1182                         $key = $person['pubkey'];
1183                 else {
1184                         logger('diaspora_like: unable to find author details');
1185                         return;
1186                 }
1187         }
1188
1189         if(! rsa_verify($author_signed_data,$author_signature,$key,'sha256')) {
1190                 logger('diaspora_like: verification failed.');
1191                 return;
1192         }
1193
1194         if($parent_author_signature) {
1195
1196                 $owner_signed_data = $guid . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $diaspora_handle;
1197
1198                 $parent_author_signature = base64_decode($parent_author_signature);
1199
1200                 $key = $msg['key'];
1201
1202                 if(! rsa_verify($owner_signed_data,$parent_author_signature,$key,'sha256')) {
1203                         logger('diaspora_like: owner verification failed.');
1204                         return;
1205                 }
1206         }
1207
1208         // Phew! Everything checks out. Now create an item.
1209
1210         $uri = $diaspora_handle . ':' . $guid;
1211
1212         $activity = ACTIVITY_LIKE;
1213         $post_type = (($parent_item['resource-id']) ? t('photo') : t('status'));
1214         $objtype = (($parent_item['resource-id']) ? ACTIVITY_OBJ_PHOTO : ACTIVITY_OBJ_NOTE ); 
1215         $link = xmlify('<link rel="alternate" type="text/html" href="' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . '" />' . "\n") ;
1216         $body = $parent_item['body'];
1217
1218         $obj = <<< EOT
1219
1220         <object>
1221                 <type>$objtype</type>
1222                 <local>1</local>
1223                 <id>{$parent_item['uri']}</id>
1224                 <link>$link</link>
1225                 <title></title>
1226                 <content>$body</content>
1227         </object>
1228 EOT;
1229         $bodyverb = t('%1$s likes %2$s\'s %3$s');
1230
1231         $arr = array();
1232
1233         $arr['uri'] = $uri;
1234         $arr['uid'] = $importer['uid'];
1235         $arr['guid'] = $guid;
1236         $arr['contact-id'] = $contact['id'];
1237         $arr['type'] = 'activity';
1238         $arr['wall'] = $parent_item['wall'];
1239         $arr['gravity'] = GRAVITY_LIKE;
1240         $arr['parent'] = $parent_item['id'];
1241         $arr['parent-uri'] = $parent_item['uri'];
1242
1243         $arr['owner-name'] = $parent_item['name'];
1244         $arr['owner-link'] = $parent_item['url'];
1245         $arr['owner-avatar'] = $parent_item['thumb'];
1246
1247         $arr['author-name'] = $person['name'];
1248         $arr['author-link'] = $person['url'];
1249         $arr['author-avatar'] = ((x($person,'thumb')) ? $person['thumb'] : $person['photo']);
1250         
1251         $ulink = '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
1252         $alink = '[url=' . $parent_item['author-link'] . ']' . $parent_item['author-name'] . '[/url]';
1253         $plink = '[url=' . $a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $parent_item['id'] . ']' . $post_type . '[/url]';
1254         $arr['body'] =  sprintf( $bodyverb, $ulink, $alink, $plink );
1255
1256         $arr['app']  = 'Diaspora';
1257
1258         $arr['private'] = $parent_item['private'];
1259         $arr['verb'] = $activity;
1260         $arr['object-type'] = $objtype;
1261         $arr['object'] = $obj;
1262         $arr['visible'] = 1;
1263         $arr['unseen'] = 1;
1264         $arr['last-child'] = 0;
1265
1266         $message_id = item_store($arr);
1267
1268
1269         if($message_id) {
1270                 q("update item set plink = '%s' where id = %d limit 1",
1271                         dbesc($a->get_baseurl() . '/display/' . $importer['nickname'] . '/' . $message_id),
1272                         intval($message_id)
1273                 );
1274         }
1275
1276         if(! $parent_author_signature) {
1277                 q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1278                         intval($message_id),
1279                         dbesc($author_signed_data),
1280                         dbesc(base64_encode($author_signature)),
1281                         dbesc($diaspora_handle)
1282                 );
1283         }
1284
1285         // if the message isn't already being relayed, notify others
1286         // the existence of parent_author_signature means the parent_author or owner
1287         // is already relaying. The parent_item['origin'] indicates the message was created on our system
1288
1289         if(($parent_item['origin']) && (! $parent_author_signature))
1290                 proc_run('php','include/notifier.php','comment',$message_id);
1291
1292         return;
1293 }
1294
1295 function diaspora_retraction($importer,$xml) {
1296
1297         $guid = notags(unxmlify($xml->guid));
1298         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1299         $type = notags(unxmlify($xml->type));
1300
1301         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1302         if(! $contact)
1303                 return;
1304
1305         if($type === 'Person') {
1306                 contact_remove($contact['id']);
1307         }
1308         elseif($type === 'Post') {
1309                 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1310                         dbesc('guid'),
1311                         intval($importer['uid'])
1312                 );
1313                 if(count($r)) {
1314                         if(link_compare($r[0]['author-link'],$contact['url'])) {
1315                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1316                                         dbesc(datetime_convert()),                      
1317                                         intval($r[0]['id'])
1318                                 );
1319                         }
1320                 }
1321         }
1322
1323         return 202;
1324         // NOTREACHED
1325 }
1326
1327 function diaspora_signed_retraction($importer,$xml) {
1328
1329         $guid = notags(unxmlify($xml->target_guid));
1330         $diaspora_handle = notags(unxmlify($xml->sender_handle));
1331         $type = notags(unxmlify($xml->target_type));
1332         $sig = notags(unxmlify($xml->target_author_signature));
1333
1334         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1335         if(! $contact)
1336                 return;
1337
1338         // this may not yet work for comments. Need to see how the relaying works
1339         // and figure out who signs it.
1340
1341
1342         $signed_data = $guid . ';' . $type ;
1343
1344         $sig = base64_decode($sig);
1345
1346         $key = $msg['key'];
1347
1348         if(! rsa_verify($signed_data,$sig,$key,'sha256')) {
1349                 logger('diaspora_signed_retraction: owner verification failed.' . print_r($msg,true));
1350                 return;
1351         }
1352
1353         if($type === 'StatusMessage') {
1354                 $r = q("select * from item where guid = '%s' and uid = %d limit 1",
1355                         dbesc('guid'),
1356                         intval($importer['uid'])
1357                 );
1358                 if(count($r)) {
1359                         if(link_compare($r[0]['author-link'],$contact['url'])) {
1360                                 q("update item set `deleted` = 1, `changed` = '%s' where `id` = %d limit 1",
1361                                         dbesc(datetime_convert()),                      
1362                                         intval($r[0]['id'])
1363                                 );
1364                         }
1365                 }
1366         }
1367
1368         return 202;
1369         // NOTREACHED
1370 }
1371
1372 function diaspora_profile($importer,$xml) {
1373
1374         $a = get_app();
1375         $diaspora_handle = notags(unxmlify($xml->diaspora_handle));
1376
1377         $contact = diaspora_get_contact_by_handle($importer['uid'],$diaspora_handle);
1378         if(! $contact)
1379                 return;
1380
1381         if($contact['blocked']) {
1382                 logger('diaspora_post: Ignoring this author.');
1383                 return 202;
1384         }
1385
1386         $name = unxmlify($xml->first_name) . ((strlen($xml->last_name)) ? ' ' . unxmlify($xml->last_name) : '');
1387         $image_url = unxmlify($xml->image_url);
1388         $birthday = unxmlify($xml->birthday);
1389
1390         $r = q("SELECT DISTINCT ( `resource-id` ) FROM `photo` WHERE  `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' ",
1391                 intval($importer['uid']),
1392                 intval($contact['id'])
1393         );
1394         $oldphotos = ((count($r)) ? $r : null);
1395
1396         require_once('include/Photo.php');
1397
1398         $images = import_profile_photo($image_url,$importer['uid'],$contact['id']);
1399         
1400         // Generic birthday. We don't know the timezone. The year is irrelevant. 
1401
1402         $birthday = str_replace('1000','1901',$birthday);
1403
1404         $birthday = datetime_convert('UTC','UTC',$birthday,'Y-m-d');
1405
1406         $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",
1407                 dbesc($name),
1408                 dbesc(datetime_convert()),
1409                 dbesc($images[0]),
1410                 dbesc($images[1]),
1411                 dbesc($images[2]),
1412                 dbesc(datetime_convert()),
1413                 dbesc($birthday),
1414                 intval($contact['id']),
1415                 intval($importer['uid'])
1416         ); 
1417
1418         if($r) {
1419                 if($oldphotos) {
1420                         foreach($oldphotos as $ph) {
1421                                 q("DELETE FROM `photo` WHERE `uid` = %d AND `contact-id` = %d AND `album` = 'Contact Photos' AND `resource-id` = '%s' ",
1422                                         intval($importer['uid']),
1423                                         intval($contact['id']),
1424                                         dbesc($ph['resource-id'])
1425                                 );
1426                         }
1427                 }
1428         }       
1429
1430         return;
1431
1432 }
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455 function diaspora_share($me,$contact) {
1456         $a = get_app();
1457         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1458         $theiraddr = $contact['addr'];
1459
1460         $tpl = get_markup_template('diaspora_share.tpl');
1461         $msg = replace_macros($tpl, array(
1462                 '$sender' => $myaddr,
1463                 '$recipient' => $theiraddr
1464         ));
1465
1466         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1467
1468         return(diaspora_transmit($owner,$contact,$slap, false));
1469 }
1470
1471 function diaspora_unshare($me,$contact) {
1472
1473         $a = get_app();
1474         $myaddr = $me['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1475
1476         $tpl = get_markup_template('diaspora_retract.tpl');
1477         $msg = replace_macros($tpl, array(
1478                 '$guid'   => $me['guid'],
1479                 '$type'   => 'Person',
1480                 '$handle' => $myaddr
1481         ));
1482
1483         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$me,$contact,$me['prvkey'],$contact['pubkey'])));
1484
1485         return(diaspora_transmit($owner,$contact,$slap, false));
1486
1487 }
1488
1489
1490
1491 function diaspora_send_status($item,$owner,$contact,$public_batch = false) {
1492
1493         $a = get_app();
1494         $myaddr = $owner['nickname'] . '@' . substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1495         $theiraddr = $contact['addr'];
1496
1497         $images = array();
1498
1499         $body = $item['body'];
1500
1501 /*
1502         // We're trying to match Diaspora's split message/photo protocol but
1503         // all the photos are displayed on D* as links and not img's - even
1504         // though we're sending pretty much precisely what they send us when
1505         // doing the same operation.  
1506         // Commented out for now, we'll use bb2diaspora to convert photos to markdown
1507         // which seems to get through intact.
1508
1509         $cnt = preg_match_all('|\[img\](.*?)\[\/img\]|',$body,$matches,PREG_SET_ORDER);
1510         if($cnt) {
1511                 foreach($matches as $mtch) {
1512                         $detail = array();
1513                         $detail['str'] = $mtch[0];
1514                         $detail['path'] = dirname($mtch[1]) . '/';
1515                         $detail['file'] = basename($mtch[1]);
1516                         $detail['guid'] = $item['guid'];
1517                         $detail['handle'] = $myaddr;
1518                         $images[] = $detail;
1519                         $body = str_replace($detail['str'],$mtch[1],$body);
1520                 }
1521         }       
1522 */
1523
1524         $body = xmlify(html_entity_decode(bb2diaspora($body)));
1525
1526         if($item['attach']) {
1527                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism',$item['attach'],$matches,PREG_SET_ORDER);
1528                 if(cnt) {
1529                         $body .= "\n" . t('Attachments:') . "\n";
1530                         foreach($matches as $mtch) {
1531                                 $body .= '[' . $mtch[3] . '](' . $mtch[1] . ')' . "\n";
1532                         }
1533                 }
1534         }       
1535
1536
1537         $public = (($item['private']) ? 'false' : 'true');
1538
1539         require_once('include/datetime.php');
1540         $created = datetime_convert('UTC','UTC',$item['created'],'Y-m-d H:i:s \U\T\C');
1541
1542         $tpl = get_markup_template('diaspora_post.tpl');
1543         $msg = replace_macros($tpl, array(
1544                 '$body' => $body,
1545                 '$guid' => $item['guid'],
1546                 '$handle' => xmlify($myaddr),
1547                 '$public' => $public,
1548                 '$created' => $created
1549         ));
1550
1551         logger('diaspora_send_status: ' . $owner['username'] . ' -> ' . $contact['name'] . ' base message: ' . $msg, LOGGER_DATA);
1552
1553         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1554
1555         $return_code = diaspora_transmit($owner,$contact,$slap,$public_batch);
1556
1557         if(count($images)) {
1558                 diaspora_send_images($item,$owner,$contact,$images,$public_batch);
1559         }
1560
1561         return $return_code;
1562 }
1563
1564
1565 function diaspora_send_images($item,$owner,$contact,$images,$public_batch = false) {
1566         $a = get_app();
1567         if(! count($images))
1568                 return;
1569         $mysite = substr($a->get_baseurl(),strpos($a->get_baseurl(),'://') + 3) . '/photo';
1570
1571         $tpl = get_markup_template('diaspora_photo.tpl');
1572         foreach($images as $image) {
1573                 if(! stristr($image['path'],$mysite))
1574                         continue;
1575                 $resource = str_replace('.jpg','',$image['file']);
1576                 $resource = substr($resource,0,strpos($resource,'-'));
1577
1578                 $r = q("select * from photo where `resource-id` = '%s' and `uid` = %d limit 1",
1579                         dbesc($resource),
1580                         intval($owner['uid'])
1581                 );
1582                 if(! count($r))
1583                         continue;
1584                 $public = (($r[0]['allow_cid'] || $r[0]['allow_gid'] || $r[0]['deny_cid'] || $r[0]['deny_gid']) ? 'false' : 'true' );
1585                 $msg = replace_macros($tpl,array(               
1586                         '$path' => xmlify($image['path']),
1587                         '$filename' => xmlify($image['file']),
1588                         '$msg_guid' => xmlify($image['guid']),
1589                         '$guid' => xmlify($r[0]['guid']),
1590                         '$handle' => xmlify($image['handle']),
1591                         '$public' => xmlify($public),
1592                         '$created_at' => xmlify(datetime_convert('UTC','UTC',$r[0]['created'],'Y-m-d H:i:s \U\T\C'))
1593                 ));
1594
1595
1596                 logger('diaspora_send_photo: base message: ' . $msg, LOGGER_DATA);
1597                 $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1598
1599                 diaspora_transmit($owner,$contact,$slap,$public_batch);
1600         }
1601
1602 }
1603
1604 function diaspora_send_followup($item,$owner,$contact,$public_batch = false) {
1605
1606         $a = get_app();
1607         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1608         $theiraddr = $contact['addr'];
1609
1610         $p = q("select guid from item where parent = %d limit 1",
1611                 $item['parent']
1612         );
1613         if(count($p))
1614                 $parent_guid = $p[0]['guid'];
1615         else
1616                 return;
1617
1618         if($item['verb'] === ACTIVITY_LIKE) {
1619                 $tpl = get_markup_template('diaspora_like.tpl');
1620                 $like = true;
1621                 $target_type = 'Post';
1622                 $positive = (($item['deleted']) ? 'false' : 'true');
1623         }
1624         else {
1625                 $tpl = get_markup_template('diaspora_comment.tpl');
1626                 $like = false;
1627         }
1628
1629         $text = html_entity_decode(bb2diaspora($item['body']));
1630
1631         // sign it
1632
1633         if($like)
1634                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1635         else
1636                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1637
1638         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1639
1640         $msg = replace_macros($tpl,array(
1641                 '$guid' => xmlify($item['guid']),
1642                 '$parent_guid' => xmlify($parent_guid),
1643                 '$target_type' =>xmlify($target_type),
1644                 '$authorsig' => xmlify($authorsig),
1645                 '$body' => xmlify($text),
1646                 '$positive' => xmlify($positive),
1647                 '$handle' => xmlify($myaddr)
1648         ));
1649
1650         logger('diaspora_followup: base message: ' . $msg, LOGGER_DATA);
1651
1652         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1653
1654         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1655 }
1656
1657
1658 function diaspora_send_relay($item,$owner,$contact,$public_batch = false) {
1659
1660
1661         $a = get_app();
1662         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1663         $theiraddr = $contact['addr'];
1664
1665
1666         $p = q("select guid from item where parent = %d limit 1",
1667                 $item['parent']
1668         );
1669         if(count($p))
1670                 $parent_guid = $p[0]['guid'];
1671         else
1672                 return;
1673
1674         if($item['verb'] === ACTIVITY_LIKE) {
1675                 $tpl = get_markup_template('diaspora_like_relay.tpl');
1676                 $like = true;
1677                 $target_type = 'Post';
1678                 $positive = (($item['deleted']) ? 'false' : 'true');
1679         }
1680         else {
1681                 $tpl = get_markup_template('diaspora_comment_relay.tpl');
1682                 $like = false;
1683         }
1684
1685         $body = $item['body'];
1686
1687         $text = html_entity_decode(bb2diaspora($body));
1688
1689         // fetch the original signature if somebody sent the post to us to relay
1690         // If we are relaying for a reply originating on our own account, there wasn't a 'send to relay'
1691         // action. It wasn't needed. In that case create the original signature and the 
1692         // owner (parent author) signature
1693         // comments from other networks will be relayed under our name, with a brief 
1694         // preamble to describe what's happening and noting the real author
1695
1696         $r = q("select * from sign where iid = %d limit 1",
1697                 intval($item['id'])
1698         );
1699         if(count($r)) { 
1700                 $orig_sign = $r[0];
1701                 $signed_text = $orig_sign['signed_text'];
1702                 $authorsig = $orig_sign['signature'];
1703                 $handle = $orig_sign['signer'];
1704         }
1705         else {
1706
1707                 $itemcontact = q("select * from contact where `id` = %d limit 1",
1708                         intval($item['contact-id'])
1709                 );
1710                 if(count($itemcontact)) {
1711                         if(! $itemcontact[0]['self']) {
1712                                 $prefix = sprintf( t('[Relayed] Comment authored by %s from network %s'),
1713                                         '['. $item['author-name'] . ']' . '(' . $item['author-link'] . ')',  
1714                                         network_to_name($itemcontact['network'])) . "\n";
1715                                 $body = $prefix . $body;
1716                         }
1717                 }
1718                 else {
1719
1720                         if($like)
1721                                 $signed_text = $item['guid'] . ';' . $target_type . ';' . $parent_guid . ';' . $positive . ';' . $myaddr;
1722                         else
1723                                 $signed_text = $item['guid'] . ';' . $parent_guid . ';' . $text . ';' . $myaddr;
1724
1725                         $authorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1726
1727                         q("insert into sign (`iid`,`signed_text`,`signature`,`signer`) values (%d,'%s','%s','%s') ",
1728                                 intval($item['id']),
1729                                 dbesc($signed_text),
1730                                 dbesc(base64_encode($authorsig)),
1731                                 dbesc($myaddr)
1732                         );
1733                         $handle = $myaddr;
1734                 }
1735         }
1736
1737         // sign it
1738
1739         $parentauthorsig = base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'));
1740
1741         $msg = replace_macros($tpl,array(
1742                 '$guid' => xmlify($item['guid']),
1743                 '$parent_guid' => xmlify($parent_guid),
1744                 '$target_type' =>xmlify($target_type),
1745                 '$authorsig' => xmlify($orig_sign['signature']),
1746                 '$parentsig' => xmlify($parentauthorsig),
1747                 '$body' => xmlify($text),
1748                 '$positive' => xmlify($positive),
1749                 '$handle' => xmlify($handle)
1750         ));
1751
1752         logger('diaspora_relay_comment: base message: ' . $msg, LOGGER_DATA);
1753
1754         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1755
1756         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1757
1758 }
1759
1760
1761
1762 function diaspora_send_retraction($item,$owner,$contact,$public_batch = false) {
1763
1764         $a = get_app();
1765         $myaddr = $owner['nickname'] . '@' .  substr($a->get_baseurl(), strpos($a->get_baseurl(),'://') + 3);
1766
1767         $signed_text = $item['guid'] . ';' . 'StatusMessage';
1768
1769         $tpl = get_markup_template('diaspora_signed_retract.tpl');
1770         $msg = replace_macros($tpl, array(
1771                 '$guid'   => $item['guid'],
1772                 '$type'   => 'StatusMessage',
1773                 '$handle' => $myaddr,
1774                 '$signature' => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256'))
1775         ));
1776
1777         $slap = 'xml=' . urlencode(urlencode(diaspora_msg_build($msg,$owner,$contact,$owner['uprvkey'],$contact['pubkey'],$public_batch)));
1778
1779         return(diaspora_transmit($owner,$contact,$slap,$public_batch));
1780 }
1781
1782
1783
1784 function diaspora_transmit($owner,$contact,$slap,$public_batch) {
1785
1786         $a = get_app();
1787         $logid = random_string(4);
1788         $dest_url = (($public_batch) ? $contact['batch'] : $contact['notify']);
1789         if(! $dest_url) {
1790                 logger('diaspora_transmit: no url for contact: ' . $contact['id'] . ' batch mode =' . $public_batch);
1791                 return 0;
1792         } 
1793
1794         logger('diaspora_transmit: ' . $logid . ' ' . $dest_url);
1795
1796         post_url($dest_url . '/', $slap);
1797
1798         $return_code = $a->get_curl_code();
1799         logger('diaspora_transmit: ' . $logid . ' returns: ' . $return_code);
1800
1801         if((! $return_code) || (($return_code == 503) && (stristr($a->get_curl_headers(),'retry-after')))) {
1802                 logger('diaspora_transmit: queue message');
1803
1804                 $r = q("SELECT id from queue where cid = %d and network = '%s' and content = '%s' and batch = %d limit 1",
1805                         intval($contact['id']),
1806                         dbesc(NETWORK_DIASPORA),
1807                         dbesc($slap),
1808                         intval($public_batch)
1809                 );
1810                 if(count($r)) {
1811                         logger('diaspora_transmit: add_to_queue ignored - identical item already in queue');
1812                 }
1813                 else {
1814                         // queue message for redelivery
1815                         add_to_queue($contact['id'],NETWORK_DIASPORA,$slap,$public_batch);
1816                 }
1817         }
1818
1819
1820         return(($return_code) ? $return_code : (-1));
1821 }