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(_('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 = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
235 $instr = _('**%%site.name%%** is a microblogging service. ');
237 $instr .= sprintf(_('It runs the [Laconica](http://laconi.ca/) ' .
238 'microblogging software, version %s, ' .
239 'available under the ' .
240 '[GNU Affero General Public License]' .
241 '(http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), LACONICA_VERSION);
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(_('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(_('. 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'), _('Public'));
281 common_menu_item(common_local_url('peoplesearch'), _('Search'));
282 common_menu_item(common_local_url('doc', array('title' => 'help')),
285 common_menu_item(common_local_url('profilesettings'),
287 common_menu_item(common_local_url('logout'),
290 common_menu_item(common_local_url('login'), _('Login'));
291 common_menu_item(common_local_url('register'), _('Register'));
292 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
294 common_element_end('ul');
297 function common_foot_menu() {
298 common_element_start('ul', array('id' => 'nav_sub'));
299 common_menu_item(common_local_url('doc', array('title' => 'about')),
301 common_menu_item(common_local_url('doc', array('title' => 'faq')),
303 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
305 common_menu_item(common_local_url('doc', array('title' => 'source')),
307 common_menu_item(common_local_url('doc', array('title' => 'contact')),
309 common_element_end('ul');
312 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
315 $lattrs['class'] = 'current';
317 common_element_start('li', $lattrs);
318 $attrs['href'] = $url;
320 $attrs['title'] = $title;
322 common_element('a', $attrs, $text);
323 common_element_end('li');
326 function common_input($id, $label, $value=NULL,$instructions=NULL) {
327 common_element_start('p');
328 common_element('label', array('for' => $id), $label);
329 $attrs = array('name' => $id,
331 'class' => 'input_text',
334 $attrs['value'] = htmlspecialchars($value);
336 common_element('input', $attrs);
338 common_element('span', 'input_instructions', $instructions);
340 common_element_end('p');
343 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
345 common_element_start('p');
346 $attrs = array('name' => $id,
347 'type' => 'checkbox',
348 'class' => 'checkbox',
351 $attrs['value'] = htmlspecialchars($value);
354 $attrs['checked'] = 'checked';
356 common_element('input', $attrs);
359 common_element('span', 'checkbox_label', $label);
362 common_element('span', 'input_instructions', $instructions);
364 common_element_end('p');
367 function common_hidden($id, $value) {
368 common_element('input', array('name' => $id,
374 function common_password($id, $label, $instructions=NULL) {
375 common_element_start('p');
376 common_element('label', array('for' => $id), $label);
377 $attrs = array('name' => $id,
378 'type' => 'password',
379 'class' => 'password',
381 common_element('input', $attrs);
383 common_element('span', 'input_instructions', $instructions);
385 common_element_end('p');
388 function common_submit($id, $label) {
390 common_element_start('p');
391 common_element('input', array('type' => 'submit',
396 common_element_end('p');
399 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
400 common_element_start('p');
401 common_element('label', array('for' => $id), $label);
402 common_element('textarea', array('rows' => 3,
406 ($content) ? $content : '');
408 common_element('span', 'input_instructions', $instructions);
410 common_element_end('p');
413 # salted, hashed passwords are stored in the DB
415 function common_munge_password($password, $id) {
416 return md5($password . $id);
419 # check if a username exists and has matching password
420 function common_check_user($nickname, $password) {
421 $user = User::staticGet('nickname', $nickname);
422 if (is_null($user)) {
425 if (0 == strcmp(common_munge_password($password, $user->id),
434 # is the current user logged in?
435 function common_logged_in() {
436 return (!is_null(common_current_user()));
439 function common_have_session() {
440 return (0 != strcmp(session_id(), ''));
443 function common_ensure_session() {
444 if (!common_have_session()) {
449 # Three kinds of arguments:
454 function common_set_user($user) {
455 if (is_null($user) && common_have_session()) {
456 unset($_SESSION['userid']);
458 } else if (is_string($user)) {
460 $user = User::staticGet('nickname', $nickname);
461 } else if (!($user instanceof User)) {
466 common_ensure_session();
467 $_SESSION['userid'] = $user->id;
473 function common_set_cookie($key, $value, $expiration=0) {
474 $path = common_config('site', 'path');
475 $server = common_config('site', 'server');
477 if ($path && ($path != '/')) {
478 $cookiepath = '/' . $path . '/';
482 return setcookie($key,
489 define('REMEMBERME', 'rememberme');
490 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
492 function common_rememberme($user=NULL) {
494 $user = common_current_user();
496 common_debug('No current user to remember', __FILE__);
500 $rm = new Remember_me();
501 $rm->code = common_good_rand(16);
502 $rm->user_id = $user->id;
503 $result = $rm->insert();
505 common_log_db_error($rm, 'INSERT', __FILE__);
506 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
509 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
510 common_set_cookie(REMEMBERME,
511 implode(':', array($rm->user_id, $rm->code)),
512 time() + REMEMBERME_EXPIRY);
516 function common_remembered_user() {
519 $packed = $_COOKIE[REMEMBERME];
521 list($id, $code) = explode(':', $packed);
523 $rm = Remember_me::staticGet($code);
524 if ($rm && ($rm->user_id == $id)) {
525 $user = User::staticGet($rm->user_id);
528 $result = $rm->delete();
530 common_log_db_error($rm, 'DELETE', __FILE__);
533 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
534 common_set_user($user->nickname);
535 common_real_login(false);
536 # We issue a new cookie, so they can log in
537 # automatically again after this session
538 common_rememberme($user);
547 # must be called with a valid user!
549 function common_forgetme() {
550 common_set_cookie(REMEMBERME, '', 0);
553 # who is the current user?
554 function common_current_user() {
555 if ($_REQUEST[session_name()]) {
556 common_ensure_session();
557 $id = $_SESSION['userid'];
559 # note: this should cache
560 $user = User::staticGet($id);
564 # that didn't work; try to remember
565 $user = common_remembered_user();
569 # Logins that are 'remembered' aren't 'real' -- they're subject to
570 # cookie-stealing. So, we don't let them do certain things. New reg,
571 # OpenID, and password logins _are_ real.
573 function common_real_login($real=true) {
574 common_ensure_session();
575 $_SESSION['real_login'] = $real;
578 function common_is_real_login() {
579 return common_logged_in() && $_SESSION['real_login'];
582 # get canonical version of nickname for comparison
583 function common_canonical_nickname($nickname) {
584 # XXX: UTF-8 canonicalization (like combining chars)
585 return strtolower($nickname);
588 # get canonical version of email for comparison
589 function common_canonical_email($email) {
590 # XXX: canonicalize UTF-8
591 # XXX: lcase the domain part
595 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$_+!*();/?:~-]))');
597 function common_render_content($text, $notice) {
598 $r = htmlspecialchars($text);
599 $id = $notice->profile_id;
600 $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
601 $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
607 function common_at_link($sender_id, $nickname) {
608 $sender = Profile::staticGet($sender_id);
609 $recipient = common_relative_profile($sender, $nickname);
611 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
617 function common_relative_profile($sender, $nickname, $dt=NULL) {
618 # Try to find profiles this profile is subscribed to that have this nickname
619 $recipient = new Profile();
620 # XXX: use a join instead of a subquery
621 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
622 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
623 if ($recipient->find(TRUE)) {
624 # XXX: should probably differentiate between profiles with
625 # the same name by date of most recent update
628 # Try to find profiles that listen to this profile and that have this nickname
629 $recipient = new Profile();
630 # XXX: use a join instead of a subquery
631 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
632 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
633 if ($recipient->find(TRUE)) {
634 # XXX: should probably differentiate between profiles with
635 # the same name by date of most recent update
638 # If this is a local user, try to find a local user with that nickname.
639 $sender = User::staticGet($sender->id);
641 $recipient_user = User::staticGet('nickname', $nickname);
642 if ($recipient_user) {
643 return $recipient_user->getProfile();
646 # Otherwise, no links. @messages from local users to remote users,
647 # or from remote users to other remote users, are just
648 # outside our ability to make intelligent guesses about
652 // where should the avatar go for this user?
654 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
658 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
660 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
664 function common_avatar_path($filename) {
666 return INSTALLDIR . '/avatar/' . $filename;
669 function common_avatar_url($filename) {
670 return common_path('avatar/'.$filename);
673 function common_avatar_display_url($avatar) {
674 $server = common_config('avatar', 'server');
676 return 'http://'.$server.'/'.$avatar->filename;
682 function common_default_avatar($size) {
683 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
684 AVATAR_STREAM_SIZE => 'stream',
685 AVATAR_MINI_SIZE => 'mini');
686 return theme_path('default-avatar-'.$sizenames[$size].'.png');
689 function common_local_url($action, $args=NULL) {
691 if ($config['site']['fancy']) {
692 return common_fancy_url($action, $args);
694 return common_simple_url($action, $args);
698 function common_fancy_url($action, $args=NULL) {
699 switch (strtolower($action)) {
701 if ($args && $args['page']) {
702 return common_path('?page=' . $args['page']);
704 return common_path('');
707 return common_path('rss');
709 return common_path('xrds');
711 return common_path('doc/'.$args['title']);
717 return common_path('main/'.$action);
718 case 'remotesubscribe':
719 if ($args && $args['nickname']) {
720 return common_path('main/remote?nickname=' . $args['nickname']);
722 return common_path('main/remote');
725 return common_path('main/openid');
728 return common_path('settings/'.$action);
729 case 'profilesettings':
730 return common_path('settings/profile');
731 case 'openidsettings':
732 return common_path('settings/openid');
734 if ($args && $args['replyto']) {
735 return common_path('notice/new?replyto='.$args['replyto']);
737 return common_path('notice/new');
740 return common_path('notice/'.$args['notice']);
743 return common_path($args['nickname'].'/'.$action);
744 case 'subscriptions':
748 if ($args && $args['page']) {
749 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
751 return common_path($args['nickname'].'/'.$action);
754 return common_path($args['nickname'].'/all/rss');
756 return common_path($args['nickname'].'/replies/rss');
758 return common_path($args['nickname'].'/rss');
760 if ($args && $args['page']) {
761 return common_path($args['nickname'].'?page=' . $args['page']);
763 return common_path($args['nickname']);
765 case 'confirmaddress':
766 return common_path('main/confirmaddress/'.$args['code']);
768 return common_path('user/'.$args['id']);
769 case 'recoverpassword':
770 $path = 'main/recoverpassword';
772 $path .= '/' . $args['code'];
774 return common_path($path);
776 return common_path('settings/im');
778 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
780 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
781 case 'noticesearchrss':
782 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
783 case 'avatarbynickname':
784 return common_path($args['nickname'].'/avatar/'.$args['size']);
786 return common_simple_url($action, $args);
790 function common_simple_url($action, $args=NULL) {
792 /* XXX: pretty URLs */
795 foreach ($args as $key => $value) {
796 $extra .= "&${key}=${value}";
799 return common_path("index.php?action=${action}${extra}");
802 function common_path($relative) {
804 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
805 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
808 function common_date_string($dt) {
809 // XXX: do some sexy date formatting
810 // return date(DATE_RFC822, $dt);
815 if ($now < $t) { # that shouldn't happen!
816 return common_exact_date($dt);
817 } else if ($diff < 60) {
818 return _('a few seconds ago');
819 } else if ($diff < 92) {
820 return _('about a minute ago');
821 } else if ($diff < 3300) {
822 return sprintf(_('about %d minutes ago'), round($diff/60));
823 } else if ($diff < 5400) {
824 return _('about an hour ago');
825 } else if ($diff < 22 * 3600) {
826 return sprintf(_('about %d hours ago'), round($diff/3600));
827 } else if ($diff < 37 * 3600) {
828 return _('about a day ago');
829 } else if ($diff < 24 * 24 * 3600) {
830 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
831 } else if ($diff < 46 * 24 * 3600) {
832 return _('about a month ago');
833 } else if ($diff < 330 * 24 * 3600) {
834 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
835 } else if ($diff < 480 * 24 * 3600) {
836 return _('about a year ago');
838 return common_exact_date($dt);
842 function common_exact_date($dt) {
844 return date(DATE_RFC850, $t);
847 function common_date_w3dtf($dt) {
849 return date(DATE_W3C, $t);
852 function common_redirect($url, $code=307) {
853 static $status = array(301 => "Moved Permanently",
856 307 => "Temporary Redirect");
857 header("Status: ${code} $status[$code]");
858 header("Location: $url");
860 common_start_xml('a',
861 '-//W3C//DTD XHTML 1.0 Strict//EN',
862 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
863 common_element('a', array('href' => $url), $url);
867 function common_save_replies($notice) {
868 # extract all @messages
869 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
873 $sender = Profile::staticGet($notice->profile_id);
874 # store replied only for first @ (what user/notice what the reply directed,
875 # we assume first @ is it)
876 for ($i=0; $i<count($match[1]); $i++) {
877 $nickname = $match[1][$i];
878 $recipient = common_relative_profile($sender, $nickname, $notice->created);
882 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
883 $reply_for = $recipient;
884 $recipient_notice = $reply_for->getCurrentNotice();
885 $orig = clone($notice);
886 $notice->reply_to = $recipient_notice->id;
887 $notice->update($orig);
889 $reply = new Reply();
890 $reply->notice_id = $notice->id;
891 $reply->profile_id = $recipient->id;
892 $id = $reply->insert();
894 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
895 common_log(LOG_ERROR, 'DB error inserting reply: ' . $last_error->message);
896 common_server_error(_('DB error inserting reply: %s'), $last_error->message);
902 function common_broadcast_notice($notice, $remote=false) {
903 if (common_config('queue', 'enabled')) {
905 return common_enqueue_notice($notice);
907 return common_real_broadcast($notice, $remote);
911 # Stick the notice on the queue
913 function common_enqueue_notice($notice) {
914 $qi = new Queue_item();
915 $qi->notice_id = $notice->id;
916 $qi->created = $notice->created;
917 $result = $qi->insert();
919 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
920 common_log(LOG_ERROR, 'DB error inserting queue item: ' . $last_error->message);
923 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id);
927 function common_real_broadcast($notice, $remote=false) {
930 # Make sure we have the OMB stuff
931 require_once(INSTALLDIR.'/lib/omb.php');
932 $success = omb_broadcast_remote_subscribers($notice);
934 common_log(LOG_ERROR, 'Error in OMB broadcast for notice ' . $notice->id);
938 require_once(INSTALLDIR.'/lib/jabber.php');
939 $success = jabber_broadcast_notice($notice);
941 common_log(LOG_ERROR, 'Error in jabber broadcast for notice ' . $notice->id);
944 // XXX: broadcast notices to SMS
945 // XXX: broadcast notices to other IM
949 function common_broadcast_profile($profile) {
950 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
951 require_once(INSTALLDIR.'/lib/omb.php');
952 omb_broadcast_profile($profile);
953 // XXX: Other broadcasts...?
957 function common_profile_url($nickname) {
958 return common_local_url('showstream', array('nickname' => $nickname));
961 # Don't call if nobody's logged in
963 function common_notice_form($action=NULL, $content=NULL) {
964 $user = common_current_user();
965 assert(!is_null($user));
966 common_element_start('form', array('id' => 'status_form',
968 'action' => common_local_url('newnotice')));
969 common_element_start('p');
970 common_element('label', array('for' => 'status_textarea',
971 'id' => 'status_label'),
972 sprintf(_('What\'s up, %s?'), $user->nickname));
973 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
974 common_element('textarea', array('id' => 'status_textarea',
977 'name' => 'status_textarea'),
978 ($content) ? $content : '');
980 common_hidden('returnto', $action);
982 common_element('input', array('id' => 'status_submit',
983 'name' => 'status_submit',
985 'value' => _('Send')));
986 common_element_end('p');
987 common_element_end('form');
990 function common_mint_tag($extra) {
993 'tag:'.$config['tag']['authority'].','.
994 $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
997 # Should make up a reasonable root URL
999 function common_root_url() {
1000 return common_path('');
1003 # returns $bytes bytes of random data as a hexadecimal string
1004 # "good" here is a goal and not a guarantee
1006 function common_good_rand($bytes) {
1007 # XXX: use random.org...?
1008 if (file_exists('/dev/urandom')) {
1009 return common_urandom($bytes);
1010 } else { # FIXME: this is probably not good enough
1011 return common_mtrand($bytes);
1015 function common_urandom($bytes) {
1016 $h = fopen('/dev/urandom', 'rb');
1018 $src = fread($h, $bytes);
1021 for ($i = 0; $i < $bytes; $i++) {
1022 $enc .= sprintf("%02x", (ord($src[$i])));
1027 function common_mtrand($bytes) {
1029 for ($i = 0; $i < $bytes; $i++) {
1030 $enc .= sprintf("%02x", mt_rand(0, 255));
1035 function common_set_returnto($url) {
1036 common_ensure_session();
1037 $_SESSION['returnto'] = $url;
1040 function common_get_returnto() {
1041 common_ensure_session();
1042 return $_SESSION['returnto'];
1045 function common_timestamp() {
1046 return date('YmdHis');
1049 function common_ensure_syslog() {
1050 static $initialized = false;
1051 if (!$initialized) {
1053 define_syslog_variables();
1054 openlog($config['syslog']['appname'], 0, LOG_USER);
1055 $initialized = true;
1059 function common_log($priority, $msg, $filename=NULL) {
1060 $logfile = common_config('site', 'logfile');
1062 $log = fopen($logfile, "a");
1064 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1065 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1066 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1067 fwrite($log, $output);
1071 common_ensure_syslog();
1072 syslog($priority, $msg);
1076 function common_debug($msg, $filename=NULL) {
1078 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1080 common_log(LOG_DEBUG, $msg);
1084 function common_log_db_error(&$object, $verb, $filename=NULL) {
1085 $objstr = common_log_objstring($object);
1086 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1087 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1090 function common_log_objstring(&$object) {
1091 if (is_null($object)) {
1094 $arr = $object->toArray();
1096 foreach ($arr as $k => $v) {
1097 $fields[] = "$k='$v'";
1099 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1103 function common_valid_http_url($url) {
1104 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1107 function common_valid_tag($tag) {
1108 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1109 return (Validate::email($matches[1]) ||
1110 preg_match('/^([\w-\.]+)$/', $matches[1]));
1115 # Does a little before-after block for next/prev page
1117 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1119 if ($have_before || $have_after) {
1120 common_element_start('div', array('id' => 'pagination'));
1121 common_element_start('ul', array('id' => 'nav_pagination'));
1125 $pargs = array('page' => $page-1);
1126 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1128 common_element_start('li', 'before');
1129 common_element('a', array('href' => common_local_url($action, $newargs)),
1131 common_element_end('li');
1135 $pargs = array('page' => $page+1);
1136 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1137 common_element_start('li', 'after');
1138 common_element('a', array('href' => common_local_url($action, $newargs)),
1140 common_element_end('li');
1143 if ($have_before || $have_after) {
1144 common_element_end('ul');
1145 common_element_end('div');
1149 /* Following functions are copied from MediaWiki GlobalFunctions.php
1150 * and written by Evan Prodromou. */
1152 function common_accept_to_prefs($accept, $def = '*/*') {
1153 # No arg means accept anything (per HTTP spec)
1155 return array($def => 1);
1160 $parts = explode(',', $accept);
1162 foreach($parts as $part) {
1163 # FIXME: doesn't deal with params like 'text/html; level=1'
1164 @list($value, $qpart) = explode(';', $part);
1166 if(!isset($qpart)) {
1168 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1169 $prefs[$value] = $match[1];
1176 function common_mime_type_match($type, $avail) {
1177 if(array_key_exists($type, $avail)) {
1180 $parts = explode('/', $type);
1181 if(array_key_exists($parts[0] . '/*', $avail)) {
1182 return $parts[0] . '/*';
1183 } elseif(array_key_exists('*/*', $avail)) {
1191 function common_negotiate_type($cprefs, $sprefs) {
1194 foreach(array_keys($sprefs) as $type) {
1195 $parts = explode('/', $type);
1196 if($parts[1] != '*') {
1197 $ckey = common_mime_type_match($type, $cprefs);
1199 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1204 foreach(array_keys($cprefs) as $type) {
1205 $parts = explode('/', $type);
1206 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1207 $skey = common_mime_type_match($type, $sprefs);
1209 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1215 $besttype = "text/html";
1217 foreach(array_keys($combine) as $type) {
1218 if($combine[$type] > $bestq) {
1220 $bestq = $combine[$type];
1227 function common_config($main, $sub) {
1229 return $config[$main][$sub];
1232 function common_copy_args($from) {
1234 $strip = get_magic_quotes_gpc();
1235 foreach ($from as $k => $v) {
1236 $to[$k] = ($strip) ? stripslashes($v) : $v;
1241 function common_user_uri(&$user) {
1242 return common_local_url('userbyid', array('id' => $user->id));
1245 function common_notice_uri(&$notice) {
1246 return common_local_url('shownotice',
1247 array('notice' => $notice->id));
1250 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1252 function common_confirmation_code($bits) {
1253 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1254 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1255 $chars = ceil($bits/5);
1257 for ($i = 0; $i < $chars; $i++) {
1258 # XXX: convert to string and back
1259 $num = hexdec(common_good_rand(1));
1260 # XXX: randomness is too precious to throw away almost
1261 # 40% of the bits we get!
1262 $code .= $codechars[$num%32];
1267 # convert markup to HTML
1269 function common_markup_to_html($c) {
1270 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1271 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1272 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1273 return Markdown($c);