3 * Laconica - a distributed open-source microblogging tool
4 * Copyright (C) 2008, Controlez-Vous, Inc.
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.
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.
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/>.
20 /* XXX: break up into separate modules (HTTP, HTML, user, files) */
24 function common_server_error($msg, $code=500) {
25 static $status = array(500 => 'Internal Server Error',
26 501 => 'Not Implemented',
28 503 => 'Service Unavailable',
29 504 => 'Gateway Timeout',
30 505 => 'HTTP Version Not Supported');
32 if (!array_key_exists($code, $status)) {
36 $status_string = $status[$code];
38 header('HTTP/1.1 '.$code.' '.$status_string);
39 header('Content-type: text/plain');
47 function common_user_error($msg, $code=400) {
48 static $status = array(400 => 'Bad Request',
49 401 => 'Unauthorized',
50 402 => 'Payment Required',
53 405 => 'Method Not Allowed',
54 406 => 'Not Acceptable',
55 407 => 'Proxy Authentication Required',
56 408 => 'Request Timeout',
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');
67 if (!array_key_exists($code, $status)) {
71 $status_string = $status[$code];
73 header('HTTP/1.1 '.$code.' '.$status_string);
75 common_show_header('Error');
76 common_element('div', array('class' => 'error'), $msg);
82 # Start an HTML element
83 function common_element_start($tag, $attrs=NULL) {
85 $xw->startElement($tag);
86 if (is_array($attrs)) {
87 foreach ($attrs as $name => $value) {
88 $xw->writeAttribute($name, $value);
90 } else if (is_string($attrs)) {
91 $xw->writeAttribute('class', $attrs);
95 function common_element_end($tag) {
100 function common_element($tag, $attrs=NULL, $content=NULL) {
101 common_element_start($tag, $attrs);
106 common_element_end($tag);
109 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
111 $xw = new XMLWriter();
112 $xw->openURI('php://output');
113 $xw->setIndent(true);
114 $xw->startDocument('1.0', 'UTF-8');
116 $xw->writeDTD($doc, $public, $system);
120 function common_end_xml() {
126 define('PAGE_TYPE_PREFS', 'application/xhtml+xml,text/html;q=0.7,application/xml;q=0.3,text/xml;q=0.2');
128 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
131 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
133 # XXX: allow content negotiation for RDF, RSS, or XRDS
135 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
136 common_accept_to_prefs(PAGE_TYPE_PREFS));
139 common_client_error(_t('This page is not available in a media type you accept'), 406);
143 header('Content-Type: '.$type);
145 common_start_xml('html',
146 '-//W3C//DTD XHTML 1.0 Strict//EN',
147 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
149 # FIXME: correct language for interface
151 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
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]');
170 common_element('script', array('type' => 'text/javascript',
171 'src' => common_path('js/jquery.min.js')),
176 call_user_func($callable, $data);
178 call_user_func($callable);
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'));
186 if ((is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
187 || file_exists(theme_file('logo.png')))
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'],
194 common_element_end('a');
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');
202 common_element('h1', 'pagetitle', $pagetitle);
206 call_user_func($headercall, $data);
208 call_user_func($headercall);
211 common_element_end('div');
212 common_element_start('div', array('id' => 'content'));
215 function common_show_footer() {
217 common_element_end('div'); # content div
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/'),
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',
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');
248 function common_text($txt) {
253 function common_raw($xml) {
258 function common_nav_menu() {
259 $user = common_current_user();
260 common_element_start('ul', array('id' => 'nav'));
262 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
265 common_menu_item(common_local_url('public'), _t('Public'));
266 common_menu_item(common_local_url('doc', array('title' => 'help')),
269 common_menu_item(common_local_url('profilesettings'),
271 common_menu_item(common_local_url('logout'),
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'));
278 common_element_end('ul');
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')),
285 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
287 common_menu_item(common_local_url('doc', array('title' => 'source')),
289 common_element_end('ul');
292 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
295 $lattrs['class'] = 'current';
297 common_element_start('li', $lattrs);
298 $attrs['href'] = $url;
300 $attrs['title'] = $title;
302 common_element('a', $attrs, $text);
303 common_element_end('li');
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,
313 $attrs['value'] = htmlspecialchars($value);
315 common_element('input', $attrs);
317 common_element('span', 'input_instructions', $instructions);
319 common_element_end('p');
322 function common_checkbox($id, $label, $instructions=NULL, $value='true')
324 common_element_start('p');
325 $attrs = array('name' => $id,
326 'type' => 'checkbox',
330 $attrs['value'] = htmlspecialchars($value);
332 common_element('input', $attrs, $label);
334 common_element('span', 'input_instructions', $instructions);
336 common_element_end('p');
339 function common_hidden($id, $value) {
340 common_element('input', array('name' => $id,
346 function common_password($id, $label, $instructions=NULL) {
347 common_element_start('p');
348 common_element('label', array('for' => $id), $label);
349 $attrs = array('name' => $id,
350 'type' => 'password',
352 common_element('input', $attrs);
354 common_element('span', 'input_instructions', $instructions);
356 common_element_end('p');
359 function common_submit($id, $label) {
361 common_element_start('p');
362 common_element('input', array('type' => 'submit',
367 common_element_end('p');
370 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
371 common_element_start('p');
372 common_element('label', array('for' => $id), $label);
373 common_element('textarea', array('rows' => 3,
377 ($content) ? $content : ' ');
379 common_element('span', 'input_instructions', $instructions);
381 common_element_end('p');
384 # salted, hashed passwords are stored in the DB
386 function common_munge_password($password, $id) {
387 return md5($password . $id);
390 # check if a username exists and has matching password
391 function common_check_user($nickname, $password) {
392 $user = User::staticGet('nickname', $nickname);
393 if (is_null($user)) {
396 return (0 == strcmp(common_munge_password($password, $user->id),
401 # is the current user logged in?
402 function common_logged_in() {
403 return (!is_null(common_current_user()));
406 function common_have_session() {
407 return (0 != strcmp(session_id(), ''));
410 function common_ensure_session() {
411 if (!common_have_session()) {
416 function common_set_user($nickname) {
417 if (is_null($nickname) && common_have_session()) {
418 unset($_SESSION['userid']);
421 $user = User::staticGet('nickname', $nickname);
423 common_ensure_session();
424 $_SESSION['userid'] = $user->id;
433 function common_set_cookie($key, $value, $expiration=0) {
434 $path = common_config('site', 'path');
435 $server = common_config('site', 'server');
437 if ($path && ($path != '/')) {
438 $cookiepath = '/' . $path . '/';
442 return setcookie($key,
449 define('REMEMBERME', 'rememberme');
450 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
452 function common_rememberme() {
453 $user = common_current_user();
457 $rm = new Remember_me();
458 $rm->code = common_good_rand(16);
459 $rm->user_id = $user->id;
460 $result = $rm->insert();
462 common_log_db_error($rm, 'INSERT', __FILE__);
465 common_set_cookie(REMEMBERME,
466 implode(':', array($rm->user_id, $rm->code)),
467 time() + REMEMBERME_EXPIRY);
470 function common_remembered_user() {
473 $packed = $_COOKIE[REMEMBERME];
475 list($id, $code) = explode(':', $packed);
477 $rm = Remember_me::staticGet($code);
478 if ($rm && ($rm->user_id == $id)) {
479 $user = User::staticGet($rm->user_id);
482 $result = $rm->delete();
484 common_log_db_error($rm, 'DELETE', __FILE__);
487 common_set_user($user->nickname);
488 common_real_login(false);
489 # We issue a new cookie, so they can log in
490 # automatically again after this session
500 # must be called with a valid user!
502 function common_forgetme() {
503 common_set_cookie(REMEMBERME, '', 0);
506 # who is the current user?
507 function common_current_user() {
508 if ($_REQUEST[session_name()]) {
509 common_ensure_session();
510 $id = $_SESSION['userid'];
512 # note: this should cache
513 $user = User::staticGet($id);
517 # that didn't work; try to remember
518 $user = common_remembered_user();
522 # Logins that are 'remembered' aren't 'real' -- they're subject to
523 # cookie-stealing. So, we don't let them do certain things. New reg,
524 # OpenID, and password logins _are_ real.
526 function common_real_login($real=true) {
527 common_ensure_session();
528 $_SESSION['real_login'] = $real;
531 function common_is_real_login() {
532 return common_logged_in() && $_SESSION['real_login'];
535 # get canonical version of nickname for comparison
536 function common_canonical_nickname($nickname) {
537 # XXX: UTF-8 canonicalization (like combining chars)
538 return strtolower($nickname);
541 # get canonical version of email for comparison
542 function common_canonical_email($email) {
543 # XXX: canonicalize UTF-8
544 # XXX: lcase the domain part
548 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$_+!*();/?:~-]))');
550 function common_render_content($text, $notice) {
551 $r = htmlspecialchars($text);
552 $id = $notice->profile_id;
553 $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
554 $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
560 function common_at_link($sender_id, $nickname) {
561 # Try to find profiles this profile is subscribed to that have this nickname
562 $recipient = new Profile();
563 # XXX: chokety and bad
564 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
565 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
566 if ($recipient->find(TRUE)) {
567 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
569 # Try to find profiles that listen to this profile and that have this nickname
570 $recipient = new Profile();
571 # XXX: chokety and bad
572 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
573 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
574 if ($recipient->find(TRUE)) {
575 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
577 # If this is a local user, try to find a local user with that nickname.
578 $sender = User::staticGet($sender_id);
580 $recipient_user = User::staticGet('nickname', $nickname);
581 if ($recipient_user) {
582 return '<a href="'.htmlspecialchars(common_profile_url($nickname)).'" class="atlink usertouser">'.$nickname.'</a>';
585 # Otherwise, no links. @messages from local users to remote users,
586 # or from remote users to other remote users, are just
587 # outside our ability to make intelligent guesses about
591 // where should the avatar go for this user?
593 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
597 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
599 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
603 function common_avatar_path($filename) {
605 return INSTALLDIR . '/avatar/' . $filename;
608 function common_avatar_url($filename) {
609 return common_path('avatar/'.$filename);
612 function common_default_avatar($size) {
613 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
614 AVATAR_STREAM_SIZE => 'stream',
615 AVATAR_MINI_SIZE => 'mini');
616 return theme_path('default-avatar-'.$sizenames[$size].'.png');
619 function common_local_url($action, $args=NULL) {
621 if ($config['site']['fancy']) {
622 return common_fancy_url($action, $args);
624 return common_simple_url($action, $args);
628 function common_fancy_url($action, $args=NULL) {
629 switch (strtolower($action)) {
631 if ($args && $args['page']) {
632 return common_path('?page=' . $args['page']);
634 return common_path('');
637 return common_path('rss');
639 return common_path('xrds');
641 return common_path('doc/'.$args['title']);
647 return common_path('main/'.$action);
649 return common_path('main/openid');
652 return common_path('settings/'.$action);
653 case 'profilesettings':
654 return common_path('settings/profile');
655 case 'openidsettings':
656 return common_path('settings/openid');
658 return common_path('notice/new');
660 return common_path('notice/'.$args['notice']);
663 return common_path($args['nickname'].'/'.$action);
664 case 'subscriptions':
667 if ($args && $args['page']) {
668 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
670 return common_path($args['nickname'].'/'.$action);
673 return common_path($args['nickname'].'/all/rss');
675 return common_path($args['nickname'].'/rss');
677 if ($args && $args['page']) {
678 return common_path($args['nickname'].'?page=' . $args['page']);
680 return common_path($args['nickname']);
682 case 'confirmaddress':
683 return common_path('main/confirmaddress/'.$args['code']);
685 return common_path('user/'.$args['id']);
686 case 'recoverpassword':
687 $path = 'main/recoverpassword';
689 $path .= '/' . $args['code'];
691 return common_path($path);
693 return common_simple_url($action, $args);
697 function common_simple_url($action, $args=NULL) {
699 /* XXX: pretty URLs */
702 foreach ($args as $key => $value) {
703 $extra .= "&${key}=${value}";
706 return common_path("index.php?action=${action}${extra}");
709 function common_path($relative) {
711 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
712 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
715 function common_date_string($dt) {
716 // XXX: do some sexy date formatting
717 // return date(DATE_RFC822, $dt);
721 function common_date_w3dtf($dt) {
723 return date(DATE_W3C, $t);
726 function common_redirect($url, $code=307) {
727 static $status = array(301 => "Moved Permanently",
730 307 => "Temporary Redirect");
731 header("Status: ${code} $status[$code]");
732 header("Location: $url");
734 common_start_xml('a',
735 '-//W3C//DTD XHTML 1.0 Strict//EN',
736 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
737 common_element('a', array('href' => $url), $url);
741 function common_broadcast_notice($notice, $remote=false) {
742 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
744 # Make sure we have the OMB stuff
745 require_once(INSTALLDIR.'/lib/omb.php');
746 omb_broadcast_remote_subscribers($notice);
748 require_once(INSTALLDIR.'/lib/jabber.php');
749 jabber_broadcast_notice($notice);
750 // XXX: broadcast notices to SMS
751 // XXX: broadcast notices to other IM
755 function common_broadcast_profile($profile) {
756 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
757 require_once(INSTALLDIR.'/lib/omb.php');
758 omb_broadcast_profile($profile);
759 // XXX: Other broadcasts...?
763 function common_profile_url($nickname) {
764 return common_local_url('showstream', array('nickname' => $nickname));
767 # Don't call if nobody's logged in
769 function common_notice_form($action=NULL) {
770 $user = common_current_user();
771 assert(!is_null($user));
772 common_element_start('form', array('id' => 'status_form',
774 'action' => common_local_url('newnotice')));
775 common_element_start('p');
776 common_element('label', array('for' => 'status_update',
777 'id' => 'status_label'),
778 _t('What\'s up, ').$user->nickname.'?');
779 common_element('textarea', array('id' => 'status_textarea',
780 'name' => 'status_textarea'),
783 common_hidden('returnto', $action);
785 common_element('input', array('id' => 'status_submit',
786 'name' => 'status_submit',
788 'value' => _t('Send')));
789 common_element_end('p');
790 common_element_end('form');
793 function common_mint_tag($extra) {
796 'tag:'.$config['tag']['authority'].','.
797 $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
800 # Should make up a reasonable root URL
802 function common_root_url() {
803 return common_path('');
806 # returns $bytes bytes of random data as a hexadecimal string
807 # "good" here is a goal and not a guarantee
809 function common_good_rand($bytes) {
810 # XXX: use random.org...?
811 if (file_exists('/dev/urandom')) {
812 return common_urandom($bytes);
813 } else { # FIXME: this is probably not good enough
814 return common_mtrand($bytes);
818 function common_urandom($bytes) {
819 $h = fopen('/dev/urandom', 'rb');
821 $src = fread($h, $bytes);
824 for ($i = 0; $i < $bytes; $i++) {
825 $enc .= sprintf("%02x", (ord($src[$i])));
830 function common_mtrand($bytes) {
832 for ($i = 0; $i < $bytes; $i++) {
833 $enc .= sprintf("%02x", mt_rand(0, 255));
838 function common_set_returnto($url) {
839 common_ensure_session();
840 $_SESSION['returnto'] = $url;
843 function common_get_returnto() {
844 common_ensure_session();
845 return $_SESSION['returnto'];
848 function common_timestamp() {
849 return date('YmdHis');
852 // XXX: set up gettext
858 function common_ensure_syslog() {
859 static $initialized = false;
862 define_syslog_variables();
863 openlog($config['syslog']['appname'], 0, LOG_USER);
868 function common_log($priority, $msg, $filename=NULL) {
869 common_ensure_syslog();
870 syslog($priority, $msg);
873 function common_debug($msg, $filename=NULL) {
875 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
877 common_log(LOG_DEBUG, $msg);
881 function common_log_db_error(&$object, $verb, $filename=NULL) {
882 $objstr = common_log_objstring($object);
883 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
884 common_log(LOG_ERROR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
887 function common_log_objstring(&$object) {
888 if (is_null($object)) {
891 $arr = $object->toArray();
893 foreach ($arr as $k => $v) {
894 $fields[] = "$k='$v'";
896 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
900 function common_valid_http_url($url) {
901 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
904 function common_valid_tag($tag) {
905 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
906 return (Validate::email($matches[1]) ||
907 preg_match('/^([\w-\.]+)$/', $matches[1]));
912 # Does a little before-after block for next/prev page
914 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
916 if ($have_before || $have_after) {
917 common_element_start('div', array('id' => 'pagination'));
918 common_element_start('ul', array('id' => 'nav_pagination'));
922 $pargs = array('page' => $page-1);
923 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
925 common_element_start('li', 'before');
926 common_element('a', array('href' => common_local_url($action, $newargs)),
928 common_element_end('li');
932 $pargs = array('page' => $page+1);
933 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
934 common_element_start('li', 'after');
935 common_element('a', array('href' => common_local_url($action, $newargs)),
937 common_element_end('li');
940 if ($have_before || $have_after) {
941 common_element_end('ul');
942 common_element_end('div');
946 /* Following functions are copied from MediaWiki GlobalFunctions.php
947 * and written by Evan Prodromou. */
949 function common_accept_to_prefs($accept, $def = '*/*') {
950 # No arg means accept anything (per HTTP spec)
952 return array($def => 1);
957 $parts = explode(',', $accept);
959 foreach($parts as $part) {
960 # FIXME: doesn't deal with params like 'text/html; level=1'
961 @list($value, $qpart) = explode(';', $part);
965 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
966 $prefs[$value] = $match[1];
973 function common_mime_type_match($type, $avail) {
974 if(array_key_exists($type, $avail)) {
977 $parts = explode('/', $type);
978 if(array_key_exists($parts[0] . '/*', $avail)) {
979 return $parts[0] . '/*';
980 } elseif(array_key_exists('*/*', $avail)) {
988 function common_negotiate_type($cprefs, $sprefs) {
991 foreach(array_keys($sprefs) as $type) {
992 $parts = explode('/', $type);
993 if($parts[1] != '*') {
994 $ckey = common_mime_type_match($type, $cprefs);
996 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1001 foreach(array_keys($cprefs) as $type) {
1002 $parts = explode('/', $type);
1003 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1004 $skey = common_mime_type_match($type, $sprefs);
1006 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1014 foreach(array_keys($combine) as $type) {
1015 if($combine[$type] > $bestq) {
1017 $bestq = $combine[$type];
1024 function common_config($main, $sub) {
1026 return $config[$main][$sub];
1029 function common_copy_args($from) {
1031 $strip = get_magic_quotes_gpc();
1032 foreach ($from as $k => $v) {
1033 $to[$k] = ($strip) ? stripslashes($v) : $v;
1038 function common_user_uri(&$user) {
1039 return common_local_url('userbyid', array('id' => $user->id));
1042 function common_notice_uri(&$notice) {
1043 return common_local_url('shownotice',
1044 array('notice' => $notice->id));
1047 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1049 function common_confirmation_code($bits) {
1050 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1051 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1052 $chars = ceil($bits/5);
1054 for ($i = 0; $i < $chars; $i++) {
1055 # XXX: convert to string and back
1056 $num = hexdec(common_good_rand(1));
1057 $code .= $codechars[$num%32];