]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
broadcast notices to jabber
[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_checkbox($id, $label, $value='true',
323                                                  $instructions=NULL)
324 {
325         common_element_start('p');
326         $attrs = array('name' => $id,
327                                    'type' => 'checkbox',
328                                    'id' => $id, 
329                                    'value' => $value);
330         if ($value) {
331                 $attrs['value'] = htmlspecialchars($value);
332         }
333         common_element('input', $attrs);
334         common_element('label', array('for' => $id), $label);
335         if ($instructions) {
336                 common_element('span', 'input_instructions', $instructions);
337         }
338         common_element_end('p');
339 }
340
341 function common_hidden($id, $value) {
342         common_element('input', array('name' => $id,
343                                                                   'type' => 'hidden',
344                                                                   'id' => $id,
345                                                                   'value' => $value));
346 }
347
348 function common_password($id, $label, $instructions=NULL) {
349         common_element_start('p');
350         common_element('label', array('for' => $id), $label);
351         $attrs = array('name' => $id,
352                                    'type' => 'password',
353                                    'id' => $id);
354         common_element('input', $attrs);
355         if ($instructions) {
356                 common_element('span', 'input_instructions', $instructions);
357         }
358         common_element_end('p');
359 }
360
361 function common_submit($id, $label) {
362         global $xw;
363         common_element_start('p');
364         common_element('input', array('type' => 'submit',
365                                                                   'id' => $id,
366                                                                   'name' => $id,
367                                                                   'class' => 'submit',
368                                                                   'value' => $label));
369         common_element_end('p');
370 }
371
372 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
373         common_element_start('p');
374         common_element('label', array('for' => $id), $label);
375         common_element('textarea', array('rows' => 3,
376                                                                          'cols' => 40,
377                                                                          'name' => $id,
378                                                                          'id' => $id),
379                                    ($content) ? $content : ' ');
380         if ($instructions) {
381                 common_element('span', 'input_instructions', $instructions);
382         }
383         common_element_end('p');
384 }
385
386 # salted, hashed passwords are stored in the DB
387
388 function common_munge_password($password, $id) {
389         return md5($password . $id);
390 }
391
392 # check if a username exists and has matching password
393 function common_check_user($nickname, $password) {
394         $user = User::staticGet('nickname', $nickname);
395         if (is_null($user)) {
396                 return false;
397         } else {
398                 return (0 == strcmp(common_munge_password($password, $user->id),
399                                                         $user->password));
400         }
401 }
402
403 # is the current user logged in?
404 function common_logged_in() {
405         return (!is_null(common_current_user()));
406 }
407
408 function common_have_session() {
409         return (0 != strcmp(session_id(), ''));
410 }
411
412 function common_ensure_session() {
413         if (!common_have_session()) {
414                 @session_start();
415         }
416 }
417
418 function common_set_user($nickname) {
419         if (is_null($nickname) && common_have_session()) {
420                 unset($_SESSION['userid']);
421                 return true;
422         } else {
423                 $user = User::staticGet('nickname', $nickname);
424                 if ($user) {
425                         common_ensure_session();
426                         $_SESSION['userid'] = $user->id;
427                         return true;
428                 } else {
429                         return false;
430                 }
431         }
432         return false;
433 }
434
435 # who is the current user?
436 function common_current_user() {
437         common_ensure_session();
438         $id = $_SESSION['userid'];
439         if ($id) {
440                 $user = User::staticGet($id);
441         }
442         return $user;
443 }
444
445 # get canonical version of nickname for comparison
446 function common_canonical_nickname($nickname) {
447         # XXX: UTF-8 canonicalization (like combining chars)
448         return strtolower($nickname);
449 }
450
451 # get canonical version of email for comparison
452 function common_canonical_email($email) {
453         # XXX: canonicalize UTF-8
454         # XXX: lcase the domain part
455         return $email;
456 }
457
458 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$_+!*();/?:~-]))');
459
460 function common_render_content($text, $notice) {
461         $r = htmlspecialchars($text);
462         $id = $notice->profile_id;
463         $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
464         $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
465         # XXX: # tags
466         # XXX: machine tags
467         return $r;
468 }
469
470 function common_at_link($sender_id, $nickname) {
471         # Try to find profiles this profile is subscribed to that have this nickname
472         $recipient = new Profile();
473         # XXX: chokety and bad
474         $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
475         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
476         if ($recipient->find(TRUE)) {
477                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
478         }
479         # Try to find profiles that listen to this profile and that have this nickname
480         $recipient = new Profile();
481         # XXX: chokety and bad
482         $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
483         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
484         if ($recipient->find(TRUE)) {
485                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
486         }
487         # If this is a local user, try to find a local user with that nickname.
488         $sender = User::staticGet($sender_id);
489         if ($sender) {
490                 $recipient_user = User::staticGet('nickname', $nickname);
491                 if ($recipient_user) {
492                         return '<a href="'.htmlspecialchars(common_profile_url($nickname)).'" class="atlink usertouser">'.$nickname.'</a>';
493                 }
494         }
495         # Otherwise, no links. @messages from local users to remote users,
496         # or from remote users to other remote users, are just
497         # outside our ability to make intelligent guesses about
498         return $nickname;
499 }
500
501 // where should the avatar go for this user?
502
503 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
504         global $config;
505
506         if ($size) {
507                 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
508         } else {
509                 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
510         }
511 }
512
513 function common_avatar_path($filename) {
514         global $config;
515         return INSTALLDIR . '/avatar/' . $filename;
516 }
517
518 function common_avatar_url($filename) {
519         return common_path('avatar/'.$filename);
520 }
521
522 function common_default_avatar($size) {
523         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
524                                                           AVATAR_STREAM_SIZE => 'stream',
525                                                           AVATAR_MINI_SIZE => 'mini');
526         return theme_path('default-avatar-'.$sizenames[$size].'.png');
527 }
528
529 function common_local_url($action, $args=NULL) {
530         global $config;
531         if ($config['site']['fancy']) {
532                 return common_fancy_url($action, $args);
533         } else {
534                 return common_simple_url($action, $args);
535         }
536 }
537
538 function common_fancy_url($action, $args=NULL) {
539         switch (strtolower($action)) {
540          case 'public':
541                 if ($args && $args['page']) {
542                         return common_path('?page=' . $args['page']);
543                 } else {
544                         return common_path('');
545                 }
546          case 'publicrss':
547                 return common_path('rss');
548          case 'publicxrds':
549                 return common_path('xrds');
550          case 'doc':
551                 return common_path('doc/'.$args['title']);
552          case 'login':
553          case 'logout':
554          case 'register':
555          case 'subscribe':
556          case 'unsubscribe':
557                 return common_path('main/'.$action);
558          case 'openidlogin':
559                 return common_path('main/openid');
560          case 'avatar':
561          case 'password':
562                 return common_path('settings/'.$action);
563          case 'profilesettings':
564                 return common_path('settings/profile');
565          case 'openidsettings':
566                 return common_path('settings/openid');
567          case 'newnotice':
568                 return common_path('notice/new');
569          case 'shownotice':
570                 return common_path('notice/'.$args['notice']);
571          case 'xrds':
572          case 'foaf':
573                 return common_path($args['nickname'].'/'.$action);
574          case 'subscriptions':
575          case 'subscribers':
576          case 'all':
577                 if ($args && $args['page']) {
578                         return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
579                 } else {
580                         return common_path($args['nickname'].'/'.$action);
581                 }
582          case 'allrss':
583                 return common_path($args['nickname'].'/all/rss');
584          case 'userrss':
585                 return common_path($args['nickname'].'/rss');
586          case 'showstream':
587                 if ($args && $args['page']) {
588                         return common_path($args['nickname'].'?page=' . $args['page']);
589                 } else {
590                         return common_path($args['nickname']);
591                 }
592          case 'confirmaddress':
593                 return common_path('main/confirmaddress/'.$args['code']);
594          case 'userbyid':
595                 return common_path('user/'.$args['id']);
596          default:
597                 return common_simple_url($action, $args);
598         }
599 }
600
601 function common_simple_url($action, $args=NULL) {
602         global $config;
603         /* XXX: pretty URLs */
604         $extra = '';
605         if ($args) {
606                 foreach ($args as $key => $value) {
607                         $extra .= "&${key}=${value}";
608                 }
609         }
610         return common_path("index.php?action=${action}${extra}");
611 }
612
613 function common_path($relative) {
614         global $config;
615         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
616         return "http://".$config['site']['server'].'/'.$pathpart.$relative;
617 }
618
619 function common_date_string($dt) {
620         // XXX: do some sexy date formatting
621         // return date(DATE_RFC822, $dt);
622         return $dt;
623 }
624
625 function common_date_w3dtf($dt) {
626         $t = strtotime($dt);
627         return date(DATE_W3C, $t);
628 }
629
630 function common_redirect($url, $code=307) {
631         static $status = array(301 => "Moved Permanently",
632                                                    302 => "Found",
633                                                    303 => "See Other",
634                                                    307 => "Temporary Redirect");
635         header("Status: ${code} $status[$code]");
636         header("Location: $url");
637
638         common_start_xml('a',
639                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
640                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
641         common_element('a', array('href' => $url), $url);
642         common_end_xml();
643 }
644
645 function common_broadcast_notice($notice, $remote=false) {
646         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
647         if (!$remote) {
648                 # Make sure we have the OMB stuff
649                 require_once(INSTALLDIR.'/lib/omb.php');
650                 omb_broadcast_remote_subscribers($notice);
651         }
652         require_once(INSTALLDIR.'/lib/jabber.php');
653         jabber_broadcast_notice($notice);
654         // XXX: broadcast notices to SMS
655         // XXX: broadcast notices to other IM
656         return true;
657 }
658
659 function common_broadcast_profile($profile) {
660         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
661         require_once(INSTALLDIR.'/lib/omb.php');
662         omb_broadcast_profile($profile);
663         // XXX: Other broadcasts...?
664         return true;
665 }
666
667 function common_profile_url($nickname) {
668         return common_local_url('showstream', array('nickname' => $nickname));
669 }
670
671 # Don't call if nobody's logged in
672
673 function common_notice_form($action=NULL) {
674         $user = common_current_user();
675         assert(!is_null($user));
676         common_element_start('form', array('id' => 'status_form',
677                                                                            'method' => 'POST',
678                                                                            'action' => common_local_url('newnotice')));
679         common_element_start('p');
680         common_element('label', array('for' => 'status_update',
681                                                                   'id' => 'status_label'),
682                                    _t('What\'s up, ').$user->nickname.'?');
683         common_element('textarea', array('id' => 'status_textarea',
684                                                                          'name' => 'status_textarea'),
685                                    ' ');
686         if ($action) {
687                 common_hidden('returnto', $action);
688         }
689         common_element('input', array('id' => 'status_submit',
690                                                                   'name' => 'status_submit',
691                                                                   'type' => 'submit',
692                                                                   'value' => _t('Send')));
693         common_element_end('p');
694         common_element_end('form');
695 }
696
697 function common_mint_tag($extra) {
698         global $config;
699         return
700           'tag:'.$config['tag']['authority'].','.
701           $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
702 }
703
704 # Should make up a reasonable root URL
705
706 function common_root_url() {
707         return common_path('');
708 }
709
710 # returns $bytes bytes of random data as a hexadecimal string
711 # "good" here is a goal and not a guarantee
712
713 function common_good_rand($bytes) {
714         # XXX: use random.org...?
715         if (file_exists('/dev/urandom')) {
716                 return common_urandom($bytes);
717         } else { # FIXME: this is probably not good enough
718                 return common_mtrand($bytes);
719         }
720 }
721
722 function common_urandom($bytes) {
723         $h = fopen('/dev/urandom', 'rb');
724         # should not block
725         $src = fread($h, $bytes);
726         fclose($h);
727         $enc = '';
728         for ($i = 0; $i < $bytes; $i++) {
729                 $enc .= sprintf("%02x", (ord($src[$i])));
730         }
731         return $enc;
732 }
733
734 function common_mtrand($bytes) {
735         $enc = '';
736         for ($i = 0; $i < $bytes; $i++) {
737                 $enc .= sprintf("%02x", mt_rand(0, 255));
738         }
739         return $enc;
740 }
741
742 function common_set_returnto($url) {
743         common_ensure_session();
744         $_SESSION['returnto'] = $url;
745 }
746
747 function common_get_returnto() {
748         common_ensure_session();
749         return $_SESSION['returnto'];
750 }
751
752 function common_timestamp() {
753         return date('YmdHis');
754 }
755
756 // XXX: set up gettext
757
758 function _t($str) {
759         return $str;
760 }
761
762 function common_ensure_syslog() {
763         static $initialized = false;
764         if (!$initialized) {
765                 global $config;
766                 define_syslog_variables();
767                 openlog($config['syslog']['appname'], 0, LOG_USER);
768                 $initialized = true;
769         }
770 }
771
772 function common_log($priority, $msg, $filename=NULL) {
773         common_ensure_syslog();
774         syslog($priority, $msg);
775 }
776
777 function common_debug($msg, $filename=NULL) {
778         if ($filename) {
779                 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
780         } else {
781                 common_log(LOG_DEBUG, $msg);
782         }
783 }
784
785 function common_log_db_error(&$object, $verb, $filename=NULL) {
786         $objstr = common_log_objstring($object);
787         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
788         common_log(LOG_ERROR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
789 }
790
791 function common_log_objstring(&$object) {
792         if (is_null($object)) {
793                 return "NULL";
794         }
795         $arr = $object->toArray();
796         $fields = array();
797         foreach ($arr as $k => $v) {
798                 $fields[] = "$k='$v'";
799         }
800         $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
801         return $objstring;
802 }
803
804 function common_valid_http_url($url) {
805         return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
806 }
807
808 function common_valid_tag($tag) {
809         if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
810                 return (Validate::email($matches[1]) ||
811                                 preg_match('/^([\w-\.]+)$/', $matches[1]));
812         }
813         return false;
814 }
815
816 # Does a little before-after block for next/prev page
817
818 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
819
820         if ($have_before || $have_after) {
821                 common_element_start('div', array('id' => 'pagination'));
822                 common_element_start('ul', array('id' => 'nav_pagination'));
823         }
824
825         if ($have_before) {
826                 $pargs = array('page' => $page-1);
827                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
828
829                 common_element_start('li', 'before');
830                 common_element('a', array('href' => common_local_url($action, $newargs)),
831                                            _t('« After'));
832                 common_element_end('li');
833         }
834
835         if ($have_after) {
836                 $pargs = array('page' => $page+1);
837                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
838                 common_element_start('li', 'after');
839                 common_element('a', array('href' => common_local_url($action, $newargs)),
840                                                    _t('Before »'));
841                 common_element_end('li');
842         }
843
844         if ($have_before || $have_after) {
845                 common_element_end('ul');
846                 common_element_end('div');
847         }
848 }
849
850 /* Following functions are copied from MediaWiki GlobalFunctions.php
851  * and written by Evan Prodromou. */
852
853 function common_accept_to_prefs($accept, $def = '*/*') {
854         # No arg means accept anything (per HTTP spec)
855         if(!$accept) {
856                 return array($def => 1);
857         }
858
859         $prefs = array();
860
861         $parts = explode(',', $accept);
862
863         foreach($parts as $part) {
864                 # FIXME: doesn't deal with params like 'text/html; level=1'
865                 @list($value, $qpart) = explode(';', $part);
866                 $match = array();
867                 if(!isset($qpart)) {
868                         $prefs[$value] = 1;
869                 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
870                         $prefs[$value] = $match[1];
871                 }
872         }
873
874         return $prefs;
875 }
876
877 function common_mime_type_match($type, $avail) {
878         if(array_key_exists($type, $avail)) {
879                 return $type;
880         } else {
881                 $parts = explode('/', $type);
882                 if(array_key_exists($parts[0] . '/*', $avail)) {
883                         return $parts[0] . '/*';
884                 } elseif(array_key_exists('*/*', $avail)) {
885                         return '*/*';
886                 } else {
887                         return NULL;
888                 }
889         }
890 }
891
892 function common_negotiate_type($cprefs, $sprefs) {
893         $combine = array();
894
895         foreach(array_keys($sprefs) as $type) {
896                 $parts = explode('/', $type);
897                 if($parts[1] != '*') {
898                         $ckey = common_mime_type_match($type, $cprefs);
899                         if($ckey) {
900                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
901                         }
902                 }
903         }
904
905         foreach(array_keys($cprefs) as $type) {
906                 $parts = explode('/', $type);
907                 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
908                         $skey = common_mime_type_match($type, $sprefs);
909                         if($skey) {
910                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
911                         }
912                 }
913         }
914
915         $bestq = 0;
916         $besttype = NULL;
917
918         foreach(array_keys($combine) as $type) {
919                 if($combine[$type] > $bestq) {
920                         $besttype = $type;
921                         $bestq = $combine[$type];
922                 }
923         }
924
925         return $besttype;
926 }
927
928 function common_config($main, $sub) {
929         global $config;
930         return $config[$main][$sub];
931 }
932
933 function common_copy_args($from) {
934         $to = array();
935         $strip = get_magic_quotes_gpc();
936         foreach ($from as $k => $v) {
937                 $to[$k] = ($strip) ? stripslashes($v) : $v;
938         }
939         return $to;
940 }
941
942 function common_user_uri(&$user) {
943         return common_local_url('userbyid', array('id' => $user->id));
944 }
945
946 function common_notice_uri(&$notice) {
947         return common_local_url('shownotice', 
948                 array('notice' => $notice->id));
949 }
950
951 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
952
953 function common_confirmation_code($bits) {
954         # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
955         static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
956         $chars = ceil($bits/5);
957         $code = '';
958         for ($i = 0; $i < $chars; $i++) {
959                 # XXX: convert to string and back
960                 $num = hexdec(common_good_rand(1));
961                 $code .= $codechars[$num%32];
962         }
963         return $code;
964 }