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);
111 if (!is_null($content)) {
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 function common_init_language() {
135 mb_internal_encoding('UTF-8');
136 $language = common_language();
137 # So we don't have to make people install the gettext locales
138 putenv('LANGUAGE='.$language);
139 putenv('LANG='.$language);
140 $locale_set = setlocale(LC_ALL, $language . ".utf8",
142 $language . ".utf-8",
143 $language . ".UTF-8",
145 bindtextdomain("laconica", common_config('site','locale_path'));
146 bind_textdomain_codeset("laconica", "UTF-8");
147 textdomain("laconica");
148 setlocale(LC_CTYPE, 'C');
149 common_log(LOG_INFO,'Language requested:'.$language.' Locale set:'.$locale_set,__FILE__);
152 define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2');
154 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
160 common_element_start('head');
161 common_element('title', NULL,
162 $pagetitle . " - " . $config['site']['name']);
163 common_element('link', array('rel' => 'stylesheet',
164 'type' => 'text/css',
165 'href' => theme_path('display.css') . '?version=' . LACONICA_VERSION,
166 'media' => 'screen, projection, tv'));
167 foreach (array(6,7) as $ver) {
168 if (file_exists(theme_file('ie'.$ver.'.css'))) {
169 # Yes, IE people should be put in jail.
170 $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
171 'href="'.theme_path('ie'.$ver.'.css').'?version='.LACONICA_VERSION.'" /><![endif]');
175 common_element('script', array('type' => 'text/javascript',
176 'src' => common_path('js/jquery.min.js')),
178 common_element('script', array('type' => 'text/javascript',
179 'src' => common_path('js/jquery.form.js')),
181 common_element('script', array('type' => 'text/javascript',
182 'src' => common_path('js/util.js?version='.LACONICA_VERSION)),
184 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
185 'href' => common_local_url('opensearch', array('type' => 'people')),
186 'title' => common_config('site', 'name').' People Search'));
188 common_element('link', array('rel' => 'search', 'type' => 'application/opensearchdescription+xml',
189 'href' => common_local_url('opensearch', array('type' => 'notice')),
190 'title' => common_config('site', 'name').' Notice Search'));
194 call_user_func($callable, $data);
196 call_user_func($callable);
199 common_element_end('head');
200 common_element_start('body');
201 common_element_start('div', array('id' => 'wrap'));
202 common_element_start('div', array('id' => 'header'));
204 if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
205 || file_exists(theme_file('logo.png')))
207 common_element_start('a', array('href' => common_local_url('public')));
208 common_element('img', array('src' => isset($config['site']['logo']) ?
209 ($config['site']['logo']) : theme_path('logo.png'),
210 'alt' => $config['site']['name'],
212 common_element_end('a');
214 common_element_start('p', array('id' => 'branding'));
215 common_element('a', array('href' => common_local_url('public')),
216 $config['site']['name']);
217 common_element_end('p');
220 common_element('h1', 'pagetitle', $pagetitle);
224 call_user_func($headercall, $data);
226 call_user_func($headercall);
229 common_element_end('div');
230 common_element_start('div', array('id' => 'content'));
233 function common_start_html($type=NULL) {
236 $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
238 # XXX: allow content negotiation for RDF, RSS, or XRDS
240 $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
241 common_accept_to_prefs(PAGE_TYPE_PREFS));
244 common_user_error(_('This page is not available in a media type you accept'), 406);
249 header('Content-Type: '.$type);
251 common_start_xml('html',
252 '-//W3C//DTD XHTML 1.0 Strict//EN',
253 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
255 # FIXME: correct language for interface
257 $language = common_language();
259 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
260 'xml:lang' => $language,
261 'lang' => $language));
264 function common_show_footer() {
266 common_element_end('div'); # content div
268 common_element_start('div', array('id' => 'footer'));
269 common_element_start('div', 'laconica');
270 if (common_config('site', 'broughtby')) {
271 $instr = _('**%%site.name%%** is a microblogging service brought to you by [%%site.broughtby%%](%%site.broughtbyurl%%). ');
273 $instr = _('**%%site.name%%** is a microblogging service. ');
275 $instr .= sprintf(_('It runs the [Laconica](http://laconi.ca/) microblogging software, version %s, available under the [GNU Affero General Public License](http://www.fsf.org/licensing/licenses/agpl-3.0.html).'), LACONICA_VERSION);
276 $output = common_markup_to_html($instr);
278 common_element_end('div');
279 common_element('img', array('id' => 'cc',
280 'src' => $config['license']['image'],
281 'alt' => $config['license']['title']));
282 common_element_start('p');
283 common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
284 common_element('a', array('class' => 'license',
286 'href' => $config['license']['url']),
287 $config['license']['title']);
288 common_text(_('. Contributors should be attributed by full name or nickname.'));
289 common_element_end('p');
290 common_element_end('div');
291 common_element_end('div');
292 common_element_end('body');
293 common_element_end('html');
297 function common_text($txt) {
302 function common_raw($xml) {
307 function common_nav_menu() {
308 $user = common_current_user();
309 common_element_start('ul', array('id' => 'nav'));
311 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
314 common_menu_item(common_local_url('peoplesearch'), _('Search'));
315 common_menu_item(common_local_url('tags'), _('Tags'));
317 common_menu_item(common_local_url('profilesettings'),
319 common_menu_item(common_local_url('invite'),
321 common_menu_item(common_local_url('logout'),
324 common_menu_item(common_local_url('login'), _('Login'));
325 if (!common_config('site', 'closed')) {
326 common_menu_item(common_local_url('register'), _('Register'));
328 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
330 common_element_end('ul');
333 function common_foot_menu() {
334 common_element_start('ul', array('id' => 'nav_sub'));
335 common_menu_item(common_local_url('doc', array('title' => 'help')),
337 common_menu_item(common_local_url('doc', array('title' => 'about')),
339 common_menu_item(common_local_url('doc', array('title' => 'faq')),
341 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
343 common_menu_item(common_local_url('doc', array('title' => 'source')),
345 common_menu_item(common_local_url('doc', array('title' => 'contact')),
347 common_element_end('ul');
350 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
353 $lattrs['class'] = 'current';
355 common_element_start('li', $lattrs);
356 $attrs['href'] = $url;
358 $attrs['title'] = $title;
360 common_element('a', $attrs, $text);
361 common_element_end('li');
364 function common_input($id, $label, $value=NULL,$instructions=NULL) {
365 common_element_start('p');
366 common_element('label', array('for' => $id), $label);
367 $attrs = array('name' => $id,
369 'class' => 'input_text',
372 $attrs['value'] = htmlspecialchars($value);
374 common_element('input', $attrs);
376 common_element('span', 'input_instructions', $instructions);
378 common_element_end('p');
381 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true', $disabled=false)
383 common_element_start('p');
384 $attrs = array('name' => $id,
385 'type' => 'checkbox',
386 'class' => 'checkbox',
389 $attrs['value'] = htmlspecialchars($value);
392 $attrs['checked'] = 'checked';
395 $attrs['disabled'] = 'true';
397 common_element('input', $attrs);
400 common_element('span', 'checkbox_label', $label);
403 common_element('span', 'input_instructions', $instructions);
405 common_element_end('p');
408 function common_dropdown($id, $label, $content, $instructions=NULL, $blank_select=FALSE, $selected=NULL) {
409 common_element_start('p');
410 common_element('label', array('for' => $id), $label);
411 common_element_start('select', array('id' => $id, 'name' => $id));
413 common_element('option', array('value' => ''));
415 foreach ($content as $value => $option) {
416 if ($value == $selected) {
417 common_element('option', array('value' => $value, 'selected' => $value), $option);
419 common_element('option', array('value' => $value), $option);
422 common_element_end('select');
424 common_element('span', 'input_instructions', $instructions);
426 common_element_end('p');
428 function common_hidden($id, $value) {
429 common_element('input', array('name' => $id,
435 function common_password($id, $label, $instructions=NULL) {
436 common_element_start('p');
437 common_element('label', array('for' => $id), $label);
438 $attrs = array('name' => $id,
439 'type' => 'password',
440 'class' => 'password',
442 common_element('input', $attrs);
444 common_element('span', 'input_instructions', $instructions);
446 common_element_end('p');
449 function common_submit($id, $label, $cls='submit') {
451 common_element_start('p');
452 common_element('input', array('type' => 'submit',
457 common_element_end('p');
460 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
461 common_element_start('p');
462 common_element('label', array('for' => $id), $label);
463 common_element('textarea', array('rows' => 3,
467 ($content) ? $content : '');
469 common_element('span', 'input_instructions', $instructions);
471 common_element_end('p');
474 function common_timezone() {
475 if (common_logged_in()) {
476 $user = common_current_user();
477 if ($user->timezone) {
478 return $user->timezone;
483 return $config['site']['timezone'];
486 function common_language() {
488 // If there is a user logged in and they've set a language preference
489 // then return that one...
490 if (common_logged_in()) {
491 $user = common_current_user();
492 $user_language = $user->language;
494 return $user_language;
497 // Otherwise, find the best match for the languages requested by the
499 $httplang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : NULL;
500 if (!empty($httplang)) {
501 $language = client_prefered_language($httplang);
506 // Finally, if none of the above worked, use the site's default...
507 return common_config('site', 'language');
509 # salted, hashed passwords are stored in the DB
511 function common_munge_password($password, $id) {
512 return md5($password . $id);
515 # check if a username exists and has matching password
516 function common_check_user($nickname, $password) {
517 # NEVER allow blank passwords, even if they match the DB
518 if (mb_strlen($password) == 0) {
521 $user = User::staticGet('nickname', $nickname);
522 if (is_null($user)) {
525 if (0 == strcmp(common_munge_password($password, $user->id),
534 # is the current user logged in?
535 function common_logged_in() {
536 return (!is_null(common_current_user()));
539 function common_have_session() {
540 return (0 != strcmp(session_id(), ''));
543 function common_ensure_session() {
544 if (!common_have_session()) {
549 # Three kinds of arguments:
554 function common_set_user($user) {
555 if (is_null($user) && common_have_session()) {
556 unset($_SESSION['userid']);
558 } else if (is_string($user)) {
560 $user = User::staticGet('nickname', $nickname);
561 } else if (!($user instanceof User)) {
566 common_ensure_session();
567 $_SESSION['userid'] = $user->id;
573 function common_set_cookie($key, $value, $expiration=0) {
574 $path = common_config('site', 'path');
575 $server = common_config('site', 'server');
577 if ($path && ($path != '/')) {
578 $cookiepath = '/' . $path . '/';
582 return setcookie($key,
589 define('REMEMBERME', 'rememberme');
590 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
592 function common_rememberme($user=NULL) {
594 $user = common_current_user();
596 common_debug('No current user to remember', __FILE__);
600 $rm = new Remember_me();
601 $rm->code = common_good_rand(16);
602 $rm->user_id = $user->id;
603 $result = $rm->insert();
605 common_log_db_error($rm, 'INSERT', __FILE__);
606 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
609 common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
610 common_set_cookie(REMEMBERME,
611 implode(':', array($rm->user_id, $rm->code)),
612 time() + REMEMBERME_EXPIRY);
616 function common_remembered_user() {
619 $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
621 list($id, $code) = explode(':', $packed);
623 $rm = Remember_me::staticGet($code);
624 if ($rm && ($rm->user_id == $id)) {
625 $user = User::staticGet($rm->user_id);
628 $result = $rm->delete();
630 common_log_db_error($rm, 'DELETE', __FILE__);
633 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
634 common_set_user($user->nickname);
635 common_real_login(false);
636 # We issue a new cookie, so they can log in
637 # automatically again after this session
638 common_rememberme($user);
647 # must be called with a valid user!
649 function common_forgetme() {
650 common_set_cookie(REMEMBERME, '', 0);
653 # who is the current user?
654 function common_current_user() {
655 if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
656 common_ensure_session();
657 $id = isset($_SESSION['userid']) ? $_SESSION['userid'] : false;
659 # note: this should cache
660 $user = User::staticGet($id);
664 # that didn't work; try to remember
665 $user = common_remembered_user();
667 common_debug("Got User " . $user->nickname);
668 common_debug("Faking session on remembered user");
669 $_SESSION['userid'] = $user->id;
674 # Logins that are 'remembered' aren't 'real' -- they're subject to
675 # cookie-stealing. So, we don't let them do certain things. New reg,
676 # OpenID, and password logins _are_ real.
678 function common_real_login($real=true) {
679 common_ensure_session();
680 $_SESSION['real_login'] = $real;
683 function common_is_real_login() {
684 return common_logged_in() && $_SESSION['real_login'];
687 # get canonical version of nickname for comparison
688 function common_canonical_nickname($nickname) {
689 # XXX: UTF-8 canonicalization (like combining chars)
690 return strtolower($nickname);
693 # get canonical version of email for comparison
694 function common_canonical_email($email) {
695 # XXX: canonicalize UTF-8
696 # XXX: lcase the domain part
700 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$_+!*();/?:~-]))');
702 function common_render_content($text, $notice) {
703 $r = common_render_text($text);
704 $id = $notice->profile_id;
705 $r = preg_replace('/(^|\s+)@([A-Za-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
706 $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
710 function common_render_text($text) {
711 $r = htmlspecialchars($text);
713 $r = preg_replace('/[\x{0}-\x{8}\x{b}-\x{c}\x{e}-\x{19}]/', '', $r);
714 $r = preg_replace_callback('@https?://[^\]>\s]+@', 'common_render_uri_thingy', $r);
715 $r = preg_replace('/(^|\s+)#([A-Za-z0-9_\-\.]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
720 function common_render_uri_thingy($matches) {
724 # Some heuristics for extracting URIs from surrounding punctuation
725 # Strip from trailing text...
726 if (preg_match('/^(.*)([,.:"\']+)$/', $uri, $matches)) {
728 $trailer = $matches[2];
732 ']' => '[', # technically disallowed in URIs, but used in Java docs
733 ')' => '(', # far too frequent in Wikipedia and MSDN
735 $final = substr($uri, -1, 1);
736 if (isset($pairs[$final])) {
737 $openers = substr_count($uri, $pairs[$final]);
738 $closers = substr_count($uri, $final);
739 if ($closers > $openers) {
740 // Assume the paren was opened outside the URI
741 $uri = substr($uri, 0, -1);
742 $trailer = $final . $trailer;
745 return '<a href="' . $uri . '" class="extlink">' . $uri . '</a>' . $trailer;
748 function common_tag_link($tag) {
749 $canonical = common_canonical_tag($tag);
750 $url = common_local_url('tag', array('tag' => $canonical));
751 return '<a href="' . htmlspecialchars($url) . '" rel="tag" class="hashlink">' . htmlspecialchars($tag) . '</a>';
754 function common_canonical_tag($tag) {
755 return strtolower(str_replace(array('-', '_', '.'), '', $tag));
758 function common_at_link($sender_id, $nickname) {
759 $sender = Profile::staticGet($sender_id);
760 $recipient = common_relative_profile($sender, common_canonical_nickname($nickname));
762 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
768 function common_relative_profile($sender, $nickname, $dt=NULL) {
769 # Try to find profiles this profile is subscribed to that have this nickname
770 $recipient = new Profile();
771 # XXX: use a join instead of a subquery
772 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
773 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
774 if ($recipient->find(TRUE)) {
775 # XXX: should probably differentiate between profiles with
776 # the same name by date of most recent update
779 # Try to find profiles that listen to this profile and that have this nickname
780 $recipient = new Profile();
781 # XXX: use a join instead of a subquery
782 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
783 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
784 if ($recipient->find(TRUE)) {
785 # XXX: should probably differentiate between profiles with
786 # the same name by date of most recent update
789 # If this is a local user, try to find a local user with that nickname.
790 $sender = User::staticGet($sender->id);
792 $recipient_user = User::staticGet('nickname', $nickname);
793 if ($recipient_user) {
794 return $recipient_user->getProfile();
797 # Otherwise, no links. @messages from local users to remote users,
798 # or from remote users to other remote users, are just
799 # outside our ability to make intelligent guesses about
803 // where should the avatar go for this user?
805 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
809 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
811 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
815 function common_avatar_path($filename) {
817 return INSTALLDIR . '/avatar/' . $filename;
820 function common_avatar_url($filename) {
821 return common_path('avatar/'.$filename);
824 function common_avatar_display_url($avatar) {
825 $server = common_config('avatar', 'server');
827 return 'http://'.$server.'/'.$avatar->filename;
833 function common_default_avatar($size) {
834 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
835 AVATAR_STREAM_SIZE => 'stream',
836 AVATAR_MINI_SIZE => 'mini');
837 return theme_path('default-avatar-'.$sizenames[$size].'.png');
840 function common_local_url($action, $args=NULL, $fragment=NULL) {
842 if (common_config('site','fancy')) {
843 $url = common_fancy_url($action, $args);
845 $url = common_simple_url($action, $args);
847 if (!is_null($fragment)) {
848 $url .= '#'.$fragment;
853 function common_fancy_url($action, $args=NULL) {
854 switch (strtolower($action)) {
856 if ($args && isset($args['page'])) {
857 return common_path('?page=' . $args['page']);
859 return common_path('');
862 return common_path('rss');
864 return common_path('xrds');
866 if ($args && $args['type']) {
867 return common_path('opensearch/'.$args['type']);
869 return common_path('opensearch/people');
872 return common_path('doc/'.$args['title']);
878 return common_path('main/'.$action);
880 if ($args && $args['code']) {
881 return common_path('main/register/'.$args['code']);
883 return common_path('main/register');
885 case 'remotesubscribe':
886 if ($args && $args['nickname']) {
887 return common_path('main/remote?nickname=' . $args['nickname']);
889 return common_path('main/remote');
892 return common_path('main/openid');
893 case 'profilesettings':
894 return common_path('settings/profile');
895 case 'emailsettings':
896 return common_path('settings/email');
897 case 'openidsettings':
898 return common_path('settings/openid');
900 return common_path('settings/sms');
901 case 'twittersettings':
902 return common_path('settings/twitter');
904 if ($args && $args['replyto']) {
905 return common_path('notice/new?replyto='.$args['replyto']);
907 return common_path('notice/new');
910 return common_path('notice/'.$args['notice']);
912 if ($args && $args['notice']) {
913 return common_path('notice/delete/'.$args['notice']);
915 return common_path('notice/delete');
919 return common_path($args['nickname'].'/'.$action);
920 case 'subscriptions':
926 if ($args && isset($args['page'])) {
927 return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
929 return common_path($args['nickname'].'/'.$action);
932 return common_path($args['nickname'].'/all/rss');
934 return common_path($args['nickname'].'/replies/rss');
936 return common_path($args['nickname'].'/rss');
938 if ($args && isset($args['page'])) {
939 return common_path($args['nickname'].'?page=' . $args['page']);
941 return common_path($args['nickname']);
943 case 'confirmaddress':
944 return common_path('main/confirmaddress/'.$args['code']);
946 return common_path('user/'.$args['id']);
947 case 'recoverpassword':
948 $path = 'main/recoverpassword';
950 $path .= '/' . $args['code'];
952 return common_path($path);
954 return common_path('settings/im');
956 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
958 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
959 case 'noticesearchrss':
960 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
961 case 'avatarbynickname':
962 return common_path($args['nickname'].'/avatar/'.$args['size']);
964 if (isset($args['tag']) && $args['tag']) {
965 $path = 'tag/' . $args['tag'];
970 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
972 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
974 return common_path('main/favor');
976 return common_path('main/disfavor');
977 case 'showfavorites':
978 if ($args && isset($args['page'])) {
979 return common_path($args['nickname'].'/favorites?page=' . $args['page']);
981 return common_path($args['nickname'].'/favorites');
984 return common_path($args['nickname'].'/favorites/rss');
986 return common_path('message/' . $args['message']);
988 return common_path('message/new' . (($args) ? ('?' . http_build_query($args)) : ''));
990 # XXX: do fancy URLs for all the API methods
991 switch (strtolower($args['apiaction'])) {
993 switch (strtolower($args['method'])) {
994 case 'user_timeline.rss':
995 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
996 case 'user_timeline.atom':
997 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
998 case 'user_timeline.rss':
999 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1000 case 'user_timeline.atom':
1001 return common_path('api/statuses/user_timeline/'.$args['argument'].'.rss');
1002 default: return common_simple_url($action, $args);
1004 default: return common_simple_url($action, $args);
1007 if ($args && isset($args['seconds'])) {
1008 return common_path('main/sup?seconds='.$args['seconds']);
1010 return common_path('main/sup');
1013 return common_simple_url($action, $args);
1017 function common_simple_url($action, $args=NULL) {
1019 /* XXX: pretty URLs */
1022 foreach ($args as $key => $value) {
1023 $extra .= "&${key}=${value}";
1026 return common_path("index.php?action=${action}${extra}");
1029 function common_path($relative) {
1031 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
1032 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
1035 function common_date_string($dt) {
1036 // XXX: do some sexy date formatting
1037 // return date(DATE_RFC822, $dt);
1038 $t = strtotime($dt);
1042 if ($now < $t) { # that shouldn't happen!
1043 return common_exact_date($dt);
1044 } else if ($diff < 60) {
1045 return _('a few seconds ago');
1046 } else if ($diff < 92) {
1047 return _('about a minute ago');
1048 } else if ($diff < 3300) {
1049 return sprintf(_('about %d minutes ago'), round($diff/60));
1050 } else if ($diff < 5400) {
1051 return _('about an hour ago');
1052 } else if ($diff < 22 * 3600) {
1053 return sprintf(_('about %d hours ago'), round($diff/3600));
1054 } else if ($diff < 37 * 3600) {
1055 return _('about a day ago');
1056 } else if ($diff < 24 * 24 * 3600) {
1057 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
1058 } else if ($diff < 46 * 24 * 3600) {
1059 return _('about a month ago');
1060 } else if ($diff < 330 * 24 * 3600) {
1061 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
1062 } else if ($diff < 480 * 24 * 3600) {
1063 return _('about a year ago');
1065 return common_exact_date($dt);
1069 function common_exact_date($dt) {
1074 $_utc = new DateTimeZone('UTC');
1075 $_siteTz = new DateTimeZone(common_timezone());
1078 $dateStr = date('d F Y H:i:s', strtotime($dt));
1079 $d = new DateTime($dateStr, $_utc);
1080 $d->setTimezone($_siteTz);
1081 return $d->format(DATE_RFC850);
1084 function common_date_w3dtf($dt) {
1085 $dateStr = date('d F Y H:i:s', strtotime($dt));
1086 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1087 $d->setTimezone(new DateTimeZone(common_timezone()));
1088 return $d->format(DATE_W3C);
1091 function common_date_rfc2822($dt) {
1092 $dateStr = date('d F Y H:i:s', strtotime($dt));
1093 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1094 $d->setTimezone(new DateTimeZone(common_timezone()));
1095 return $d->format('r');
1098 function common_date_iso8601($dt) {
1099 $dateStr = date('d F Y H:i:s', strtotime($dt));
1100 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1101 $d->setTimezone(new DateTimeZone(common_timezone()));
1102 return $d->format('c');
1105 function common_sql_now() {
1106 return strftime('%Y-%m-%d %H:%M:%S', time());
1109 function common_redirect($url, $code=307) {
1110 static $status = array(301 => "Moved Permanently",
1113 307 => "Temporary Redirect");
1114 header("Status: ${code} $status[$code]");
1115 header("Location: $url");
1117 common_start_xml('a',
1118 '-//W3C//DTD XHTML 1.0 Strict//EN',
1119 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
1120 common_element('a', array('href' => $url), $url);
1125 function common_save_replies($notice) {
1126 # Alternative reply format
1128 if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
1131 # extract all @messages
1132 $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
1133 if (!$cnt && !$tname) {
1136 # XXX: is there another way to make an array copy?
1137 $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
1138 $sender = Profile::staticGet($notice->profile_id);
1139 # store replied only for first @ (what user/notice what the reply directed,
1140 # we assume first @ is it)
1141 for ($i=0; $i<count($names); $i++) {
1142 $nickname = $names[$i];
1143 $recipient = common_relative_profile($sender, $nickname, $notice->created);
1147 if ($i == 0 && ($recipient->id != $sender->id) && !$notice->reply_to) { # Don't save reply to self
1148 $reply_for = $recipient;
1149 $recipient_notice = $reply_for->getCurrentNotice();
1150 if ($recipient_notice) {
1151 $orig = clone($notice);
1152 $notice->reply_to = $recipient_notice->id;
1153 $notice->update($orig);
1156 $reply = new Reply();
1157 $reply->notice_id = $notice->id;
1158 $reply->profile_id = $recipient->id;
1159 $id = $reply->insert();
1161 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1162 common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
1163 common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
1169 function common_broadcast_notice($notice, $remote=false) {
1171 // Check to see if notice should go to Twitter
1172 $flink = Foreign_link::getForeignLink($notice->profile_id, 1); // 1 == Twitter
1173 if (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND) {
1175 // If it's not a Twitter-style reply, or if the user WANTS to send replies...
1177 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
1178 (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY)) {
1180 $result = common_twitter_broadcast($notice, $flink);
1183 common_debug('Unable to send notice: ' . $notice->id . ' to Twitter.', __FILE__);
1188 if (common_config('queue', 'enabled')) {
1190 return common_enqueue_notice($notice);
1192 return common_real_broadcast($notice, $remote);
1196 function common_twitter_broadcast($notice, $flink) {
1199 $fuser = $flink->getForeignUser();
1200 $twitter_user = $fuser->nickname;
1201 $twitter_password = $flink->credentials;
1202 $uri = 'http://www.twitter.com/statuses/update.json';
1204 // XXX: Hack to get around PHP cURL's use of @ being a a meta character
1205 $statustxt = preg_replace('/^@/', ' @', $notice->content);
1208 CURLOPT_USERPWD => "$twitter_user:$twitter_password",
1209 CURLOPT_POST => true,
1210 CURLOPT_POSTFIELDS => array(
1211 'status' => $statustxt,
1212 'source' => $config['integration']['source']
1214 CURLOPT_RETURNTRANSFER => true,
1215 CURLOPT_FAILONERROR => true,
1216 CURLOPT_HEADER => false,
1217 CURLOPT_FOLLOWLOCATION => true,
1218 CURLOPT_USERAGENT => "Laconica",
1219 CURLOPT_CONNECTTIMEOUT => 120, // XXX: Scary!!!! How long should this be?
1220 CURLOPT_TIMEOUT => 120
1223 $ch = curl_init($uri);
1224 curl_setopt_array($ch, $options);
1225 $data = curl_exec($ch);
1226 $errmsg = curl_error($ch);
1229 common_debug("cURL error: $errmsg - trying to send notice for $twitter_user.",
1237 common_debug("No data returned by Twitter's API trying to send update for $twitter_user",
1242 // Twitter should return a status
1243 $status = json_decode($data);
1246 common_debug("Unexpected data returned by Twitter API trying to send update for $twitter_user",
1254 # Stick the notice on the queue
1256 function common_enqueue_notice($notice) {
1257 foreach (array('jabber', 'omb', 'sms', 'public') as $transport) {
1258 $qi = new Queue_item();
1259 $qi->notice_id = $notice->id;
1260 $qi->transport = $transport;
1261 $qi->created = $notice->created;
1262 $result = $qi->insert();
1264 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1265 common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
1268 common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id . ' for ' . $transport);
1273 function common_dequeue_notice($notice) {
1274 $qi = Queue_item::staticGet($notice->id);
1276 $result = $qi->delete();
1278 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1279 common_log(LOG_ERR, 'DB error deleting queue item: ' . $last_error->message);
1282 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
1289 function common_real_broadcast($notice, $remote=false) {
1292 # Make sure we have the OMB stuff
1293 require_once(INSTALLDIR.'/lib/omb.php');
1294 $success = omb_broadcast_remote_subscribers($notice);
1296 common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
1300 require_once(INSTALLDIR.'/lib/jabber.php');
1301 $success = jabber_broadcast_notice($notice);
1303 common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1307 require_once(INSTALLDIR.'/lib/mail.php');
1308 $success = mail_broadcast_notice_sms($notice);
1310 common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1314 $success = jabber_public_notice($notice);
1316 common_log(LOG_ERR, 'Error in public broadcast for notice ' . $notice->id);
1319 // XXX: broadcast notices to other IM
1323 function common_broadcast_profile($profile) {
1324 // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1325 require_once(INSTALLDIR.'/lib/omb.php');
1326 omb_broadcast_profile($profile);
1327 // XXX: Other broadcasts...?
1331 function common_profile_url($nickname) {
1332 return common_local_url('showstream', array('nickname' => $nickname));
1335 # Don't call if nobody's logged in
1337 function common_notice_form($action=NULL, $content=NULL) {
1338 $user = common_current_user();
1339 assert(!is_null($user));
1340 common_element_start('form', array('id' => 'status_form',
1342 'action' => common_local_url('newnotice')));
1343 common_element_start('p');
1344 common_element('label', array('for' => 'status_textarea',
1345 'id' => 'status_label'),
1346 sprintf(_('What\'s up, %s?'), $user->nickname));
1347 common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1348 common_element('textarea', array('id' => 'status_textarea',
1351 'name' => 'status_textarea'),
1352 ($content) ? $content : '');
1354 common_hidden('returnto', $action);
1357 common_hidden('inreplyto', 'false');
1358 common_element('input', array('id' => 'status_submit',
1359 'name' => 'status_submit',
1361 'value' => _('Send')));
1362 common_element_end('p');
1363 common_element_end('form');
1366 # Should make up a reasonable root URL
1368 function common_root_url() {
1369 return common_path('');
1372 # returns $bytes bytes of random data as a hexadecimal string
1373 # "good" here is a goal and not a guarantee
1375 function common_good_rand($bytes) {
1376 # XXX: use random.org...?
1377 if (file_exists('/dev/urandom')) {
1378 return common_urandom($bytes);
1379 } else { # FIXME: this is probably not good enough
1380 return common_mtrand($bytes);
1384 function common_urandom($bytes) {
1385 $h = fopen('/dev/urandom', 'rb');
1387 $src = fread($h, $bytes);
1390 for ($i = 0; $i < $bytes; $i++) {
1391 $enc .= sprintf("%02x", (ord($src[$i])));
1396 function common_mtrand($bytes) {
1398 for ($i = 0; $i < $bytes; $i++) {
1399 $enc .= sprintf("%02x", mt_rand(0, 255));
1404 function common_set_returnto($url) {
1405 common_ensure_session();
1406 $_SESSION['returnto'] = $url;
1409 function common_get_returnto() {
1410 common_ensure_session();
1411 return $_SESSION['returnto'];
1414 function common_timestamp() {
1415 return date('YmdHis');
1418 function common_ensure_syslog() {
1419 static $initialized = false;
1420 if (!$initialized) {
1422 openlog($config['syslog']['appname'], 0, LOG_USER);
1423 $initialized = true;
1427 function common_log($priority, $msg, $filename=NULL) {
1428 $logfile = common_config('site', 'logfile');
1430 $log = fopen($logfile, "a");
1432 static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1433 'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1434 $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1435 fwrite($log, $output);
1439 common_ensure_syslog();
1440 syslog($priority, $msg);
1444 function common_debug($msg, $filename=NULL) {
1446 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1448 common_log(LOG_DEBUG, $msg);
1452 function common_log_db_error(&$object, $verb, $filename=NULL) {
1453 $objstr = common_log_objstring($object);
1454 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1455 common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1458 function common_log_objstring(&$object) {
1459 if (is_null($object)) {
1462 $arr = $object->toArray();
1464 foreach ($arr as $k => $v) {
1465 $fields[] = "$k='$v'";
1467 $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1471 function common_valid_http_url($url) {
1472 return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1475 function common_valid_tag($tag) {
1476 if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1477 return (Validate::email($matches[1]) ||
1478 preg_match('/^([\w-\.]+)$/', $matches[1]));
1483 # Does a little before-after block for next/prev page
1485 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1487 if ($have_before || $have_after) {
1488 common_element_start('div', array('id' => 'pagination'));
1489 common_element_start('ul', array('id' => 'nav_pagination'));
1493 $pargs = array('page' => $page-1);
1494 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1496 common_element_start('li', 'before');
1497 common_element('a', array('href' => common_local_url($action, $newargs)),
1499 common_element_end('li');
1503 $pargs = array('page' => $page+1);
1504 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1505 common_element_start('li', 'after');
1506 common_element('a', array('href' => common_local_url($action, $newargs)),
1508 common_element_end('li');
1511 if ($have_before || $have_after) {
1512 common_element_end('ul');
1513 common_element_end('div');
1517 /* Following functions are copied from MediaWiki GlobalFunctions.php
1518 * and written by Evan Prodromou. */
1520 function common_accept_to_prefs($accept, $def = '*/*') {
1521 # No arg means accept anything (per HTTP spec)
1523 return array($def => 1);
1528 $parts = explode(',', $accept);
1530 foreach($parts as $part) {
1531 # FIXME: doesn't deal with params like 'text/html; level=1'
1532 @list($value, $qpart) = explode(';', $part);
1534 if(!isset($qpart)) {
1536 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1537 $prefs[$value] = $match[1];
1544 function common_mime_type_match($type, $avail) {
1545 if(array_key_exists($type, $avail)) {
1548 $parts = explode('/', $type);
1549 if(array_key_exists($parts[0] . '/*', $avail)) {
1550 return $parts[0] . '/*';
1551 } elseif(array_key_exists('*/*', $avail)) {
1559 function common_negotiate_type($cprefs, $sprefs) {
1562 foreach(array_keys($sprefs) as $type) {
1563 $parts = explode('/', $type);
1564 if($parts[1] != '*') {
1565 $ckey = common_mime_type_match($type, $cprefs);
1567 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1572 foreach(array_keys($cprefs) as $type) {
1573 $parts = explode('/', $type);
1574 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1575 $skey = common_mime_type_match($type, $sprefs);
1577 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1583 $besttype = "text/html";
1585 foreach(array_keys($combine) as $type) {
1586 if($combine[$type] > $bestq) {
1588 $bestq = $combine[$type];
1595 function common_config($main, $sub) {
1597 return isset($config[$main][$sub]) ? $config[$main][$sub] : false;
1600 function common_copy_args($from) {
1602 $strip = get_magic_quotes_gpc();
1603 foreach ($from as $k => $v) {
1604 $to[$k] = ($strip) ? stripslashes($v) : $v;
1609 // Neutralise the evil effects of magic_quotes_gpc in the current request.
1610 // This is used before handing a request off to OAuthRequest::from_request.
1611 function common_remove_magic_from_request() {
1612 if(get_magic_quotes_gpc()) {
1613 $_POST=array_map('stripslashes',$_POST);
1614 $_GET=array_map('stripslashes',$_GET);
1618 function common_user_uri(&$user) {
1619 return common_local_url('userbyid', array('id' => $user->id));
1622 function common_notice_uri(&$notice) {
1623 return common_local_url('shownotice',
1624 array('notice' => $notice->id));
1627 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1629 function common_confirmation_code($bits) {
1630 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1631 static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1632 $chars = ceil($bits/5);
1634 for ($i = 0; $i < $chars; $i++) {
1635 # XXX: convert to string and back
1636 $num = hexdec(common_good_rand(1));
1637 # XXX: randomness is too precious to throw away almost
1638 # 40% of the bits we get!
1639 $code .= $codechars[$num%32];
1644 # convert markup to HTML
1646 function common_markup_to_html($c) {
1647 $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1648 $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1649 $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1650 return Markdown($c);
1653 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1654 $avatar = $profile->getAvatar($size);
1656 return common_avatar_display_url($avatar);
1658 return common_default_avatar($size);
1662 function common_profile_uri($profile) {
1666 $user = User::staticGet($profile->id);
1671 $remote = Remote_profile::staticGet($profile->id);
1673 return $remote->uri;
1675 # XXX: this is a very bad profile!
1679 function common_canonical_sms($sms) {
1681 preg_replace('/\D/', '', $sms);
1685 function common_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
1688 common_log(LOG_ERR, "[$errno] $errstr ($errfile:$errline)");
1692 case E_USER_WARNING:
1693 common_log(LOG_WARNING, "[$errno] $errstr ($errfile:$errline)");
1697 common_log(LOG_NOTICE, "[$errno] $errstr ($errfile:$errline)");
1701 # FIXME: show error page if we're on the Web
1702 /* Don't execute PHP internal error handler */
1706 function common_session_token() {
1707 common_ensure_session();
1708 if (!array_key_exists('token', $_SESSION)) {
1709 $_SESSION['token'] = common_good_rand(64);
1711 return $_SESSION['token'];
1714 function common_disfavor_form($notice) {
1715 common_element_start('form', array('id' => 'disfavor-' . $notice->id,
1717 'class' => 'disfavor',
1718 'action' => common_local_url('disfavor')));
1719 common_hidden('token', common_session_token());
1720 common_hidden('notice', $notice->id);
1721 common_element('input', array('type' => 'submit',
1722 'id' => 'disfavor-submit-' . $notice->id,
1723 'name' => 'disfavor-submit-' . $notice->id,
1724 'class' => 'disfavor',
1726 common_element_end('form');
1729 function common_favor_form($notice) {
1730 common_element_start('form', array('id' => 'favor-' . $notice->id,
1733 'action' => common_local_url('favor')));
1734 common_hidden('token', common_session_token());
1735 common_hidden('notice', $notice->id);
1736 common_element('input', array('type' => 'submit',
1737 'id' => 'favor-submit-' . $notice->id,
1738 'name' => 'favor-submit-' . $notice->id,
1741 common_element_end('form');
1744 function common_cache_key($extra) {
1745 return 'laconica:' . common_keyize(common_config('site', 'name')) . ':' . $extra;
1748 function common_keyize($str) {
1749 $str = strtolower($str);
1750 $str = preg_replace('/\s/', '_', $str);
1754 function common_message_form($content, $user, $to) {
1756 common_element_start('form', array('id' => 'message_form',
1758 'action' => common_local_url('newmessage')));
1760 $mutual_users = $user->mutuallySubscribedUsers();
1764 while ($mutual_users->fetch()) {
1765 if ($mutual_users->id != $user->id) {
1766 $mutual[$mutual_users->id] = $mutual_users->nickname;
1770 $mutual_users->free();
1771 unset($mutual_users);
1773 common_dropdown('to', _('To'), $mutual, NULL, FALSE, $to->id);
1775 common_element_start('p');
1777 common_element('textarea', array('id' => 'message_content',
1780 'name' => 'content'),
1781 ($content) ? $content : '');
1783 common_element('input', array('id' => 'message_send',
1784 'name' => 'message_send',
1786 'value' => _('Send')));
1788 common_hidden('token', common_session_token());
1790 common_element_end('p');
1791 common_element_end('form');
1794 function common_memcache() {
1795 static $cache = NULL;
1796 if (!common_config('memcached', 'enabled')) {
1800 $cache = new Memcache();
1801 $servers = common_config('memcached', 'server');
1802 if (is_array($servers)) {
1803 foreach($servers as $server) {
1804 $cache->addServer($server);
1807 $cache->addServer($servers);