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