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