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