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) {
25 header('Status: 500 Server Error');
26 header('Content-type: text/plain');
33 function common_user_error($msg, $code=200) {
34 common_show_header('Error');
35 common_element('div', array('class' => 'error'), $msg);
41 # Start an HTML element
42 function common_element_start($tag, $attrs=NULL) {
44 $xw->startElement($tag);
45 if (is_array($attrs)) {
46 foreach ($attrs as $name => $value) {
47 $xw->writeAttribute($name, $value);
49 } else if (is_string($attrs)) {
50 $xw->writeAttribute('class', $attrs);
54 function common_element_end($tag) {
59 function common_element($tag, $attrs=NULL, $content=NULL) {
60 common_element_start($tag, $attrs);
65 common_element_end($tag);
68 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
70 $xw = new XMLWriter();
71 $xw->openURI('php://output');
73 $xw->startDocument('1.0', 'UTF-8');
75 $xw->writeDTD($doc, $public, $system);
79 function common_end_xml() {
85 function common_show_header($pagetitle, $callable=NULL, $data=NULL) {
88 header('Content-Type: application/xhtml+xml');
90 common_start_xml('html',
91 '-//W3C//DTD XHTML 1.0 Strict//EN',
92 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
94 # FIXME: correct language for interface
96 common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
100 common_element_start('head');
101 common_element('title', NULL,
102 $pagetitle . " - " . $config['site']['name']);
103 common_element('link', array('rel' => 'stylesheet',
104 'type' => 'text/css',
105 'href' => common_path('theme/default/style/html.css'),
106 'media' => 'screen, projection, tv'));
107 common_element('link', array('rel' => 'stylesheet',
108 'type' => 'text/css',
109 'href' => common_path('theme/default/style/layout.css'),
110 'media' => 'screen, projection, tv'));
111 common_element('link', array('rel' => 'stylesheet',
112 'type' => 'text/css',
113 'href' => common_path('theme/default/style/print.css'),
114 'media' => 'print'));
117 call_user_func($callable, $data);
119 call_user_func($callable);
122 common_element_end('head');
123 common_element_start('body');
124 common_element_start('div', array('id' => 'wrapper'));
125 common_element_start('div', array('id' => 'content'));
126 common_element_start('div', array('id' => 'header'));
127 common_element('h1', 'title', $pagetitle);
128 common_element('h2', 'subtitle', $config['site']['name']);
129 common_element_end('div');
131 common_element_start('div', array('id' => 'page'));
134 function common_show_footer() {
136 common_element_start('div', 'footer');
138 common_license_block();
139 common_element_end('div');
140 common_element_end('div');
141 common_element_end('div');
142 common_element_end('div');
143 common_element_end('body');
144 common_element_end('html');
148 function common_text($txt) {
153 function common_raw($xml) {
158 function common_license_block() {
160 common_element_start('p', 'license greenBg');
161 common_element_start('span', 'floatLeft width25');
162 common_element_start('a', array('class' => 'license',
164 href => $config['license']['url']));
165 common_element('img', array('class' => 'license',
166 'src' => $config['license']['image'],
167 'alt' => $config['license']['title']));
168 common_element_end('a');
169 common_element_end('span');
170 common_element_start('span', 'floatRight width75');
171 common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
172 common_element('a', array('class' => 'license',
174 href => $config['license']['url']),
175 $config['license']['title']);
176 common_text(_t('. Contributors should be attributed by full name or nickname.'));
177 common_element_end('span');
178 common_element_end('p');
181 function common_head_menu() {
182 $user = common_current_user();
183 common_element_start('ul', array('id' => 'menu', 'class' => ($user) ? 'five' : 'three'));
184 common_menu_item(common_local_url('public'), _t('Public'));
186 common_menu_item(common_local_url('all', array('nickname' =>
189 common_menu_item(common_local_url('showstream', array('nickname' =>
191 _t('Profile'), $user->fullname || $user->nickname);
192 common_menu_item(common_local_url('profilesettings'),
194 common_menu_item(common_local_url('logout'),
197 common_menu_item(common_local_url('login'),
199 common_menu_item(common_local_url('register'),
202 common_element_end('ul');
205 function common_foot_menu() {
206 common_element_start('ul', 'footmenu menuish');
207 common_menu_item(common_local_url('doc', array('title' => 'about')),
209 common_menu_item(common_local_url('doc', array('title' => 'help')),
211 common_menu_item(common_local_url('doc', array('title' => 'privacy')),
213 common_menu_item(common_local_url('doc', array('title' => 'source')),
215 common_element_end('ul');
218 function common_menu_item($url, $text, $title=NULL) {
219 $attrs['href'] = $url;
221 $attrs['title'] = $title;
223 common_element_start('li', 'menuitem');
224 common_element('a', $attrs, $text);
225 common_element_end('li');
228 function common_input($id, $label, $value=NULL) {
229 common_element_start('p');
230 common_element('label', array('for' => $id), $label);
231 $attrs = array('name' => $id,
235 $attrs['value'] = htmlspecialchars($value);
237 common_element('input', $attrs);
238 common_element_end('p');
241 function common_hidden($id, $value) {
242 common_element('input', array('name' => $id,
248 function common_password($id, $label) {
249 common_element_start('p');
250 common_element('label', array('for' => $id), $label);
251 $attrs = array('name' => $id,
252 'type' => 'password',
254 common_element('input', $attrs);
255 common_element_end('p');
258 function common_submit($id, $label) {
260 common_element_start('p');
261 common_element_start('label', array('for' => $id));
262 $xw->writeRaw(' ');
263 common_element_end('label');
264 common_element('input', array('type' => 'submit',
268 'class' => 'button'));
269 common_element_end('p');
272 function common_textarea($id, $label, $content=NULL) {
273 common_element_start('p');
274 common_element('label', array('for' => $id), $label);
275 common_element('textarea', array('rows' => 3,
279 'class' => 'width50'),
280 ($content) ? $content : ' ');
281 common_element_end('p');
284 # salted, hashed passwords are stored in the DB
286 function common_munge_password($id, $password) {
287 return md5($id . $password);
290 # check if a username exists and has matching password
291 function common_check_user($nickname, $password) {
292 $user = User::staticGet('nickname', $nickname);
293 if (is_null($user)) {
296 return (0 == strcmp(common_munge_password($password, $user->id),
301 # is the current user logged in?
302 function common_logged_in() {
303 return (!is_null(common_current_user()));
306 function common_have_session() {
307 return (0 != strcmp(session_id(), ''));
310 function common_ensure_session() {
311 if (!common_have_session()) {
316 function common_set_user($nickname) {
317 if (is_null($nickname) && common_have_session()) {
318 unset($_SESSION['userid']);
321 $user = User::staticGet('nickname', $nickname);
323 common_ensure_session();
324 $_SESSION['userid'] = $user->id;
333 # who is the current user?
334 function common_current_user() {
335 static $user = NULL; # FIXME: global memcached
336 if (is_null($user)) {
337 common_ensure_session();
338 $id = $_SESSION['userid'];
340 $user = User::staticGet($id);
346 # get canonical version of nickname for comparison
347 function common_canonical_nickname($nickname) {
348 # XXX: UTF-8 canonicalization (like combining chars)
352 # get canonical version of email for comparison
353 function common_canonical_email($email) {
354 # XXX: canonicalize UTF-8
355 # XXX: lcase the domain part
359 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$_+!*();/?:~-]))');
361 function common_render_content($text, $notice) {
362 $r = htmlspecialchars($text);
363 $id = $notice->profile_id;
364 $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
365 $r = preg_replace('/(^|\b)@([\w-]+)($|\b)/e', "'\\1@'.common_at_link($id, '\\2').'\\3'", $r);
371 function common_at_link($sender_id, $nickname) {
372 # Try to find profiles this profile is subscribed to that have this nickname
373 $recipient = new Profile();
374 # XXX: chokety and bad
375 $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
376 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
377 if ($recipient->find(TRUE)) {
378 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
380 # Try to find profiles that listen to this profile and that have this nickname
381 $recipient = new Profile();
382 # XXX: chokety and bad
383 $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
384 $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
385 if ($recipient->find(TRUE)) {
386 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
388 # If this is a local user, try to find a local user with that nickname.
389 $sender = User::staticGet($sender_id);
391 $recipient_user = User::staticGet('nickname', $nickname);
392 if ($recipient_user) {
393 $recipient = $recipient->getProfile();
394 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink usertouser">'.$nickname.'</a>';
397 # Otherwise, no links. @messages from local users to remote users,
398 # or from remote users to other remote users, are just
399 # outside our ability to make intelligent guesses about
403 // where should the avatar go for this user?
405 function common_avatar_filename($user, $extension, $size=NULL, $extra=NULL) {
409 return $user->id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
411 return $user->id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
415 function common_avatar_path($filename) {
417 return INSTALLDIR . '/avatar/' . $filename;
420 function common_avatar_url($filename) {
421 return common_path('avatar/'.$filename);
424 function common_default_avatar($size) {
425 static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
426 AVATAR_STREAM_SIZE => 'stream',
427 AVATAR_MINI_SIZE => 'mini');
430 return common_path($config['avatar']['default'][$sizenames[$size]]);
433 function common_local_url($action, $args=NULL) {
434 /* XXX: pretty URLs */
437 foreach ($args as $key => $value) {
438 $extra .= "&${key}=${value}";
441 return common_path("index.php?action=${action}${extra}");
444 function common_path($relative) {
446 $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
447 return "http://".$config['site']['server'].'/'.$pathpart.$relative;
450 function common_date_string($dt) {
451 // XXX: do some sexy date formatting
452 // return date(DATE_RFC822, $dt);
456 function common_date_w3dtf($dt) {
458 return date(DATE_W3C, $t);
461 function common_redirect($url, $code=307) {
462 static $status = array(301 => "Moved Permanently",
465 307 => "Temporary Redirect");
466 header("Status: ${code} $status[$code]");
467 header("Location: $url");
468 common_element('a', array('href' => $url), $url);
471 function common_broadcast_notice($notice) {
472 // XXX: broadcast notices to remote subscribers
473 // XXX: broadcast notices to SMS
474 // XXX: broadcast notices to Jabber
475 // XXX: broadcast notices to other IM
476 // XXX: use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
480 function common_profile_url($nickname) {
481 return common_local_url('showstream', array('nickname' => $nickname));
484 function common_notice_form() {
485 common_element_start('form', array('id' => 'newnotice', 'method' => 'POST',
486 'action' => common_local_url('newnotice')));
487 common_textarea('noticecontent', _t('What\'s up?'));
488 common_submit('submit', _t('Send'));
489 common_element_end('form');
492 function common_mint_tag($extra) {
495 'tag:'.$config['tag']['authority'].','.
496 $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
499 # Should make up a reasonable root URL
501 function common_root_url() {
502 return common_path('');
505 # returns $bytes bytes of random data as a hexadecimal string
506 # "good" here is a goal and not a guarantee
508 function common_good_rand($bytes) {
509 # XXX: use random.org...?
510 if (file_exists('/dev/urandom')) {
511 return common_urandom($bytes);
512 } else { # FIXME: this is probably not good enough
513 return common_mtrand($bytes);
517 function common_urandom($bytes) {
518 $h = fopen('/dev/urandom', 'rb');
520 $src = fread($h, $bytes);
523 for ($i = 0; $i < $bytes; $i++) {
524 $enc .= sprintf("%02x", (ord($src[$i])));
529 function common_mtrand($bytes) {
531 for ($i = 0; $i < $bytes; $i++) {
532 $enc .= sprintf("%02x", mt_rand(0, 255));
537 function common_set_returnto($url) {
538 common_ensure_session();
539 $_SESSION['returnto'] = $url;
542 function common_get_returnto() {
543 common_ensure_session();
544 return $_SESSION['returnto'];
547 function common_timestamp() {
548 return date('YmdHis');
551 // XXX: set up gettext
557 function common_ensure_syslog() {
558 static $initialized = false;
560 define_syslog_variables();
561 openlog("laconica", 0, LOG_USER);
566 function common_log($priority, $msg) {
567 common_ensure_syslog();
568 syslog($priority, $msg);
571 function common_debug($msg) {
572 common_log(LOG_DEBUG, $msg);