]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
0e3af013d51041903abfb555121594382dc8bf22
[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         } else {
194                 common_element('p', 'branding', $config['site']['name']);
195         }
196         
197         common_element('h1', 'pagetitle', $pagetitle);
198         
199         if ($headercall) {
200                 if ($data) {
201                         call_user_func($headercall, $data);
202                 } else {
203                         call_user_func($headercall);
204                 }
205         }
206         common_element_end('div');
207         common_element_start('div', array('id' => 'content'));
208 }
209
210 function common_show_footer() {
211         global $xw, $config;
212         common_element_end('div'); # content div
213         common_foot_menu();
214         common_element_start('div', array('id' => 'footer'));
215         common_element_start('p', 'laconica');
216         common_text(_t('This site is running the '));
217         common_element('a', array('class' => 'software',
218                                                           href => 'http://laconi.ca/'),
219                                    'Laconica');
220         common_text(_t('microblogging tool, version ' . LACONICA_VERSION . ', available under the '));
221         common_element('a', array(href => 'http://www.fsf.org/licensing/licenses/agpl-3.0.html'),
222                                    'GNU Affero General Public License');
223         common_text(_t('.'));
224         common_element_end('p');
225         common_element('img', array('id' => 'cc',
226                                                                 'src' => $config['license']['image'],
227                                                                 'alt' => $config['license']['title']));
228         common_element_start('p');
229         common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
230         common_element('a', array('class' => 'license',
231                                                           'rel' => 'license',
232                                                           href => $config['license']['url']),
233                                    $config['license']['title']);
234         common_text(_t('. Contributors should be attributed by full name or nickname.'));
235         common_element_end('p');
236         common_element_end('div');
237         common_element_end('div');
238         common_element_end('body');
239         common_element_end('html');
240         common_end_xml();
241 }
242
243 function common_text($txt) {
244         global $xw;
245         $xw->text($txt);
246 }
247
248 function common_raw($xml) {
249         global $xw;
250         $xw->writeRaw($xml);
251 }
252
253 function common_nav_menu() {
254         $user = common_current_user();
255         common_element_start('ul', array('id' => 'nav'));
256         if ($user) {
257                 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
258                                                  _t('Home'));
259         }
260         common_menu_item(common_local_url('public'), _t('Public'));
261         common_menu_item(common_local_url('doc', array('title' => 'help')),
262                                          _t('Help'));
263         if ($user) {
264                 common_menu_item(common_local_url('profilesettings'),
265                                                  _t('Settings'));
266                 common_menu_item(common_local_url('logout'),
267                                                  _t('Logout'));
268         } else {
269                 common_menu_item(common_local_url('login'), _t('Login'));
270                 common_menu_item(common_local_url('register'), _t('Register'));
271                 common_menu_item(common_local_url('openidlogin'), _t('OpenID'));
272         }
273         common_element_end('ul');
274 }
275
276 function common_foot_menu() {
277         common_element_start('ul', array('id' => 'nav_sub'));
278         common_menu_item(common_local_url('doc', array('title' => 'about')),
279                                          _t('About'));
280         common_menu_item(common_local_url('doc', array('title' => 'privacy')),
281                                          _t('Privacy'));
282         common_menu_item(common_local_url('doc', array('title' => 'source')),
283                                          _t('Source'));
284         common_element_end('ul');
285 }
286
287 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
288         $lattrs = array();
289         if ($is_selected) {
290                 $lattrs['class'] = 'current';
291         }
292         common_element_start('li', $lattrs);
293         $attrs['href'] = $url;
294         if ($title) {
295                 $attrs['title'] = $title;
296         }
297         common_element('a', $attrs, $text);
298         common_element_end('li');
299 }
300
301 function common_input($id, $label, $value=NULL,$instructions=NULL) {
302         common_element_start('p');
303         common_element('label', array('for' => $id), $label);
304         $attrs = array('name' => $id,
305                                    'type' => 'text',
306                                    'id' => $id);
307         if ($value) {
308                 $attrs['value'] = htmlspecialchars($value);
309         }
310         common_element('input', $attrs);
311         if ($instructions) {
312                 common_element('span', 'input_instructions', $instructions);
313         }
314         common_element_end('p');
315 }
316
317 function common_hidden($id, $value) {
318         common_element('input', array('name' => $id,
319                                                                   'type' => 'hidden',
320                                                                   'id' => $id,
321                                                                   'value' => $value));
322 }
323
324 function common_password($id, $label, $instructions=NULL) {
325         common_element_start('p');
326         common_element('label', array('for' => $id), $label);
327         $attrs = array('name' => $id,
328                                    'type' => 'password',
329                                    'id' => $id);
330         common_element('input', $attrs);
331         if ($instructions) {
332                 common_element('span', 'input_instructions', $instructions);
333         }
334         common_element_end('p');
335 }
336
337 function common_submit($id, $label) {
338         global $xw;
339         common_element_start('p');
340         common_element('input', array('type' => 'submit',
341                                                                   'id' => $id,
342                                                                   'name' => $id,
343                                                                   'class' => 'submit',
344                                                                   'value' => $label));
345         common_element_end('p');
346 }
347
348 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
349         common_element_start('p');
350         common_element('label', array('for' => $id), $label);
351         common_element('textarea', array('rows' => 3,
352                                                                          'cols' => 40,
353                                                                          'name' => $id,
354                                                                          'id' => $id),
355                                    ($content) ? $content : ' ');
356         if ($instructions) {
357                 common_element('span', 'input_instructions', $instructions);
358         }
359         common_element_end('p');
360 }
361
362 # salted, hashed passwords are stored in the DB
363
364 function common_munge_password($id, $password) {
365         return md5($id . $password);
366 }
367
368 # check if a username exists and has matching password
369 function common_check_user($nickname, $password) {
370         $user = User::staticGet('nickname', $nickname);
371         if (is_null($user)) {
372                 return false;
373         } else {
374                 return (0 == strcmp(common_munge_password($password, $user->id),
375                                                         $user->password));
376         }
377 }
378
379 # is the current user logged in?
380 function common_logged_in() {
381         return (!is_null(common_current_user()));
382 }
383
384 function common_have_session() {
385         return (0 != strcmp(session_id(), ''));
386 }
387
388 function common_ensure_session() {
389         if (!common_have_session()) {
390                 @session_start();
391         }
392 }
393
394 function common_set_user($nickname) {
395         if (is_null($nickname) && common_have_session()) {
396                 unset($_SESSION['userid']);
397                 return true;
398         } else {
399                 $user = User::staticGet('nickname', $nickname);
400                 if ($user) {
401                         common_ensure_session();
402                         $_SESSION['userid'] = $user->id;
403                         return true;
404                 } else {
405                         return false;
406                 }
407         }
408         return false;
409 }
410
411 # who is the current user?
412 function common_current_user() {
413         static $user = NULL; # FIXME: global memcached
414         if (is_null($user)) {
415                 common_ensure_session();
416                 $id = $_SESSION['userid'];
417                 if ($id) {
418                         $user = User::staticGet($id);
419                 }
420         }
421         return $user;
422 }
423
424 # get canonical version of nickname for comparison
425 function common_canonical_nickname($nickname) {
426         # XXX: UTF-8 canonicalization (like combining chars)
427         return strtolower($nickname);
428 }
429
430 # get canonical version of email for comparison
431 function common_canonical_email($email) {
432         # XXX: canonicalize UTF-8
433         # XXX: lcase the domain part
434         return $email;
435 }
436
437 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$_+!*();/?:~-]))');
438
439 function common_render_content($text, $notice) {
440         $r = htmlspecialchars($text);
441         $id = $notice->profile_id;
442         $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
443         $r = preg_replace('/(^|\b)@([\w-]+)($|\b)/e', "'\\1@'.common_at_link($id, '\\2').'\\3'", $r);
444         # XXX: # tags
445         # XXX: machine tags
446         return $r;
447 }
448
449 function common_at_link($sender_id, $nickname) {
450         # Try to find profiles this profile is subscribed to that have this nickname
451         $recipient = new Profile();
452         # XXX: chokety and bad
453         $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
454         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
455         if ($recipient->find(TRUE)) {
456                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
457         }
458         # Try to find profiles that listen to this profile and that have this nickname
459         $recipient = new Profile();
460         # XXX: chokety and bad
461         $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
462         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
463         if ($recipient->find(TRUE)) {
464                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
465         }
466         # If this is a local user, try to find a local user with that nickname.
467         $sender = User::staticGet($sender_id);
468         if ($sender) {
469                 $recipient_user = User::staticGet('nickname', $nickname);
470                 if ($recipient_user) {
471                         $recipient = $recipient->getProfile();
472                         return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink usertouser">'.$nickname.'</a>';
473                 }
474         }
475         # Otherwise, no links. @messages from local users to remote users,
476         # or from remote users to other remote users, are just
477         # outside our ability to make intelligent guesses about
478         return $nickname;
479 }
480
481 // where should the avatar go for this user?
482
483 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
484         global $config;
485
486         if ($size) {
487                 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
488         } else {
489                 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
490         }
491 }
492
493 function common_avatar_path($filename) {
494         global $config;
495         return INSTALLDIR . '/avatar/' . $filename;
496 }
497
498 function common_avatar_url($filename) {
499         return common_path('avatar/'.$filename);
500 }
501
502 function common_default_avatar($size) {
503         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
504                                                           AVATAR_STREAM_SIZE => 'stream',
505                                                           AVATAR_MINI_SIZE => 'mini');
506         return theme_path('default-avatar-'.$sizenames[$size].'.png');
507 }
508
509 function common_local_url($action, $args=NULL) {
510         global $config;
511         if ($config['site']['fancy']) {
512                 return common_fancy_url($action, $args);
513         } else {
514                 return common_simple_url($action, $args);
515         }
516 }
517
518 function common_fancy_url($action, $args=NULL) {
519         switch (strtolower($action)) {
520          case 'public':
521                 if ($args && $args['page']) {
522                         return common_path('?page=' . $args['page']);
523                 } else {
524                         return common_path('');
525                 }
526          case 'publicrss':
527                 return common_path('rss');
528          case 'doc':
529                 return common_path('doc/'.$args['title']);
530          case 'login':
531          case 'logout':
532          case 'register':
533          case 'subscribe':
534          case 'unsubscribe':
535                 return common_path('main/'.$action);
536          case 'openidlogin':
537                 return common_path('main/openid');
538          case 'avatar':
539          case 'password':
540                 return common_path('settings/'.$action);
541          case 'profilesettings':
542                 return common_path('settings/profile');
543          case 'openidsettings':
544                 return common_path('settings/openid');
545          case 'newnotice':
546                 return common_path('notice/new');
547          case 'shownotice':
548                 return common_path('notice/'.$args['notice']);
549          case 'xrds':           
550          case 'foaf':
551                 return common_path($args['nickname'].'/'.$action);
552          case 'subscriptions':
553          case 'subscribed':
554          case 'all':
555                 if ($args && $args['page']) {
556                         return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
557                 } else {
558                         return common_path($args['nickname'].'/'.$action);
559                 }
560          case 'allrss':
561                 return common_path($args['nickname'].'/all/rss');
562          case 'userrss':
563                 return common_path($args['nickname'].'/rss');
564          case 'showstream':
565                 if ($args && $args['page']) {
566                         return common_path($args['nickname'].'?page=' . $args['page']);
567                 } else {
568                         return common_path($args['nickname']);
569                 }
570          default:
571                 return common_simple_url($action, $args);
572         }
573 }
574
575 function common_simple_url($action, $args=NULL) {
576         global $config;
577         /* XXX: pretty URLs */
578         $extra = '';
579         if ($args) {
580                 foreach ($args as $key => $value) {
581                         $extra .= "&${key}=${value}";
582                 }
583         }
584         return common_path("index.php?action=${action}${extra}");
585 }
586
587 function common_path($relative) {
588         global $config;
589         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
590         return "http://".$config['site']['server'].'/'.$pathpart.$relative;
591 }
592
593 function common_date_string($dt) {
594         // XXX: do some sexy date formatting
595         // return date(DATE_RFC822, $dt);
596         return $dt;
597 }
598
599 function common_date_w3dtf($dt) {
600         $t = strtotime($dt);
601         return date(DATE_W3C, $t);
602 }
603
604 function common_redirect($url, $code=307) {
605         static $status = array(301 => "Moved Permanently",
606                                                    302 => "Found",
607                                                    303 => "See Other",
608                                                    307 => "Temporary Redirect");
609         header("Status: ${code} $status[$code]");
610         header("Location: $url");
611         common_element('a', array('href' => $url), $url);
612 }
613
614 function common_broadcast_notice($notice, $remote=false) {
615         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
616         if (!$remote) {
617                 # Make sure we have the OMB stuff
618                 require_once(INSTALLDIR.'/lib/omb.php');
619                 omb_broadcast_remote_subscribers($notice);
620         }
621         // XXX: broadcast notices to Jabber
622         // XXX: broadcast notices to SMS
623         // XXX: broadcast notices to other IM
624         return true;
625 }
626
627 function common_broadcast_profile($profile) {
628         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
629         require_once(INSTALLDIR.'/lib/omb.php');
630         omb_broadcast_profile($profile);
631         // XXX: Other broadcasts...?
632         return true;
633 }
634
635 function common_profile_url($nickname) {
636         return common_local_url('showstream', array('nickname' => $nickname));
637 }
638
639 # Don't call if nobody's logged in
640
641 function common_notice_form() {
642         $user = common_current_user();
643         assert(!is_null($user));
644         common_element_start('form', array('id' => 'status_form',
645                                                                            'method' => 'POST',
646                                                                            'action' => common_local_url('newnotice')));
647         common_element_start('p');
648         common_element('label', array('for' => 'status_update',
649                                                                   'id' => 'status_label'),
650                                    _t('What\'s up, ').$user->nickname.'?');
651         common_element('textarea', array('id' => 'status_textarea',
652                                                                          'name' => 'status_textarea'),
653                                    ' ');
654         common_element('input', array('id' => 'status_submit',
655                                                                   'name' => 'status_submit',
656                                                                   'type' => 'submit',
657                                                                   'value' => _t('Send')));
658         common_element_end('p');
659         common_element_end('form');
660 }
661
662 function common_mint_tag($extra) {
663         global $config;
664         return
665           'tag:'.$config['tag']['authority'].','.
666           $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
667 }
668
669 # Should make up a reasonable root URL
670
671 function common_root_url() {
672         return common_path('');
673 }
674
675 # returns $bytes bytes of random data as a hexadecimal string
676 # "good" here is a goal and not a guarantee
677
678 function common_good_rand($bytes) {
679         # XXX: use random.org...?
680         if (file_exists('/dev/urandom')) {
681                 return common_urandom($bytes);
682         } else { # FIXME: this is probably not good enough
683                 return common_mtrand($bytes);
684         }
685 }
686
687 function common_urandom($bytes) {
688         $h = fopen('/dev/urandom', 'rb');
689         # should not block
690         $src = fread($h, $bytes);
691         fclose($h);
692         $enc = '';
693         for ($i = 0; $i < $bytes; $i++) {
694                 $enc .= sprintf("%02x", (ord($src[$i])));
695         }
696         return $enc;
697 }
698
699 function common_mtrand($bytes) {
700         $enc = '';
701         for ($i = 0; $i < $bytes; $i++) {
702                 $enc .= sprintf("%02x", mt_rand(0, 255));
703         }
704         return $enc;
705 }
706
707 function common_set_returnto($url) {
708         common_ensure_session();
709         $_SESSION['returnto'] = $url;
710 }
711
712 function common_get_returnto() {
713         common_ensure_session();
714         return $_SESSION['returnto'];
715 }
716
717 function common_timestamp() {
718         return date('YmdHis');
719 }
720
721 // XXX: set up gettext
722
723 function _t($str) {
724         return $str;
725 }
726
727 function common_ensure_syslog() {
728         static $initialized = false;
729         if (!$initialized) {
730                 global $config;
731                 define_syslog_variables();
732                 openlog($config['syslog']['appname'], 0, LOG_USER);
733                 $initialized = true;
734         }
735 }
736
737 function common_log($priority, $msg, $filename=NULL) {
738         common_ensure_syslog();
739         syslog($priority, $msg);
740 }
741
742 function common_debug($msg, $filename=NULL) {
743         if ($filename) {
744                 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
745         } else {
746                 common_log(LOG_DEBUG, $msg);
747         }
748 }
749
750 function common_valid_http_url($url) {
751         return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
752 }
753
754 function common_valid_tag($tag) {
755         if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
756                 return (Validate::email($matches[1]) ||
757                                 preg_match('/^([\w-\.]+)$/', $matches[1]));
758         }
759         return false;
760 }
761
762 # Does a little before-after block for next/prev page
763
764 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {             
765         
766         if ($have_before || $have_after) {
767                 common_element_start('div', array('id' => 'pagination'));
768                 common_element_start('ul', array('id' => 'nav_pagination'));
769         }
770         
771         if ($have_before) {
772                 $pargs = array('page' => $page-1);
773                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
774                                                                                  
775                 common_element_start('li', 'before');
776                 common_element('a', array('href' => common_local_url($action, $newargs)),
777                                            _t('« After'));
778                 common_element_end('li');
779         }
780
781         if ($have_after) {
782                 $pargs = array('page' => $page+1);
783                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
784                 common_element_start('li', 'after');
785                 common_element('a', array('href' => common_local_url($action, $newargs)),
786                                                    _t('Before »'));
787                 common_element_end('li');
788         }
789         
790         if ($have_before || $have_after) {
791                 common_element_end('ul');
792                 common_element_end('div');
793         }
794 }
795
796 /* Following functions are copied from MediaWiki GlobalFunctions.php
797  * and written by Evan Prodromou. */
798
799 function common_accept_to_prefs($accept, $def = '*/*') {
800         # No arg means accept anything (per HTTP spec)
801         if(!$accept) {
802                 return array($def => 1);
803         }
804
805         $prefs = array();
806
807         $parts = explode(',', $accept);
808
809         foreach($parts as $part) {
810                 # FIXME: doesn't deal with params like 'text/html; level=1'
811                 @list($value, $qpart) = explode(';', $part);
812                 $match = array();
813                 if(!isset($qpart)) {
814                         $prefs[$value] = 1;
815                 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
816                         $prefs[$value] = $match[1];
817                 }
818         }
819
820         return $prefs;
821 }
822
823 function common_mime_type_match($type, $avail) {
824         if(array_key_exists($type, $avail)) {
825                 return $type;
826         } else {
827                 $parts = explode('/', $type);
828                 if(array_key_exists($parts[0] . '/*', $avail)) {
829                         return $parts[0] . '/*';
830                 } elseif(array_key_exists('*/*', $avail)) {
831                         return '*/*';
832                 } else {
833                         return NULL;
834                 }
835         }
836 }
837
838 function common_negotiate_type($cprefs, $sprefs) {
839         $combine = array();
840
841         foreach(array_keys($sprefs) as $type) {
842                 $parts = explode('/', $type);
843                 if($parts[1] != '*') {
844                         $ckey = common_mime_type_match($type, $cprefs);
845                         if($ckey) {
846                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
847                         }
848                 }
849         }
850
851         foreach(array_keys($cprefs) as $type) {
852                 $parts = explode('/', $type);
853                 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
854                         $skey = common_mime_type_match($type, $sprefs);
855                         if($skey) {
856                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
857                         }
858                 }
859         }
860
861         $bestq = 0;
862         $besttype = NULL;
863
864         foreach(array_keys($combine) as $type) {
865                 if($combine[$type] > $bestq) {
866                         $besttype = $type;
867                         $bestq = $combine[$type];
868                 }
869         }
870
871         return $besttype;
872 }
873
874 function common_config($main, $sub) {
875         global $config;
876         return $config[$main][$sub];
877 }