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) {
96 static $empty_tag = array('base', 'meta', 'link', 'hr',
97 'br', 'param', 'img', 'area',
100 # XXX: check namespace
101 if (in_array($tag, $empty_tag)) {
104 $xw->fullEndElement();
108 function common_element($tag, $attrs=NULL, $content=NULL) {
109 common_element_start($tag, $attrs);
114 common_element_end($tag);
117 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
119 $xw = new XMLWriter();
120 $xw->openURI('php://output');
121 $xw->setIndent(true);
122 $xw->startDocument('1.0', 'UTF-8');
124 $xw->writeDTD($doc, $public, $system);
128 function common_end_xml() {
134 define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2');
136 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
139 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
141 # XXX: allow content negotiation for RDF, RSS, or XRDS
143 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
144 common_accept_to_prefs(PAGE_TYPE_PREFS));
147 common_user_error(_t('This page is not available in a media type you accept'), 406);
151 header('Content-Type: '.$type);
153 common_start_xml('html',
154 '-//W3C//DTD XHTML 1.0 Strict//EN',
155 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
157 # FIXME: correct language for interface
159 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
163 common_element_start('head');
164 common_element('title', NULL,
165 $pagetitle . " - " . $config['site']['name']);
166 common_element('link', array('rel' => 'stylesheet',
167 'type' => 'text/css',
168 'href' => theme_path('display.css'),
169 'media' => 'screen, projection, tv'));
170 foreach (array(6,7) as $ver) {
171 if (file_exists(theme_file('ie'.$ver.'.css'))) {
172 # Yes, IE people should be put in jail.
173 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
174 'href="'.theme_path('ie'.$ver.'.css').'" /><![endif]');
178 common_element('script', array('type' => 'text/javascript',
179 'src' => common_path('js/jquery.min.js')),
181 common_element('script', array('type' => 'text/javascript',
182 'src' => common_path('js/util.js')),
187 call_user_func($callable, $data);
189 call_user_func($callable);
192 common_element_end('head');
193 common_element_start('body');
194 common_element_start('div', array('id' => 'wrap'));
195 common_element_start('div', array('id' => 'header'));
197 if ((is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
198 || file_exists(theme_file('logo.png')))
200 common_element_start('a', array('href' => common_local_url('public')));
201 common_element('img', array('src' => ($config['site']['logo']) ?
202 ($config['site']['logo']) : theme_path('logo.png'),
203 'alt' => $config['site']['name'],
205 common_element_end('a');
207 common_element_start('p', array('id' => 'branding'));
208 common_element('a', array('href' => common_local_url('public')),
209 $config['site']['name']);
210 common_element_end('p');
213 common_element('h1', 'pagetitle', $pagetitle);
217 call_user_func($headercall, $data);
219 call_user_func($headercall);
222 common_element_end('div');
223 common_element_start('div', array('id' => 'content'));
226 function common_show_footer() {
228 common_element_end('div'); # content div
230 common_element_start('div', array('id' => 'footer'));
231 common_element_start('div', 'laconica');
232 if (common_config('site', 'broughtby')) {
233 $instr = _t('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
235 $instr = _t('**%%site.name%%** is a microblogging service. ');
237 $instr .= _t('It runs the [Laconica](http://laconi.ca/) ' .
238 'microblogging software, version ' . LACONICA_VERSION . ', ' .
239 'available under the ' .
240 '[GNU Affero General Public License]' .
241 '(http://www.fsf.org/licensing/licenses/agpl-3.0.html).');
242 $output = common_markup_to_html($instr);
244 common_element_end('div');
245 common_element('img', array('id' => 'cc',
246 'src' => $config['license']['image'],
247 'alt' => $config['license']['title']));
248 common_element_start('p');
249 common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
250 common_element('a', array('class' => 'license',
252 href => $config['license']['url']),
253 $config['license']['title']);
254 common_text(_t('. Contributors should be attributed by full name or nickname.'));
255 common_element_end('p');
256 common_element_end('div');
257 common_element_end('div');
258 common_element_end('body');
259 common_element_end('html');
263 function common_text($txt) {
268 function common_raw($xml) {
273 function common_nav_menu() {
274 $user = common_current_user();
275 common_element_start('ul', array('id' => 'nav'));
277 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
280 common_menu_item(common_local_url('public'), _t('Public'));
281 common_menu_item(common_local_url('doc', array('title' => 'help')),
284 common_menu_item(common_local_url('profilesettings'),
286 common_menu_item(common_local_url('logout'),
289 common_menu_item(common_local_url('login'), _t('Login'));
290 common_menu_item(common_local_url('register'), _t('Register'));
291 common_menu_item(common_local_url('openidlogin'), _t('OpenID'));
293 common_element_end('ul');
296 function common_foot_menu() {
297 common_element_start('ul', array('id' => 'nav_sub'));
298 common_menu_item(common_local_url('doc', array('title' => 'about')),
300 common_menu_item(common_local_url('doc', array('title' => 'faq')),
302 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
304 common_menu_item(common_local_url('doc', array('title' => 'source')),
306 common_menu_item(common_local_url('doc', array('title' => 'contact')),
308 common_element_end('ul');
311 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
314 $lattrs['class'] = 'current';
316 common_element_start('li', $lattrs);
317 $attrs['href'] = $url;
319 $attrs['title'] = $title;
321 common_element('a', $attrs, $text);
322 common_element_end('li');
325 function common_input($id, $label, $value=NULL,$instructions=NULL) {
326 common_element_start('p');
327 common_element('label', array('for' => $id), $label);
328 $attrs = array('name' => $id,
330 'class' => 'input_text',
333 $attrs['value'] = htmlspecialchars($value);
335 common_element('input', $attrs);
337 common_element('span', 'input_instructions', $instructions);
339 common_element_end('p');
342 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
344 common_element_start('p');
345 $attrs = array('name' => $id,
346 'type' => 'checkbox',
347 'class' => 'checkbox',
350 $attrs['value'] = htmlspecialchars($value);
353 $attrs['checked'] = 'checked';
355 common_element('input', $attrs);
358 common_element('span', 'checkbox_label', $label);
361 common_element('span', 'input_instructions', $instructions);
363 common_element_end('p');
366 function common_hidden($id, $value) {
367 common_element('input', array('name' => $id,
373 function common_password($id, $label, $instructions=NULL) {
374 common_element_start('p');
375 common_element('label', array('for' => $id), $label);
376 $attrs = array('name' => $id,
377 'type' => 'password',
378 'class' => 'password',
380 common_element('input', $attrs);
382 common_element('span', 'input_instructions', $instructions);
384 common_element_end('p');
387 function common_submit($id, $label) {
389 common_element_start('p');
390 common_element('input', array('type' => 'submit',
395 common_element_end('p');
398 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
399 common_element_start('p');
400 common_element('label', array('for' => $id), $label);
401 common_element('textarea', array('rows' => 3,
405 ($content) ? $content : '');
407 common_element('span', 'input_instructions', $instructions);
409 common_element_end('p');
412 # salted, hashed passwords are stored in the DB
414 function common_munge_password($password, $id) {
415 return md5($password . $id);
418 # check if a username exists and has matching password
419 function common_check_user($nickname, $password) {
420 $user = User::staticGet('nickname', $nickname);
421 if (is_null($user)) {
424 return (0 == strcmp(common_munge_password($password, $user->id),
429 # is the current user logged in?
430 function common_logged_in() {
431 return (!is_null(common_current_user()));
434 function common_have_session() {
435 return (0 != strcmp(session_id(), ''));
438 function common_ensure_session() {
439 if (!common_have_session()) {
444 function common_set_user($nickname) {
445 if (is_null($nickname) && common_have_session()) {
446 unset($_SESSION['userid']);
449 $user = User::staticGet('nickname', $nickname);
451 common_ensure_session();
452 $_SESSION['userid'] = $user->id;
461 function common_set_cookie($key, $value, $expiration=0) {
462 $path = common_config('site', 'path');
463 $server = common_config('site', 'server');
465 if ($path && ($path != '/')) {
466 $cookiepath = '/' . $path . '/';
470 return setcookie($key,
477 define('REMEMBERME', 'rememberme');
478 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
480 function common_rememberme() {
481 $user = common_current_user();
485 $rm = new Remember_me();
486 $rm->code = common_good_rand(16);
487 $rm->user_id = $user->id;
488 $result = $rm->insert();
490 common_log_db_error($rm, 'INSERT', __FILE__);
493 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
494 common_set_cookie(REMEMBERME,
495 implode(':', array($rm->user_id, $rm->code)),
496 time() + REMEMBERME_EXPIRY);
500 function common_remembered_user() {
503 $packed = $_COOKIE[REMEMBERME];
505 list($id, $code) = explode(':', $packed);
507 $rm = Remember_me::staticGet($code);
508 if ($rm && ($rm->user_id == $id)) {
509 $user = User::staticGet($rm->user_id);
512 $result = $rm->delete();
514 common_log_db_error($rm, 'DELETE', __FILE__);
517 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
518 common_set_user($user->nickname);
519 common_real_login(false);
520 # We issue a new cookie, so they can log in
521 # automatically again after this session
531 # must be called with a valid user!
533 function common_forgetme() {
534 common_set_cookie(REMEMBERME, '', 0);
537 # who is the current user?
538 function common_current_user() {
539 if ($_REQUEST[session_name()]) {
540 common_ensure_session();
541 $id = $_SESSION['userid'];
543 # note: this should cache
544 $user = User::staticGet($id);
548 # that didn't work; try to remember
549 $user = common_remembered_user();
553 # Logins that are 'remembered' aren't 'real' -- they're subject to
554 # cookie-stealing. So, we don't let them do certain things. New reg,
555 # OpenID, and password logins _are_ real.
557 function common_real_login($real=true) {
558 common_ensure_session();
559 $_SESSION['real_login'] = $real;
562 function common_is_real_login() {
563 return common_logged_in() && $_SESSION['real_login'];
566 # get canonical version of nickname for comparison
567 function common_canonical_nickname($nickname) {
568 # XXX: UTF-8 canonicalization (like combining chars)
569 return strtolower($nickname);
572 # get canonical version of email for comparison
573 function common_canonical_email($email) {
574 # XXX: canonicalize UTF-8
575 # XXX: lcase the domain part
579 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$_+!*();/?:~-]))');
581 function common_render_content($text, $notice) {
582 $r = htmlspecialchars($text);
583 $id = $notice->profile_id;
584 $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
585 $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
591 function common_at_link($sender_id, $nickname) {
592 $sender = Profile::staticGet($sender_id);
593 $recipient = common_relative_profile($sender, $nickname);
595 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
601 function common_relative_profile($sender, $nickname, $dt=NULL) {
602 # Try to find profiles this profile is subscribed to that have this nickname
603 $recipient = new Profile();
604 # XXX: use a join instead of a subquery
605 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
606 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
607 if ($recipient->find(TRUE)) {
608 # XXX: should probably differentiate between profiles with
609 # the same name by date of most recent update
612 # Try to find profiles that listen to this profile and that have this nickname
613 $recipient = new Profile();
614 # XXX: use a join instead of a subquery
615 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
616 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
617 if ($recipient->find(TRUE)) {
618 # XXX: should probably differentiate between profiles with
619 # the same name by date of most recent update
622 # If this is a local user, try to find a local user with that nickname.
623 $sender = User::staticGet($sender->id);
625 $recipient_user = User::staticGet('nickname', $nickname);
626 if ($recipient_user) {
627 return $recipient_user->getProfile();
630 # Otherwise, no links. @messages from local users to remote users,
631 # or from remote users to other remote users, are just
632 # outside our ability to make intelligent guesses about
636 // where should the avatar go for this user?
638 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
642 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
644 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
648 function common_avatar_path($filename) {
650 return INSTALLDIR . '/avatar/' . $filename;
653 function common_avatar_url($filename) {
654 return common_path('avatar/'.$filename);
657 function common_avatar_display_url($avatar) {
658 $server = common_config('avatar', 'server');
660 return 'http://'.$server.'/'.$avatar->filename;
666 function common_default_avatar($size) {
667 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
668 AVATAR_STREAM_SIZE => 'stream',
669 AVATAR_MINI_SIZE => 'mini');
670 return theme_path('default-avatar-'.$sizenames[$size].'.png');
673 function common_local_url($action, $args=NULL) {
675 if ($config['site']['fancy']) {
676 return common_fancy_url($action, $args);
678 return common_simple_url($action, $args);
682 function common_fancy_url($action, $args=NULL) {
683 switch (strtolower($action)) {
685 if ($args && $args['page']) {
686 return common_path('?page=' . $args['page']);
688 return common_path('');
691 return common_path('rss');
693 return common_path('xrds');
695 return common_path('doc/'.$args['title']);
701 return common_path('main/'.$action);
702 case 'remotesubscribe':
703 if ($args && $args['nickname']) {
704 return common_path('main/remote?nickname=' . $args['nickname']);
706 return common_path('main/remote');
709 return common_path('main/openid');
712 return common_path('settings/'.$action);
713 case 'profilesettings':
714 return common_path('settings/profile');
715 case 'openidsettings':
716 return common_path('settings/openid');
718 return common_path('notice/new');
720 return common_path('notice/'.$args['notice']);
723 return common_path($args['nickname'].'/'.$action);
724 case 'subscriptions':
728 if ($args && $args['page']) {
729 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
731 return common_path($args['nickname'].'/'.$action);
734 return common_path($args['nickname'].'/all/rss');
736 return common_path($args['nickname'].'/replies/rss');
738 return common_path($args['nickname'].'/rss');
740 if ($args && $args['page']) {
741 return common_path($args['nickname'].'?page=' . $args['page']);
743 return common_path($args['nickname']);
745 case 'confirmaddress':
746 return common_path('main/confirmaddress/'.$args['code']);
748 return common_path('user/'.$args['id']);
749 case 'recoverpassword':
750 $path = 'main/recoverpassword';
752 $path .= '/' . $args['code'];
754 return common_path($path);
756 return common_path('settings/im');
758 return common_simple_url($action, $args);
762 function common_simple_url($action, $args=NULL) {
764 /* XXX: pretty URLs */
767 foreach ($args as $key => $value) {
768 $extra .= "&${key}=${value}";
771 return common_path("index.php?action=${action}${extra}");
774 function common_path($relative) {
776 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
777 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
780 function common_date_string($dt) {
781 // XXX: do some sexy date formatting
782 // return date(DATE_RFC822, $dt);
787 if ($now < $t) { # that shouldn't happen!
788 return common_exact_date($dt);
789 } else if ($diff < 60) {
790 return _t('a few seconds ago');
791 } else if ($diff < 92) {
792 return _t('about a minute ago');
793 } else if ($diff < 3300) {
794 return _t('about ') . round($diff/60) . _t(' minutes ago');
795 } else if ($diff < 5400) {
796 return _t('about an hour ago');
797 } else if ($diff < 22 * 3600) {
798 return _t('about ') . round($diff/3600) . _t(' hours ago');
799 } else if ($diff < 37 * 3600) {
800 return _t('about a day ago');
801 } else if ($diff < 24 * 24 * 3600) {
802 return _t('about ') . round($diff/(24*3600)) . _t(' days ago');
803 } else if ($diff < 46 * 24 * 3600) {
804 return _t('about a month ago');
805 } else if ($diff < 330 * 24 * 3600) {
806 return _t('about ') . round($diff/(30*24*3600)) . _t(' months ago');
807 } else if ($diff < 480 * 24 * 3600) {
808 return _t('about a year ago');
810 return common_exact_date($dt);
814 function common_exact_date($dt) {
816 return date(DATE_RFC850, $t);
819 function common_date_w3dtf($dt) {
821 return date(DATE_W3C, $t);
824 function common_redirect($url, $code=307) {
825 static $status = array(301 => "Moved Permanently",
828 307 => "Temporary Redirect");
829 header("Status: ${code} $status[$code]");
830 header("Location: $url");
832 common_start_xml('a',
833 '-//W3C//DTD XHTML 1.0 Strict//EN',
834 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
835 common_element('a', array('href' => $url), $url);
839 function common_save_replies($notice) {
840 # extract all @messages
841 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
845 $sender = Profile::staticGet($notice->profile_id);
846 # store replied only for first @ (what user/notice what the reply directed,
847 # we assume first @ is it)
848 for ($i=0; $i<count($match[1]); $i++) {
849 $nickname = $match[1][$i];
850 $recipient = common_relative_profile($sender, $nickname, $notice->created);
855 $reply_for = $recipient;
857 $reply = new Reply();
858 $reply->notice_id = $notice->id;
859 $reply->profile_id = $recipient->id;
861 # $recipient_notice = $reply_for->getCurrentNotice($notice->created);
862 $recipient_notice = $reply_for->getCurrentNotice();
863 $reply->replied_id = $recipient_notice->id;
865 $id = $reply->insert();
867 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
868 common_log(LOG_ERROR, 'DB error inserting reply: ' . $last_error->message);
869 common_server_error('DB error inserting reply: ' . $last_error->message);
875 function common_broadcast_notice($notice, $remote=false) {
876 if (common_config('queue', 'enabled')) {
878 return common_enqueue_notice($notice);
880 return common_real_broadcast($notice, $remote);
884 # Stick the notice on the queue
886 function common_enqueue_notice($notice) {
887 $qi = new Queue_item();
888 $qi->notice_id = $notice->id;
889 $qi->created = $notice->created;
890 $result = $qi->insert();
892 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
893 common_log(LOG_ERROR, 'DB error inserting queue item: ' . $last_error->message);
896 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id);
900 function common_real_broadcast($notice, $remote=false) {
903 # Make sure we have the OMB stuff
904 require_once(INSTALLDIR.'/lib/omb.php');
905 $success = omb_broadcast_remote_subscribers($notice);
907 common_log(LOG_ERROR, 'Error in OMB broadcast for notice ' . $notice->id);
911 require_once(INSTALLDIR.'/lib/jabber.php');
912 $success = jabber_broadcast_notice($notice);
914 common_log(LOG_ERROR, 'Error in jabber broadcast for notice ' . $notice->id);
917 // XXX: broadcast notices to SMS
918 // XXX: broadcast notices to other IM
922 function common_broadcast_profile($profile) {
923 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
924 require_once(INSTALLDIR.'/lib/omb.php');
925 omb_broadcast_profile($profile);
926 // XXX: Other broadcasts...?
930 function common_profile_url($nickname) {
931 return common_local_url('showstream', array('nickname' => $nickname));
934 # Don't call if nobody's logged in
936 function common_notice_form($action=NULL, $content=NULL) {
937 $user = common_current_user();
938 assert(!is_null($user));
939 common_element_start('form', array('id' => 'status_form',
941 'action' => common_local_url('newnotice')));
942 common_element_start('p');
943 common_element('label', array('for' => 'status_textarea',
944 'id' => 'status_label'),
945 _t('What\'s up, ').$user->nickname.'?');
946 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
947 common_element('textarea', array('id' => 'status_textarea',
950 'name' => 'status_textarea'),
951 ($content) ? $content : '');
953 common_hidden('returnto', $action);
955 common_element('input', array('id' => 'status_submit',
956 'name' => 'status_submit',
958 'value' => _t('Send')));
959 common_element_end('p');
960 common_element_end('form');
963 function common_mint_tag($extra) {
966 'tag:'.$config['tag']['authority'].','.
967 $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
970 # Should make up a reasonable root URL
972 function common_root_url() {
973 return common_path('');
976 # returns $bytes bytes of random data as a hexadecimal string
977 # "good" here is a goal and not a guarantee
979 function common_good_rand($bytes) {
980 # XXX: use random.org...?
981 if (file_exists('/dev/urandom')) {
982 return common_urandom($bytes);
983 } else { # FIXME: this is probably not good enough
984 return common_mtrand($bytes);
988 function common_urandom($bytes) {
989 $h = fopen('/dev/urandom', 'rb');
991 $src = fread($h, $bytes);
994 for ($i = 0; $i < $bytes; $i++) {
995 $enc .= sprintf("%02x", (ord($src[$i])));
1000 function common_mtrand($bytes) {
1002 for ($i = 0; $i < $bytes; $i++) {
1003 $enc .= sprintf("%02x", mt_rand(0, 255));
1008 function common_set_returnto($url) {
1009 common_ensure_session();
1010 $_SESSION['returnto'] = $url;
1013 function common_get_returnto() {
1014 common_ensure_session();
1015 return $_SESSION['returnto'];
1018 function common_timestamp() {
1019 return date('YmdHis');
1022 // XXX: set up gettext
1028 function common_ensure_syslog() {
1029 static $initialized = false;
1030 if (!$initialized) {
1032 define_syslog_variables();
1033 openlog($config['syslog']['appname'], 0, LOG_USER);
1034 $initialized = true;
1038 function common_log($priority, $msg, $filename=NULL) {
1039 common_ensure_syslog();
1040 syslog($priority, $msg);
1043 function common_debug($msg, $filename=NULL) {
1045 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1047 common_log(LOG_DEBUG, $msg);
1051 function common_log_db_error(&$object, $verb, $filename=NULL) {
1052 $objstr = common_log_objstring($object);
1053 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1054 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1057 function common_log_objstring(&$object) {
1058 if (is_null($object)) {
1061 $arr = $object->toArray();
1063 foreach ($arr as $k => $v) {
1064 $fields[] = "$k='$v'";
1066 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1070 function common_valid_http_url($url) {
1071 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1074 function common_valid_tag($tag) {
1075 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1076 return (Validate::email($matches[1]) ||
1077 preg_match('/^([\w-\.]+)$/', $matches[1]));
1082 # Does a little before-after block for next/prev page
1084 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1086 if ($have_before || $have_after) {
1087 common_element_start('div', array('id' => 'pagination'));
1088 common_element_start('ul', array('id' => 'nav_pagination'));
1092 $pargs = array('page' => $page-1);
1093 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1095 common_element_start('li', 'before');
1096 common_element('a', array('href' => common_local_url($action, $newargs)),
1098 common_element_end('li');
1102 $pargs = array('page' => $page+1);
1103 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1104 common_element_start('li', 'after');
1105 common_element('a', array('href' => common_local_url($action, $newargs)),
1107 common_element_end('li');
1110 if ($have_before || $have_after) {
1111 common_element_end('ul');
1112 common_element_end('div');
1116 /* Following functions are copied from MediaWiki GlobalFunctions.php
1117 * and written by Evan Prodromou. */
1119 function common_accept_to_prefs($accept, $def = '*/*') {
1120 # No arg means accept anything (per HTTP spec)
1122 return array($def => 1);
1127 $parts = explode(',', $accept);
1129 foreach($parts as $part) {
1130 # FIXME: doesn't deal with params like 'text/html; level=1'
1131 @list($value, $qpart) = explode(';', $part);
1133 if(!isset($qpart)) {
1135 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1136 $prefs[$value] = $match[1];
1143 function common_mime_type_match($type, $avail) {
1144 if(array_key_exists($type, $avail)) {
1147 $parts = explode('/', $type);
1148 if(array_key_exists($parts[0] . '/*', $avail)) {
1149 return $parts[0] . '/*';
1150 } elseif(array_key_exists('*/*', $avail)) {
1158 function common_negotiate_type($cprefs, $sprefs) {
1161 foreach(array_keys($sprefs) as $type) {
1162 $parts = explode('/', $type);
1163 if($parts[1] != '*') {
1164 $ckey = common_mime_type_match($type, $cprefs);
1166 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1171 foreach(array_keys($cprefs) as $type) {
1172 $parts = explode('/', $type);
1173 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1174 $skey = common_mime_type_match($type, $sprefs);
1176 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1182 $besttype = "text/html";
1184 foreach(array_keys($combine) as $type) {
1185 if($combine[$type] > $bestq) {
1187 $bestq = $combine[$type];
1194 function common_config($main, $sub) {
1196 return $config[$main][$sub];
1199 function common_copy_args($from) {
1201 $strip = get_magic_quotes_gpc();
1202 foreach ($from as $k => $v) {
1203 $to[$k] = ($strip) ? stripslashes($v) : $v;
1208 function common_user_uri(&$user) {
1209 return common_local_url('userbyid', array('id' => $user->id));
1212 function common_notice_uri(&$notice) {
1213 return common_local_url('shownotice',
1214 array('notice' => $notice->id));
1217 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1219 function common_confirmation_code($bits) {
1220 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1221 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1222 $chars = ceil($bits/5);
1224 for ($i = 0; $i < $chars; $i++) {
1225 # XXX: convert to string and back
1226 $num = hexdec(common_good_rand(1));
1227 # XXX: randomness is too precious to throw away almost
1228 # 40% of the bits we get!
1229 $code .= $codechars[$num%32];
1234 # convert markup to HTML
1236 function common_markup_to_html($c) {
1237 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1238 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1239 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1240 return Markdown($c);