]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
fake spaces in textareas to fakeout XMLWriter
[quix0rs-gnu-social.git] / lib / util.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, Controlez-Vous, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /* XXX: break up into separate modules (HTTP, HTML, user, files) */
21
22 # Show a server error
23
24 function common_server_error($msg, $code=500) {
25         static $status = array(500 => 'Internal Server Error',
26                                                    501 => 'Not Implemented',
27                                                    502 => 'Bad Gateway',
28                                                    503 => 'Service Unavailable',
29                                                    504 => 'Gateway Timeout',
30                                                    505 => 'HTTP Version Not Supported');
31
32         if (!array_key_exists($code, $status)) {
33                 $code = 500;
34         }
35
36         $status_string = $status[$code];
37
38         header('HTTP/1.1 '.$code.' '.$status_string);
39         header('Content-type: text/plain');
40
41         print $msg;
42         print "\n";
43         exit();
44 }
45
46 # Show a user error
47 function common_user_error($msg, $code=400) {
48         static $status = array(400 => 'Bad Request',
49                                                    401 => 'Unauthorized',
50                                                    402 => 'Payment Required',
51                                                    403 => 'Forbidden',
52                                                    404 => 'Not Found',
53                                                    405 => 'Method Not Allowed',
54                                                    406 => 'Not Acceptable',
55                                                    407 => 'Proxy Authentication Required',
56                                                    408 => 'Request Timeout',
57                                                    409 => 'Conflict',
58                                                    410 => 'Gone',
59                                                    411 => 'Length Required',
60                                                    412 => 'Precondition Failed',
61                                                    413 => 'Request Entity Too Large',
62                                                    414 => 'Request-URI Too Long',
63                                                    415 => 'Unsupported Media Type',
64                                                    416 => 'Requested Range Not Satisfiable',
65                                                    417 => 'Expectation Failed');
66
67         if (!array_key_exists($code, $status)) {
68                 $code = 400;
69         }
70
71         $status_string = $status[$code];
72
73         header('HTTP/1.1 '.$code.' '.$status_string);
74
75         common_show_header('Error');
76         common_element('div', array('class' => 'error'), $msg);
77         common_show_footer();
78 }
79
80 $xw = null;
81
82 # Start an HTML element
83 function common_element_start($tag, $attrs=NULL) {
84         global $xw;
85         $xw->startElement($tag);
86         if (is_array($attrs)) {
87                 foreach ($attrs as $name => $value) {
88                         $xw->writeAttribute($name, $value);
89                 }
90         } else if (is_string($attrs)) {
91                 $xw->writeAttribute('class', $attrs);
92         }
93 }
94
95 function common_element_end($tag) {
96         global $xw;
97         $xw->endElement();
98 }
99
100 function common_element($tag, $attrs=NULL, $content=NULL) {
101     common_element_start($tag, $attrs);
102         if ($content) {
103                 global $xw;
104                 $xw->text($content);
105         }
106         common_element_end($tag);
107 }
108
109 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
110         global $xw;
111         $xw = new XMLWriter();
112         $xw->openURI('php://output');
113         $xw->setIndent(true);
114         $xw->startDocument('1.0', 'UTF-8');
115         if ($doc) {
116                 $xw->writeDTD($doc, $public, $system);
117         }
118 }
119
120 function common_end_xml() {
121         global $xw;
122         $xw->endDocument();
123         $xw->flush();
124 }
125
126 define('PAGE_TYPE_PREFS', 'application/xhtml+xml,text/html;q=0.7,application/xml;q=0.3,text/xml;q=0.2');
127            
128 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
129         global $config, $xw;
130
131         $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
132
133         # XXX: allow content negotiation for RDF, RSS, or XRDS
134         
135         $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
136                                                                   common_accept_to_prefs(PAGE_TYPE_PREFS));
137
138         if (!$type) {
139                 common_client_error(_t('This page is not available in a media type you accept'), 406);
140                 exit(0);
141         }
142         
143         header('Content-Type: '.$type);
144
145         common_start_xml('html',
146                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
147                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
148
149         # FIXME: correct language for interface
150
151         common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
152                                                                            'xml:lang' => 'en',
153                                                                            'lang' => 'en'));
154
155         common_element_start('head');
156         common_element('title', NULL,
157                                    $pagetitle . " - " . $config['site']['name']);
158         common_element('link', array('rel' => 'stylesheet',
159                                                                  'type' => 'text/css',
160                                                                  'href' => theme_path('display.css'),
161                                                                  'media' => 'screen, projection, tv'));
162         foreach (array(6,7) as $ver) {
163                 if (file_exists(theme_file('ie'.$ver.'.css'))) {
164                         # Yes, IE people should be put in jail.
165                         $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
166                                                           'href="'.theme_path('ie'.$ver.'.css').' /><![endif]');
167                 }
168         }
169         
170         common_element('script', array('type' => 'text/javascript',
171                                                                    'src' => common_path('js/jquery.min.js')),
172                                    ' ');
173                                                  
174         if ($callable) {
175                 if ($data) {
176                         call_user_func($callable, $data);
177                 } else {
178                         call_user_func($callable);
179                 }
180         }
181         common_element_end('head');
182         common_element_start('body');
183         common_element_start('div', array('id' => 'wrap'));
184         common_element_start('div', array('id' => 'header'));
185         common_nav_menu();
186         if ($config['site']['logo'] || file_exists(theme_file('logo.png'))) {
187                 common_element_start('a', array('href' => common_local_url('public')));
188                 common_element('img', array('src' => ($config['site']['logo']) ?
189                                                                         ($config['site']['logo']) : theme_path('logo.png'),
190                                                                         'alt' => $config['site']['name'],
191                                                                         'id' => 'logo'));
192                 common_element_end('a');
193         }
194         common_element('h1', 'pagetitle', $pagetitle);
195         common_element('h2', 'sitename', $config['site']['name']);
196         
197         if ($headercall) {
198                 if ($data) {
199                         call_user_func($headercall, $data);
200                 } else {
201                         call_user_func($headercall);
202                 }
203         }
204         common_element_end('div');
205         common_element_start('div', array('id' => 'content'));
206 }
207
208 function common_show_footer() {
209         global $xw, $config;
210         common_element_end('div'); # content div
211         common_foot_menu();
212         common_element_start('div', array('id' => 'footer'));
213         common_element_start('p', 'laconica');
214         common_text(_t('This site is running the '));
215         common_element('a', array('class' => 'software',
216                                                           href => 'http://laconi.ca/'),
217                                    'Laconica');
218         common_text(_t('microblogging tool, version ' . LACONICA_VERSION . ', available under the '));
219         common_element('a', array(href => 'http://www.fsf.org/licensing/licenses/agpl-3.0.html'),
220                                    'GNU Affero General Public License');
221         common_text(_t('.'));
222         common_element_end('p');
223         common_element('img', array('id' => 'cc',
224                                                                 'src' => $config['license']['image'],
225                                                                 'alt' => $config['license']['title']));
226         common_element_start('p');
227         common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
228         common_element('a', array('class' => 'license',
229                                                           'rel' => 'license',
230                                                           href => $config['license']['url']),
231                                    $config['license']['title']);
232         common_text(_t('. Contributors should be attributed by full name or nickname.'));
233         common_element_end('p');
234         common_element_end('div');
235         common_element_end('div');
236         common_element_end('body');
237         common_element_end('html');
238         common_end_xml();
239 }
240
241 function common_text($txt) {
242         global $xw;
243         $xw->text($txt);
244 }
245
246 function common_raw($xml) {
247         global $xw;
248         $xw->writeRaw($xml);
249 }
250
251 function common_nav_menu() {
252         $user = common_current_user();
253         common_element_start('ul', array('id' => 'nav'));
254         if ($user) {
255                 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
256                                                  _t('Home'));
257         }
258         common_menu_item(common_local_url('public'), _t('Public'));
259         common_menu_item(common_local_url('doc', array('title' => 'help')),
260                                          _t('Help'));
261         if ($user) {
262                 common_menu_item(common_local_url('profilesettings'),
263                                                  _t('Settings'));
264                 common_menu_item(common_local_url('logout'),
265                                                  _t('Logout'));
266         } else {
267                 common_menu_item(common_local_url('login'), _t('Login'));
268                 common_menu_item(common_local_url('register'), _t('Register'));
269                 common_menu_item(common_local_url('openidlogin'), _t('OpenID'));
270         }
271         common_element_end('ul');
272 }
273
274 function common_foot_menu() {
275         common_element_start('ul', array('id' => 'nav_sub'));
276         common_menu_item(common_local_url('doc', array('title' => 'about')),
277                                          _t('About'));
278         common_menu_item(common_local_url('doc', array('title' => 'privacy')),
279                                          _t('Privacy'));
280         common_menu_item(common_local_url('doc', array('title' => 'source')),
281                                          _t('Source'));
282         common_element_end('ul');
283 }
284
285 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
286         $lattrs = array();
287         if ($is_selected) {
288                 $lattrs['class'] = 'current';
289         }
290         common_element_start('li', $lattrs);
291         $attrs['href'] = $url;
292         if ($title) {
293                 $attrs['title'] = $title;
294         }
295         common_element('a', $attrs, $text);
296         common_element_end('li');
297 }
298
299 function common_input($id, $label, $value=NULL,$instructions=NULL) {
300         common_element_start('p');
301         common_element('label', array('for' => $id), $label);
302         $attrs = array('name' => $id,
303                                    'type' => 'text',
304                                    'id' => $id);
305         if ($value) {
306                 $attrs['value'] = htmlspecialchars($value);
307         }
308         common_element('input', $attrs);
309         if ($instructions) {
310                 common_element('span', 'input_instructions', $instructions);
311         }
312         common_element_end('p');
313 }
314
315 function common_hidden($id, $value) {
316         common_element('input', array('name' => $id,
317                                                                   'type' => 'hidden',
318                                                                   'id' => $id,
319                                                                   'value' => $value));
320 }
321
322 function common_password($id, $label, $instructions=NULL) {
323         common_element_start('p');
324         common_element('label', array('for' => $id), $label);
325         $attrs = array('name' => $id,
326                                    'type' => 'password',
327                                    'id' => $id);
328         common_element('input', $attrs);
329         if ($instructions) {
330                 common_element('span', 'input_instructions', $instructions);
331         }
332         common_element_end('p');
333 }
334
335 function common_submit($id, $label) {
336         global $xw;
337         common_element_start('p');
338         common_element('input', array('type' => 'submit',
339                                                                   'id' => $id,
340                                                                   'name' => $id,
341                                                                   'class' => 'submit',
342                                                                   'value' => $label));
343         common_element_end('p');
344 }
345
346 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
347         common_element_start('p');
348         common_element('label', array('for' => $id), $label);
349         common_element('textarea', array('rows' => 3,
350                                                                          'cols' => 40,
351                                                                          'name' => $id,
352                                                                          'id' => $id),
353                                    ($content) ? $content : ' ');
354         if ($instructions) {
355                 common_element('span', 'input_instructions', $instructions);
356         }
357         common_element_end('p');
358 }
359
360 # salted, hashed passwords are stored in the DB
361
362 function common_munge_password($id, $password) {
363         return md5($id . $password);
364 }
365
366 # check if a username exists and has matching password
367 function common_check_user($nickname, $password) {
368         $user = User::staticGet('nickname', $nickname);
369         if (is_null($user)) {
370                 return false;
371         } else {
372                 return (0 == strcmp(common_munge_password($password, $user->id),
373                                                         $user->password));
374         }
375 }
376
377 # is the current user logged in?
378 function common_logged_in() {
379         return (!is_null(common_current_user()));
380 }
381
382 function common_have_session() {
383         return (0 != strcmp(session_id(), ''));
384 }
385
386 function common_ensure_session() {
387         if (!common_have_session()) {
388                 @session_start();
389         }
390 }
391
392 function common_set_user($nickname) {
393         if (is_null($nickname) && common_have_session()) {
394                 unset($_SESSION['userid']);
395                 return true;
396         } else {
397                 $user = User::staticGet('nickname', $nickname);
398                 if ($user) {
399                         common_ensure_session();
400                         $_SESSION['userid'] = $user->id;
401                         return true;
402                 } else {
403                         return false;
404                 }
405         }
406         return false;
407 }
408
409 # who is the current user?
410 function common_current_user() {
411         static $user = NULL; # FIXME: global memcached
412         if (is_null($user)) {
413                 common_ensure_session();
414                 $id = $_SESSION['userid'];
415                 if ($id) {
416                         $user = User::staticGet($id);
417                 }
418         }
419         return $user;
420 }
421
422 # get canonical version of nickname for comparison
423 function common_canonical_nickname($nickname) {
424         # XXX: UTF-8 canonicalization (like combining chars)
425         return strtolower($nickname);
426 }
427
428 # get canonical version of email for comparison
429 function common_canonical_email($email) {
430         # XXX: canonicalize UTF-8
431         # XXX: lcase the domain part
432         return $email;
433 }
434
435 define('URL_REGEX', '^|[ \t\r\n])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))');
436
437 function common_render_content($text, $notice) {
438         $r = htmlspecialchars($text);
439         $id = $notice->profile_id;
440         $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
441         $r = preg_replace('/(^|\b)@([\w-]+)($|\b)/e', "'\\1@'.common_at_link($id, '\\2').'\\3'", $r);
442         # XXX: # tags
443         # XXX: machine tags
444         return $r;
445 }
446
447 function common_at_link($sender_id, $nickname) {
448         # Try to find profiles this profile is subscribed to that have this nickname
449         $recipient = new Profile();
450         # XXX: chokety and bad
451         $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
452         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
453         if ($recipient->find(TRUE)) {
454                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
455         }
456         # Try to find profiles that listen to this profile and that have this nickname
457         $recipient = new Profile();
458         # XXX: chokety and bad
459         $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
460         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
461         if ($recipient->find(TRUE)) {
462                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
463         }
464         # If this is a local user, try to find a local user with that nickname.
465         $sender = User::staticGet($sender_id);
466         if ($sender) {
467                 $recipient_user = User::staticGet('nickname', $nickname);
468                 if ($recipient_user) {
469                         $recipient = $recipient->getProfile();
470                         return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink usertouser">'.$nickname.'</a>';
471                 }
472         }
473         # Otherwise, no links. @messages from local users to remote users,
474         # or from remote users to other remote users, are just
475         # outside our ability to make intelligent guesses about
476         return $nickname;
477 }
478
479 // where should the avatar go for this user?
480
481 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
482         global $config;
483
484         if ($size) {
485                 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
486         } else {
487                 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
488         }
489 }
490
491 function common_avatar_path($filename) {
492         global $config;
493         return INSTALLDIR . '/avatar/' . $filename;
494 }
495
496 function common_avatar_url($filename) {
497         return common_path('avatar/'.$filename);
498 }
499
500 function common_default_avatar($size) {
501         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
502                                                           AVATAR_STREAM_SIZE => 'stream',
503                                                           AVATAR_MINI_SIZE => 'mini');
504         return theme_path('default-avatar-'.$sizenames[$size].'.png');
505 }
506
507 function common_local_url($action, $args=NULL) {
508         global $config;
509         if ($config['site']['fancy']) {
510                 return common_fancy_url($action, $args);
511         } else {
512                 return common_simple_url($action, $args);
513         }
514 }
515
516 function common_fancy_url($action, $args=NULL) {
517         switch (strtolower($action)) {
518          case 'public':
519                 if ($args && $args['page']) {
520                         return common_path('?page=' . $args['page']);
521                 } else {
522                         return common_path('');
523                 }
524          case 'publicrss':
525                 return common_path('rss');
526          case 'doc':
527                 return common_path('doc/'.$args['title']);
528          case 'login':
529          case 'logout':
530          case 'register':
531          case 'subscribe':
532          case 'unsubscribe':
533                 return common_path('main/'.$action);
534          case 'openidlogin':
535                 return common_path('main/openid');
536          case 'avatar':
537          case 'password':
538                 return common_path('settings/'.$action);
539          case 'profilesettings':
540                 return common_path('settings/profile');
541          case 'openidsettings':
542                 return common_path('settings/openid');
543          case 'newnotice':
544                 return common_path('notice/new');
545          case 'shownotice':
546                 return common_path('notice/'.$args['notice']);
547          case 'xrds':           
548          case 'foaf':
549                 return common_path($args['nickname'].'/'.$action);
550          case 'subscriptions':
551          case 'subscribed':
552          case 'all':
553                 if ($args && $args['page']) {
554                         return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
555                 } else {
556                         return common_path($args['nickname'].'/'.$action);
557                 }
558          case 'allrss':
559                 return common_path($args['nickname'].'/all/rss');
560          case 'userrss':
561                 return common_path($args['nickname'].'/rss');
562          case 'showstream':
563                 if ($args && $args['page']) {
564                         return common_path($args['nickname'].'?page=' . $args['page']);
565                 } else {
566                         return common_path($args['nickname']);
567                 }
568          default:
569                 return common_simple_url($action, $args);
570         }
571 }
572
573 function common_simple_url($action, $args=NULL) {
574         global $config;
575         /* XXX: pretty URLs */
576         $extra = '';
577         if ($args) {
578                 foreach ($args as $key => $value) {
579                         $extra .= "&${key}=${value}";
580                 }
581         }
582         return common_path("index.php?action=${action}${extra}");
583 }
584
585 function common_path($relative) {
586         global $config;
587         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
588         return "http://".$config['site']['server'].'/'.$pathpart.$relative;
589 }
590
591 function common_date_string($dt) {
592         // XXX: do some sexy date formatting
593         // return date(DATE_RFC822, $dt);
594         return $dt;
595 }
596
597 function common_date_w3dtf($dt) {
598         $t = strtotime($dt);
599         return date(DATE_W3C, $t);
600 }
601
602 function common_redirect($url, $code=307) {
603         static $status = array(301 => "Moved Permanently",
604                                                    302 => "Found",
605                                                    303 => "See Other",
606                                                    307 => "Temporary Redirect");
607         header("Status: ${code} $status[$code]");
608         header("Location: $url");
609         common_element('a', array('href' => $url), $url);
610 }
611
612 function common_broadcast_notice($notice, $remote=false) {
613         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
614         if (!$remote) {
615                 # Make sure we have the OMB stuff
616                 require_once(INSTALLDIR.'/lib/omb.php');
617                 omb_broadcast_remote_subscribers($notice);
618         }
619         // XXX: broadcast notices to Jabber
620         // XXX: broadcast notices to SMS
621         // XXX: broadcast notices to other IM
622         return true;
623 }
624
625 function common_broadcast_profile($profile) {
626         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
627         require_once(INSTALLDIR.'/lib/omb.php');
628         omb_broadcast_profile($profile);
629         // XXX: Other broadcasts...?
630         return true;
631 }
632
633 function common_profile_url($nickname) {
634         return common_local_url('showstream', array('nickname' => $nickname));
635 }
636
637 # Don't call if nobody's logged in
638
639 function common_notice_form() {
640         $user = common_current_user();
641         assert(!is_null($user));
642         common_element_start('form', array('id' => 'status_form',
643                                                                            'method' => 'POST',
644                                                                            'action' => common_local_url('newnotice')));
645         common_element_start('p');
646         common_element('label', array('for' => 'status_update',
647                                                                   'id' => 'status_label'),
648                                    _t('What\'s up, ').$user->nickname.'?');
649         common_element('textarea', array('id' => 'status_textarea',
650                                                                          'name' => 'status_textarea'),
651                                    ' ');
652         common_element('input', array('id' => 'status_submit',
653                                                                   'name' => 'status_submit',
654                                                                   'type' => 'submit',
655                                                                   'value' => _t('Send')));
656         common_element_end('p');
657         common_element_end('form');
658 }
659
660 function common_mint_tag($extra) {
661         global $config;
662         return
663           'tag:'.$config['tag']['authority'].','.
664           $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
665 }
666
667 # Should make up a reasonable root URL
668
669 function common_root_url() {
670         return common_path('');
671 }
672
673 # returns $bytes bytes of random data as a hexadecimal string
674 # "good" here is a goal and not a guarantee
675
676 function common_good_rand($bytes) {
677         # XXX: use random.org...?
678         if (file_exists('/dev/urandom')) {
679                 return common_urandom($bytes);
680         } else { # FIXME: this is probably not good enough
681                 return common_mtrand($bytes);
682         }
683 }
684
685 function common_urandom($bytes) {
686         $h = fopen('/dev/urandom', 'rb');
687         # should not block
688         $src = fread($h, $bytes);
689         fclose($h);
690         $enc = '';
691         for ($i = 0; $i < $bytes; $i++) {
692                 $enc .= sprintf("%02x", (ord($src[$i])));
693         }
694         return $enc;
695 }
696
697 function common_mtrand($bytes) {
698         $enc = '';
699         for ($i = 0; $i < $bytes; $i++) {
700                 $enc .= sprintf("%02x", mt_rand(0, 255));
701         }
702         return $enc;
703 }
704
705 function common_set_returnto($url) {
706         common_ensure_session();
707         $_SESSION['returnto'] = $url;
708 }
709
710 function common_get_returnto() {
711         common_ensure_session();
712         return $_SESSION['returnto'];
713 }
714
715 function common_timestamp() {
716         return date('YmdHis');
717 }
718
719 // XXX: set up gettext
720
721 function _t($str) {
722         return $str;
723 }
724
725 function common_ensure_syslog() {
726         static $initialized = false;
727         if (!$initialized) {
728                 global $config;
729                 define_syslog_variables();
730                 openlog($config['syslog']['appname'], 0, LOG_USER);
731                 $initialized = true;
732         }
733 }
734
735 function common_log($priority, $msg, $filename=NULL) {
736         common_ensure_syslog();
737         syslog($priority, $msg);
738 }
739
740 function common_debug($msg, $filename=NULL) {
741         if ($filename) {
742                 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
743         } else {
744                 common_log(LOG_DEBUG, $msg);
745         }
746 }
747
748 function common_valid_http_url($url) {
749         return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
750 }
751
752 function common_valid_tag($tag) {
753         if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
754                 return (Validate::email($matches[1]) ||
755                                 preg_match('/^([\w-\.]+)$/', $matches[1]));
756         }
757         return false;
758 }
759
760 # Does a little before-after block for next/prev page
761
762 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {             
763         
764         if ($have_before || $have_after) {
765                 common_element_start('div', array('id' => 'pagination'));
766                 common_element_start('ul', array('id' => 'nav_pagination'));
767         }
768         
769         if ($have_before) {
770                 $pargs = array('page' => $page-1);
771                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
772                                                                                  
773                 common_element_start('li', 'before');
774                 common_element('a', array('href' => common_local_url($action, $newargs)),
775                                            _t('« After'));
776                 common_element_end('li');
777         }
778
779         if ($have_after) {
780                 $pargs = array('page' => $page+1);
781                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
782                 common_element_start('li', 'after');
783                 common_element('a', array('href' => common_local_url($action, $newargs)),
784                                                    _t('Before »'));
785                 common_element_end('li');
786         }
787         
788         if ($have_before || $have_after) {
789                 common_element_end('ul');
790                 common_element_end('div');
791         }
792 }
793
794 /* Following functions are copied from MediaWiki GlobalFunctions.php
795  * and written by Evan Prodromou. */
796
797 function common_accept_to_prefs($accept, $def = '*/*') {
798         # No arg means accept anything (per HTTP spec)
799         if(!$accept) {
800                 return array($def => 1);
801         }
802
803         $prefs = array();
804
805         $parts = explode(',', $accept);
806
807         foreach($parts as $part) {
808                 # FIXME: doesn't deal with params like 'text/html; level=1'
809                 @list($value, $qpart) = explode(';', $part);
810                 $match = array();
811                 if(!isset($qpart)) {
812                         $prefs[$value] = 1;
813                 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
814                         $prefs[$value] = $match[1];
815                 }
816         }
817
818         return $prefs;
819 }
820
821 function common_mime_type_match($type, $avail) {
822         if(array_key_exists($type, $avail)) {
823                 return $type;
824         } else {
825                 $parts = explode('/', $type);
826                 if(array_key_exists($parts[0] . '/*', $avail)) {
827                         return $parts[0] . '/*';
828                 } elseif(array_key_exists('*/*', $avail)) {
829                         return '*/*';
830                 } else {
831                         return NULL;
832                 }
833         }
834 }
835
836 function common_negotiate_type($cprefs, $sprefs) {
837         $combine = array();
838
839         foreach(array_keys($sprefs) as $type) {
840                 $parts = explode('/', $type);
841                 if($parts[1] != '*') {
842                         $ckey = common_mime_type_match($type, $cprefs);
843                         if($ckey) {
844                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
845                         }
846                 }
847         }
848
849         foreach(array_keys($cprefs) as $type) {
850                 $parts = explode('/', $type);
851                 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
852                         $skey = common_mime_type_match($type, $sprefs);
853                         if($skey) {
854                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
855                         }
856                 }
857         }
858
859         $bestq = 0;
860         $besttype = NULL;
861
862         foreach(array_keys($combine) as $type) {
863                 if($combine[$type] > $bestq) {
864                         $besttype = $type;
865                         $bestq = $combine[$type];
866                 }
867         }
868
869         return $besttype;
870 }
871
872 function common_config($main, $sub) {
873         global $config;
874         return $config[$main][$sub];
875 }