]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
6d409f9436de14e633d7db4cdbb4277343ac3a10
[quix0rs-gnu-social.git] / lib / util.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, Controlez-Vous, Inc.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 /* XXX: break up into separate modules (HTTP, HTML, user, files) */
21
22 # Show a server error
23
24 function common_server_error($msg, $code=500) {
25         static $status = array(500 => 'Internal Server Error',
26                                                    501 => 'Not Implemented',
27                                                    502 => 'Bad Gateway',
28                                                    503 => 'Service Unavailable',
29                                                    504 => 'Gateway Timeout',
30                                                    505 => 'HTTP Version Not Supported');
31
32         if (!array_key_exists($code, $status)) {
33                 $code = 500;
34         }
35
36         $status_string = $status[$code];
37
38         header('HTTP/1.1 '.$code.' '.$status_string);
39         header('Content-type: text/plain');
40
41         print $msg;
42         print "\n";
43         exit();
44 }
45
46 # Show a user error
47 function common_user_error($msg, $code=400) {
48         static $status = array(400 => 'Bad Request',
49                                                    401 => 'Unauthorized',
50                                                    402 => 'Payment Required',
51                                                    403 => 'Forbidden',
52                                                    404 => 'Not Found',
53                                                    405 => 'Method Not Allowed',
54                                                    406 => 'Not Acceptable',
55                                                    407 => 'Proxy Authentication Required',
56                                                    408 => 'Request Timeout',
57                                                    409 => 'Conflict',
58                                                    410 => 'Gone',
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');
66
67         if (!array_key_exists($code, $status)) {
68                 $code = 400;
69         }
70
71         $status_string = $status[$code];
72
73         header('HTTP/1.1 '.$code.' '.$status_string);
74
75         common_show_header('Error');
76         common_element('div', array('class' => 'error'), $msg);
77         common_show_footer();
78 }
79
80 $xw = null;
81
82 # Start an HTML element
83 function common_element_start($tag, $attrs=NULL) {
84         global $xw;
85         $xw->startElement($tag);
86         if (is_array($attrs)) {
87                 foreach ($attrs as $name => $value) {
88                         $xw->writeAttribute($name, $value);
89                 }
90         } else if (is_string($attrs)) {
91                 $xw->writeAttribute('class', $attrs);
92         }
93 }
94
95 function common_element_end($tag) {
96         static $empty_tag = array('base', 'meta', 'link', 'hr',
97                                                           'br', 'param', 'img', 'area',
98                                                           'input', 'col');
99         global $xw;
100         # XXX: check namespace
101         if (in_array($tag, $empty_tag)) {
102                 $xw->endElement();
103         } else {
104                 $xw->fullEndElement();
105         }
106 }
107
108 function common_element($tag, $attrs=NULL, $content=NULL) {
109         common_element_start($tag, $attrs);
110         global $xw;
111         if (!is_null($content)) {
112                 $xw->text($content);
113         }
114         common_element_end($tag);
115 }
116
117 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
118         global $xw;
119         $xw = new XMLWriter();
120         $xw->openURI('php://output');
121         $xw->setIndent(true);
122         $xw->startDocument('1.0', 'UTF-8');
123         if ($doc) {
124                 $xw->writeDTD($doc, $public, $system);
125         }
126 }
127
128 function common_end_xml() {
129         global $xw;
130         $xw->endDocument();
131         $xw->flush();
132 }
133
134 define('PAGE_TYPE_PREFS', 'text/html,application/xhtml+xml,application/xml;q=0.3,text/xml;q=0.2');
135
136 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $headercall=NULL) {
137         global $config, $xw;
138
139         $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : NULL;
140
141         # XXX: allow content negotiation for RDF, RSS, or XRDS
142
143         $type = common_negotiate_type(common_accept_to_prefs($httpaccept),
144                                                                   common_accept_to_prefs(PAGE_TYPE_PREFS));
145
146         if (!$type) {
147                 common_user_error(_('This page is not available in a media type you accept'), 406);
148                 exit(0);
149         }
150
151         header('Content-Type: '.$type);
152
153         common_start_xml('html',
154                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
155                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
156
157         # FIXME: correct language for interface
158
159         common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
160                                                                            'xml:lang' => 'en',
161                                                                            'lang' => 'en'));
162
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]');
175                 }
176         }
177
178         common_element('script', array('type' => 'text/javascript',
179                                                                    'src' => common_path('js/jquery.min.js')),
180                                    ' ');
181         common_element('script', array('type' => 'text/javascript',
182                                                                    'src' => common_path('js/util.js')),
183                                    ' ');
184
185         if ($callable) {
186                 if ($data) {
187                         call_user_func($callable, $data);
188                 } else {
189                         call_user_func($callable);
190                 }
191         }
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'));
196         common_nav_menu();
197         if ((isset($config['site']['logo']) && is_string($config['site']['logo']) && (strlen($config['site']['logo']) > 0))
198                 || file_exists(theme_file('logo.png')))
199         {
200                 common_element_start('a', array('href' => common_local_url('public')));
201                 common_element('img', array('src' => isset($config['site']['logo']) ?
202                                                                         ($config['site']['logo']) : theme_path('logo.png'),
203                                                                         'alt' => $config['site']['name'],
204                                                                         'id' => 'logo'));
205                 common_element_end('a');
206         } else {
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');
211         }
212
213         common_element('h1', 'pagetitle', $pagetitle);
214
215         if ($headercall) {
216                 if ($data) {
217                         call_user_func($headercall, $data);
218                 } else {
219                         call_user_func($headercall);
220                 }
221         }
222         common_element_end('div');
223         common_element_start('div', array('id' => 'content'));
224 }
225
226 function common_show_footer() {
227         global $xw, $config;
228         common_element_end('div'); # content div
229         common_foot_menu();
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%%). ');
234         } else {
235                 $instr = _('**%%site.name%%** is a microblogging service. ');
236         }
237         $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);
238     $output = common_markup_to_html($instr);
239     common_raw($output);
240         common_element_end('div');
241         common_element('img', array('id' => 'cc',
242                                                                 'src' => $config['license']['image'],
243                                                                 'alt' => $config['license']['title']));
244         common_element_start('p');
245         common_text(_('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
246         common_element('a', array('class' => 'license',
247                                                           'rel' => 'license',
248                                                           'href' => $config['license']['url']),
249                                    $config['license']['title']);
250         common_text(_('. Contributors should be attributed by full name or nickname.'));
251         common_element_end('p');
252         common_element_end('div');
253         common_element_end('div');
254         common_element_end('body');
255         common_element_end('html');
256         common_end_xml();
257 }
258
259 function common_text($txt) {
260         global $xw;
261         $xw->text($txt);
262 }
263
264 function common_raw($xml) {
265         global $xw;
266         $xw->writeRaw($xml);
267 }
268
269 function common_nav_menu() {
270         $user = common_current_user();
271         common_element_start('ul', array('id' => 'nav'));
272         if ($user) {
273                 common_menu_item(common_local_url('all', array('nickname' => $user->nickname)),
274                                                  _('Home'));
275         }
276         common_menu_item(common_local_url('public'), _('Public'));
277         common_menu_item(common_local_url('peoplesearch'), _('Search'));
278         common_menu_item(common_local_url('tags'), _('Tags'));
279         common_menu_item(common_local_url('doc', array('title' => 'help')),
280                                          _('Help'));
281         if ($user) {
282                 common_menu_item(common_local_url('profilesettings'),
283                                                  _('Settings'));
284                 common_menu_item(common_local_url('logout'),
285                                                  _('Logout'));
286         } else {
287                 common_menu_item(common_local_url('login'), _('Login'));
288                 if (!common_config('site', 'closed')) {
289                         common_menu_item(common_local_url('register'), _('Register'));
290                 }
291                 common_menu_item(common_local_url('openidlogin'), _('OpenID'));
292         }
293         common_element_end('ul');
294 }
295
296 function common_foot_menu() {
297         common_element_start('ul', array('id' => 'nav_sub'));
298         common_menu_item(common_local_url('doc', array('title' => 'about')),
299                                          _('About'));
300         common_menu_item(common_local_url('doc', array('title' => 'faq')),
301                                          _('FAQ'));
302         common_menu_item(common_local_url('doc', array('title' => 'privacy')),
303                                          _('Privacy'));
304         common_menu_item(common_local_url('doc', array('title' => 'source')),
305                                          _('Source'));
306         common_menu_item(common_local_url('doc', array('title' => 'contact')),
307                                          _('Contact'));
308         common_element_end('ul');
309 }
310
311 function common_menu_item($url, $text, $title=NULL, $is_selected=false) {
312         $lattrs = array();
313         if ($is_selected) {
314                 $lattrs['class'] = 'current';
315         }
316         common_element_start('li', $lattrs);
317         $attrs['href'] = $url;
318         if ($title) {
319                 $attrs['title'] = $title;
320         }
321         common_element('a', $attrs, $text);
322         common_element_end('li');
323 }
324
325 function common_input($id, $label, $value=NULL,$instructions=NULL) {
326         common_element_start('p');
327         common_element('label', array('for' => $id), $label);
328         $attrs = array('name' => $id,
329                                    'type' => 'text',
330                                    'class' => 'input_text',
331                                    'id' => $id);
332         if ($value) {
333                 $attrs['value'] = htmlspecialchars($value);
334         }
335         common_element('input', $attrs);
336         if ($instructions) {
337                 common_element('span', 'input_instructions', $instructions);
338         }
339         common_element_end('p');
340 }
341
342 function common_checkbox($id, $label, $checked=false, $instructions=NULL, $value='true')
343 {
344         common_element_start('p');
345         $attrs = array('name' => $id,
346                                    'type' => 'checkbox',
347                                    'class' => 'checkbox',
348                                    'id' => $id);
349         if ($value) {
350                 $attrs['value'] = htmlspecialchars($value);
351         }
352         if ($checked) {
353                 $attrs['checked'] = 'checked';
354         }
355         common_element('input', $attrs);
356         # XXX: use a <label>
357         common_text(' ');
358         common_element('span', 'checkbox_label', $label);
359         common_text(' ');
360         if ($instructions) {
361                 common_element('span', 'input_instructions', $instructions);
362         }
363         common_element_end('p');
364 }
365
366 function common_hidden($id, $value) {
367         common_element('input', array('name' => $id,
368                                                                   'type' => 'hidden',
369                                                                   'id' => $id,
370                                                                   'value' => $value));
371 }
372
373 function common_password($id, $label, $instructions=NULL) {
374         common_element_start('p');
375         common_element('label', array('for' => $id), $label);
376         $attrs = array('name' => $id,
377                                    'type' => 'password',
378                                    'class' => 'password',
379                                    'id' => $id);
380         common_element('input', $attrs);
381         if ($instructions) {
382                 common_element('span', 'input_instructions', $instructions);
383         }
384         common_element_end('p');
385 }
386
387 function common_submit($id, $label) {
388         global $xw;
389         common_element_start('p');
390         common_element('input', array('type' => 'submit',
391                                                                   'id' => $id,
392                                                                   'name' => $id,
393                                                                   'class' => 'submit',
394                                                                   'value' => $label));
395         common_element_end('p');
396 }
397
398 function common_textarea($id, $label, $content=NULL, $instructions=NULL) {
399         common_element_start('p');
400         common_element('label', array('for' => $id), $label);
401         common_element('textarea', array('rows' => 3,
402                                                                          'cols' => 40,
403                                                                          'name' => $id,
404                                                                          'id' => $id),
405                                    ($content) ? $content : '');
406         if ($instructions) {
407                 common_element('span', 'input_instructions', $instructions);
408         }
409         common_element_end('p');
410 }
411
412 # salted, hashed passwords are stored in the DB
413
414 function common_munge_password($password, $id) {
415         return md5($password . $id);
416 }
417
418 # check if a username exists and has matching password
419 function common_check_user($nickname, $password) {
420         $user = User::staticGet('nickname', $nickname);
421         if (is_null($user)) {
422                 return false;
423         } else {
424                 if (0 == strcmp(common_munge_password($password, $user->id),
425                                                 $user->password)) {
426                         return $user;
427                 } else {
428                         return false;
429                 }
430         }
431 }
432
433 # is the current user logged in?
434 function common_logged_in() {
435         return (!is_null(common_current_user()));
436 }
437
438 function common_have_session() {
439         return (0 != strcmp(session_id(), ''));
440 }
441
442 function common_ensure_session() {
443         if (!common_have_session()) {
444                 @session_start();
445         }
446 }
447
448 # Three kinds of arguments:
449 # 1) a user object
450 # 2) a nickname
451 # 3) NULL to clear
452
453 function common_set_user($user) {
454         if (is_null($user) && common_have_session()) {
455                 unset($_SESSION['userid']);
456                 return true;
457         } else if (is_string($user)) {
458                 $nickname = $user;
459                 $user = User::staticGet('nickname', $nickname);
460         } else if (!($user instanceof User)) {
461                 return false;
462         }
463
464         if ($user) {
465                 common_ensure_session();
466                 $_SESSION['userid'] = $user->id;
467                 return $user;
468         }
469         return false;
470 }
471
472 function common_set_cookie($key, $value, $expiration=0) {
473         $path = common_config('site', 'path');
474         $server = common_config('site', 'server');
475
476         if ($path && ($path != '/')) {
477                 $cookiepath = '/' . $path . '/';
478         } else {
479                 $cookiepath = '/';
480         }
481         return setcookie($key,
482                          $value,
483                                  $expiration,
484                                          $cookiepath,
485                                      $server);
486 }
487
488 define('REMEMBERME', 'rememberme');
489 define('REMEMBERME_EXPIRY', 30 * 24 * 60 * 60);
490
491 function common_rememberme($user=NULL) {
492         if (!$user) {
493                 $user = common_current_user();
494                 if (!$user) {
495                         common_debug('No current user to remember', __FILE__);
496                         return false;
497                 }
498         }
499         $rm = new Remember_me();
500         $rm->code = common_good_rand(16);
501         $rm->user_id = $user->id;
502         $result = $rm->insert();
503         if (!$result) {
504                 common_log_db_error($rm, 'INSERT', __FILE__);
505                 common_debug('Error adding rememberme record for ' . $user->nickname, __FILE__);
506                 return false;
507         }
508         common_log(LOG_INFO, 'adding rememberme cookie for ' . $user->nickname);
509         common_set_cookie(REMEMBERME,
510                                           implode(':', array($rm->user_id, $rm->code)),
511                                           time() + REMEMBERME_EXPIRY);
512         return true;
513 }
514
515 function common_remembered_user() {
516         $user = NULL;
517         # Try to remember
518         $packed = isset($_COOKIE[REMEMBERME]) ? $_COOKIE[REMEMBERME] : '';
519         if ($packed) {
520                 list($id, $code) = explode(':', $packed);
521                 if ($id && $code) {
522                         $rm = Remember_me::staticGet($code);
523                         if ($rm && ($rm->user_id == $id)) {
524                                 $user = User::staticGet($rm->user_id);
525                                 if ($user) {
526                                         # successful!
527                                         $result = $rm->delete();
528                                         if (!$result) {
529                                                 common_log_db_error($rm, 'DELETE', __FILE__);
530                                                 $user = NULL;
531                                         } else {
532                                                 common_log(LOG_INFO, 'logging in ' . $user->nickname . ' using rememberme code ' . $rm->code);
533                                                 common_set_user($user->nickname);
534                                                 common_real_login(false);
535                                                 # We issue a new cookie, so they can log in
536                                                 # automatically again after this session
537                                                 common_rememberme($user);
538                                         }
539                                 }
540                         }
541                 }
542         }
543         return $user;
544 }
545
546 # must be called with a valid user!
547
548 function common_forgetme() {
549         common_set_cookie(REMEMBERME, '', 0);
550 }
551
552 # who is the current user?
553 function common_current_user() {
554         if (isset($_REQUEST[session_name()]) || (isset($_SESSION['userid']) && $_SESSION['userid'])) {
555                 common_ensure_session();
556                 $id = $_SESSION['userid'];
557                 if ($id) {
558                         # note: this should cache
559                         $user = User::staticGet($id);
560                         return $user;
561                 }
562         }
563         # that didn't work; try to remember
564         $user = common_remembered_user();
565         if ($user) {
566                 common_debug("Got User " . $user->nickname);
567             common_debug("Faking session on remembered user");
568             $_SESSION['userid'] = $user->id;
569         }
570         return $user;
571 }
572
573 # Logins that are 'remembered' aren't 'real' -- they're subject to
574 # cookie-stealing. So, we don't let them do certain things. New reg,
575 # OpenID, and password logins _are_ real.
576
577 function common_real_login($real=true) {
578         common_ensure_session();
579         $_SESSION['real_login'] = $real;
580 }
581
582 function common_is_real_login() {
583         return common_logged_in() && $_SESSION['real_login'];
584 }
585
586 # get canonical version of nickname for comparison
587 function common_canonical_nickname($nickname) {
588         # XXX: UTF-8 canonicalization (like combining chars)
589         return strtolower($nickname);
590 }
591
592 # get canonical version of email for comparison
593 function common_canonical_email($email) {
594         # XXX: canonicalize UTF-8
595         # XXX: lcase the domain part
596         return $email;
597 }
598
599 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$_+!*();/?:~-]))');
600
601 function common_render_content($text, $notice) {
602         $r = htmlspecialchars($text);
603         $id = $notice->profile_id;
604         $r = preg_replace('@https?://[^)\]>\s]+@', '<a href="\0" class="extlink">\0</a>', $r);
605         $r = preg_replace('/(^|\s+)@([a-z0-9]{1,64})/e', "'\\1@'.common_at_link($id, '\\2')", $r);
606         $r = preg_replace('/^T ([A-Z0-9]{1,64}) /e', "'T '.common_at_link($id, '\\1').' '", $r);
607         $r = preg_replace('/(^|\s+)#([a-z0-9]{1,64})/e', "'\\1#'.common_tag_link('\\2')", $r);
608         # XXX: machine tags
609         return $r;
610 }
611
612 function common_tag_link($tag) {
613         return '<a href="' . htmlspecialchars(common_path('tag/' . $tag)) . '" class="hashlink">' . $tag . '</a>';
614 }
615
616 function common_at_link($sender_id, $nickname) {
617         $sender = Profile::staticGet($sender_id);
618         $recipient = common_relative_profile($sender, $nickname);
619         if ($recipient) {
620                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink">'.$nickname.'</a>';
621         } else {
622                 return $nickname;
623         }
624 }
625
626 function common_relative_profile($sender, $nickname, $dt=NULL) {
627         # Try to find profiles this profile is subscribed to that have this nickname
628         $recipient = new Profile();
629         # XXX: use a join instead of a subquery
630         $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender->id.' and subscribed = id)', 'AND');
631         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
632         if ($recipient->find(TRUE)) {
633                 # XXX: should probably differentiate between profiles with
634                 # the same name by date of most recent update
635                 return $recipient;
636         }
637         # Try to find profiles that listen to this profile and that have this nickname
638         $recipient = new Profile();
639         # XXX: use a join instead of a subquery
640         $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender->id.' and subscriber = id)', 'AND');
641         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
642         if ($recipient->find(TRUE)) {
643                 # XXX: should probably differentiate between profiles with
644                 # the same name by date of most recent update
645                 return $recipient;
646         }
647         # If this is a local user, try to find a local user with that nickname.
648         $sender = User::staticGet($sender->id);
649         if ($sender) {
650                 $recipient_user = User::staticGet('nickname', $nickname);
651                 if ($recipient_user) {
652                         return $recipient_user->getProfile();
653                 }
654         }
655         # Otherwise, no links. @messages from local users to remote users,
656         # or from remote users to other remote users, are just
657         # outside our ability to make intelligent guesses about
658         return NULL;
659 }
660
661 // where should the avatar go for this user?
662
663 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
664         global $config;
665
666         if ($size) {
667                 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
668         } else {
669                 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
670         }
671 }
672
673 function common_avatar_path($filename) {
674         global $config;
675         return INSTALLDIR . '/avatar/' . $filename;
676 }
677
678 function common_avatar_url($filename) {
679         return common_path('avatar/'.$filename);
680 }
681
682 function common_avatar_display_url($avatar) {
683         $server = common_config('avatar', 'server');
684         if ($server) {
685                 return 'http://'.$server.'/'.$avatar->filename;
686         } else {
687                 return $avatar->url;
688         }
689 }
690
691 function common_default_avatar($size) {
692         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
693                                                           AVATAR_STREAM_SIZE => 'stream',
694                                                           AVATAR_MINI_SIZE => 'mini');
695         return theme_path('default-avatar-'.$sizenames[$size].'.png');
696 }
697
698 function common_local_url($action, $args=NULL) {
699         global $config;
700         if ($config['site']['fancy']) {
701                 return common_fancy_url($action, $args);
702         } else {
703                 return common_simple_url($action, $args);
704         }
705 }
706
707 function common_fancy_url($action, $args=NULL) {
708         switch (strtolower($action)) {
709          case 'public':
710                 if ($args && isset($args['page'])) {
711                         return common_path('?page=' . $args['page']);
712                 } else {
713                         return common_path('');
714                 }
715          case 'publicrss':
716                 return common_path('rss');
717          case 'publicxrds':
718                 return common_path('xrds');
719          case 'doc':
720                 return common_path('doc/'.$args['title']);
721          case 'login':
722          case 'logout':
723          case 'register':
724          case 'subscribe':
725          case 'unsubscribe':
726                 return common_path('main/'.$action);
727          case 'remotesubscribe':
728                 if ($args && $args['nickname']) {
729                         return common_path('main/remote?nickname=' . $args['nickname']);
730                 } else {
731                         return common_path('main/remote');
732                 }
733          case 'openidlogin':
734                 return common_path('main/openid');
735          case 'avatar':
736          case 'password':
737                 return common_path('settings/'.$action);
738          case 'profilesettings':
739                 return common_path('settings/profile');
740          case 'emailsettings':
741                 return common_path('settings/email');
742          case 'openidsettings':
743                 return common_path('settings/openid');
744          case 'smssettings':
745                 return common_path('settings/sms');
746          case 'newnotice':
747                 if ($args && $args['replyto']) {
748                         return common_path('notice/new?replyto='.$args['replyto']);
749                 } else {
750                         return common_path('notice/new');
751                 }
752          case 'shownotice':
753                 return common_path('notice/'.$args['notice']);
754          case 'deletenotice':
755                 if ($args && $args['notice']) {
756                         return common_path('deletenotice/'.$args['notice']);
757                 } else {
758                         return common_path('deletenotice/');
759                 }
760          case 'xrds':
761          case 'foaf':
762                 return common_path($args['nickname'].'/'.$action);
763          case 'subscriptions':
764          case 'subscribers':
765          case 'all':
766          case 'replies':
767                 if ($args && isset($args['page'])) {
768                         return common_path($args['nickname'].'/'.$action.'?page=' . $args['page']);
769                 } else {
770                         return common_path($args['nickname'].'/'.$action);
771                 }
772          case 'allrss':
773                 return common_path($args['nickname'].'/all/rss');
774          case 'repliesrss':
775                 return common_path($args['nickname'].'/replies/rss');
776          case 'userrss':
777                 return common_path($args['nickname'].'/rss');
778          case 'showstream':
779                 if ($args && isset($args['page'])) {
780                         return common_path($args['nickname'].'?page=' . $args['page']);
781                 } else {
782                         return common_path($args['nickname']);
783                 }
784          case 'confirmaddress':
785                 return common_path('main/confirmaddress/'.$args['code']);
786          case 'userbyid':
787                 return common_path('user/'.$args['id']);
788          case 'recoverpassword':
789             $path = 'main/recoverpassword';
790             if ($args['code']) {
791                 $path .= '/' . $args['code'];
792                 }
793             return common_path($path);
794          case 'imsettings':
795                 return common_path('settings/im');
796          case 'peoplesearch':
797                 return common_path('search/people' . (($args) ? ('?' . http_build_query($args)) : ''));
798          case 'noticesearch':
799                 return common_path('search/notice' . (($args) ? ('?' . http_build_query($args)) : ''));
800          case 'noticesearchrss':
801                 return common_path('search/notice/rss' . (($args) ? ('?' . http_build_query($args)) : ''));
802          case 'avatarbynickname':
803                 return common_path($args['nickname'].'/avatar/'.$args['size']);
804          case 'tag':
805             if (isset($args['tag']) && $args['tag']) {
806                         $path = 'tag/' . $args['tag'];
807                         unset($args['tag']);
808                 } else {
809                         $path = 'tags';
810                 }
811                 return common_path($path . (($args) ? ('?' . http_build_query($args)) : ''));
812          case 'tags':
813                 return common_path('tags' . (($args) ? ('?' . http_build_query($args)) : ''));
814          default:
815                 return common_simple_url($action, $args);
816         }
817 }
818
819 function common_simple_url($action, $args=NULL) {
820         global $config;
821         /* XXX: pretty URLs */
822         $extra = '';
823         if ($args) {
824                 foreach ($args as $key => $value) {
825                         $extra .= "&${key}=${value}";
826                 }
827         }
828         return common_path("index.php?action=${action}${extra}");
829 }
830
831 function common_path($relative) {
832         global $config;
833         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
834         return "http://".$config['site']['server'].'/'.$pathpart.$relative;
835 }
836
837 function common_date_string($dt) {
838         // XXX: do some sexy date formatting
839         // return date(DATE_RFC822, $dt);
840         $t = strtotime($dt);
841         $now = time();
842         $diff = $now - $t;
843
844         if ($now < $t) { # that shouldn't happen!
845                 return common_exact_date($dt);
846         } else if ($diff < 60) {
847                 return _('a few seconds ago');
848         } else if ($diff < 92) {
849                 return _('about a minute ago');
850         } else if ($diff < 3300) {
851                 return sprintf(_('about %d minutes ago'), round($diff/60));
852         } else if ($diff < 5400) {
853                 return _('about an hour ago');
854         } else if ($diff < 22 * 3600) {
855                 return sprintf(_('about %d hours ago'), round($diff/3600));
856         } else if ($diff < 37 * 3600) {
857                 return _('about a day ago');
858         } else if ($diff < 24 * 24 * 3600) {
859                 return sprintf(_('about %d days ago'), round($diff/(24*3600)));
860         } else if ($diff < 46 * 24 * 3600) {
861                 return _('about a month ago');
862         } else if ($diff < 330 * 24 * 3600) {
863                 return sprintf(_('about %d months ago'), round($diff/(30*24*3600)));
864         } else if ($diff < 480 * 24 * 3600) {
865                 return _('about a year ago');
866         } else {
867                 return common_exact_date($dt);
868         }
869 }
870
871 function common_exact_date($dt) {
872         $t = strtotime($dt);
873         return date(DATE_RFC850, $t);
874 }
875
876 function common_date_w3dtf($dt) {
877         $t = strtotime($dt);
878         return date(DATE_W3C, $t);
879 }
880
881 function common_date_rfc2822($dt) {
882         $t = strtotime($dt);
883         return date("r", $t);
884 }
885
886 function common_date_iso8601($dt) {
887         $t = strtotime($dt);
888         return date("c", $t);
889 }
890
891 function common_redirect($url, $code=307) {
892         static $status = array(301 => "Moved Permanently",
893                                                    302 => "Found",
894                                                    303 => "See Other",
895                                                    307 => "Temporary Redirect");
896         header("Status: ${code} $status[$code]");
897         header("Location: $url");
898
899         common_start_xml('a',
900                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
901                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
902         common_element('a', array('href' => $url), $url);
903         common_end_xml();
904     exit;
905 }
906
907 function common_save_replies($notice) {
908         # Alternative reply format
909         $tname = false;
910         if (preg_match('/^T ([A-Z0-9]{1,64}) /', $notice->content, $match)) {
911                 $tname = $match[1];
912         }
913         # extract all @messages
914         $cnt = preg_match_all('/(?:^|\s)@([a-z0-9]{1,64})/', $notice->content, $match);
915         if (!$cnt && !$tname) {
916                 return true;
917         }
918         # XXX: is there another way to make an array copy?
919         $names = ($tname) ? array_unique(array_merge(array(strtolower($tname)), $match[1])) : array_unique($match[1]);
920         $sender = Profile::staticGet($notice->profile_id);
921         # store replied only for first @ (what user/notice what the reply directed,
922         # we assume first @ is it)
923         for ($i=0; $i<count($names); $i++) {
924                 $nickname = $names[$i];
925                 $recipient = common_relative_profile($sender, $nickname, $notice->created);
926                 if (!$recipient) {
927                         continue;
928                 }
929                 if ($i == 0 && ($recipient->id != $sender->id)) { # Don't save reply to self
930                         $reply_for = $recipient;
931                         $recipient_notice = $reply_for->getCurrentNotice();
932                         $orig = clone($notice);
933                         $notice->reply_to = $recipient_notice->id;
934                         $notice->update($orig);
935                 }
936                 $reply = new Reply();
937                 $reply->notice_id = $notice->id;
938                 $reply->profile_id = $recipient->id;
939                 $id = $reply->insert();
940                 if (!$id) {
941                         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
942                         common_log(LOG_ERR, 'DB error inserting reply: ' . $last_error->message);
943                         common_server_error(sprintf(_('DB error inserting reply: %s'), $last_error->message));
944                         return;
945                 }
946         }
947 }
948
949 function common_broadcast_notice($notice, $remote=false) {
950         if (common_config('queue', 'enabled')) {
951                 # Do it later!
952                 return common_enqueue_notice($notice);
953         } else {
954                 return common_real_broadcast($notice, $remote);
955         }
956 }
957
958 # Stick the notice on the queue
959
960 function common_enqueue_notice($notice) {
961         $qi = new Queue_item();
962         $qi->notice_id = $notice->id;
963         $qi->created = $notice->created;
964         $result = $qi->insert();
965         if (!$result) {
966             $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
967             common_log(LOG_ERR, 'DB error inserting queue item: ' . $last_error->message);
968             return false;
969         }
970         common_log(LOG_DEBUG, 'complete queueing notice ID = ' . $notice->id);
971         return $result;
972 }
973
974 function common_dequeue_notice($notice) {
975         $qi = Queue_Item::staticGet($notice->id);
976         if ($qi) {
977                 $result = $qi->delete();
978                 if (!$result) {
979                     $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
980                     common_log(LOG_ERROR, 'DB error deleting queue item: ' . $last_error->message);
981                     return false;
982                 }
983                 common_log(LOG_DEBUG, 'complete dequeueing notice ID = ' . $notice->id);
984                 return $result;
985         } else {
986             return false;
987         }
988 }
989
990 function common_real_broadcast($notice, $remote=false) {
991         $success = true;
992         if (!$remote) {
993                 # Make sure we have the OMB stuff
994                 require_once(INSTALLDIR.'/lib/omb.php');
995                 $success = omb_broadcast_remote_subscribers($notice);
996                 if (!$success) {
997                         common_log(LOG_ERR, 'Error in OMB broadcast for notice ' . $notice->id);
998                 }
999         }
1000         if ($success) {
1001                 require_once(INSTALLDIR.'/lib/jabber.php');
1002                 $success = jabber_broadcast_notice($notice);
1003                 if (!$success) {
1004                         common_log(LOG_ERR, 'Error in jabber broadcast for notice ' . $notice->id);
1005                 }
1006         }
1007         if ($success) {
1008                 require_once(INSTALLDIR.'/lib/mail.php');
1009                 $success = mail_broadcast_notice_sms($notice);
1010                 if (!$success) {
1011                         common_log(LOG_ERR, 'Error in sms broadcast for notice ' . $notice->id);
1012                 }
1013         }
1014         // XXX: broadcast notices to other IM
1015         return $success;
1016 }
1017
1018 function common_broadcast_profile($profile) {
1019         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
1020         require_once(INSTALLDIR.'/lib/omb.php');
1021         omb_broadcast_profile($profile);
1022         // XXX: Other broadcasts...?
1023         return true;
1024 }
1025
1026 function common_profile_url($nickname) {
1027         return common_local_url('showstream', array('nickname' => $nickname));
1028 }
1029
1030 # Don't call if nobody's logged in
1031
1032 function common_notice_form($action=NULL, $content=NULL) {
1033         $user = common_current_user();
1034         assert(!is_null($user));
1035         common_element_start('form', array('id' => 'status_form',
1036                                                                            'method' => 'post',
1037                                                                            'action' => common_local_url('newnotice')));
1038         common_element_start('p');
1039         common_element('label', array('for' => 'status_textarea',
1040                                                                   'id' => 'status_label'),
1041                                    sprintf(_('What\'s up, %s?'), $user->nickname));
1042         common_element('span', array('id' => 'counter', 'class' => 'counter'), '140');
1043         common_element('textarea', array('id' => 'status_textarea',
1044                                                                          'cols' => 60,
1045                                                                          'rows' => 3,
1046                                                                          'name' => 'status_textarea'),
1047                                    ($content) ? $content : '');
1048         if ($action) {
1049                 common_hidden('returnto', $action);
1050         }
1051         common_element('input', array('id' => 'status_submit',
1052                                                                   'name' => 'status_submit',
1053                                                                   'type' => 'submit',
1054                                                                   'value' => _('Send')));
1055         common_element_end('p');
1056         common_element_end('form');
1057 }
1058
1059 # Should make up a reasonable root URL
1060
1061 function common_root_url() {
1062         return common_path('');
1063 }
1064
1065 # returns $bytes bytes of random data as a hexadecimal string
1066 # "good" here is a goal and not a guarantee
1067
1068 function common_good_rand($bytes) {
1069         # XXX: use random.org...?
1070         if (file_exists('/dev/urandom')) {
1071                 return common_urandom($bytes);
1072         } else { # FIXME: this is probably not good enough
1073                 return common_mtrand($bytes);
1074         }
1075 }
1076
1077 function common_urandom($bytes) {
1078         $h = fopen('/dev/urandom', 'rb');
1079         # should not block
1080         $src = fread($h, $bytes);
1081         fclose($h);
1082         $enc = '';
1083         for ($i = 0; $i < $bytes; $i++) {
1084                 $enc .= sprintf("%02x", (ord($src[$i])));
1085         }
1086         return $enc;
1087 }
1088
1089 function common_mtrand($bytes) {
1090         $enc = '';
1091         for ($i = 0; $i < $bytes; $i++) {
1092                 $enc .= sprintf("%02x", mt_rand(0, 255));
1093         }
1094         return $enc;
1095 }
1096
1097 function common_set_returnto($url) {
1098         common_ensure_session();
1099         $_SESSION['returnto'] = $url;
1100 }
1101
1102 function common_get_returnto() {
1103         common_ensure_session();
1104         return $_SESSION['returnto'];
1105 }
1106
1107 function common_timestamp() {
1108         return date('YmdHis');
1109 }
1110
1111 function common_ensure_syslog() {
1112         static $initialized = false;
1113         if (!$initialized) {
1114                 global $config;
1115                 openlog($config['syslog']['appname'], 0, LOG_USER);
1116                 $initialized = true;
1117         }
1118 }
1119
1120 function common_log($priority, $msg, $filename=NULL) {
1121         $logfile = common_config('site', 'logfile');
1122         if ($logfile) {
1123                 $log = fopen($logfile, "a");
1124                 if ($log) {
1125                         static $syslog_priorities = array('LOG_EMERG', 'LOG_ALERT', 'LOG_CRIT', 'LOG_ERR',
1126                                                                                           'LOG_WARNING', 'LOG_NOTICE', 'LOG_INFO', 'LOG_DEBUG');
1127                         $output = date('Y-m-d H:i:s') . ' ' . $syslog_priorities[$priority] . ': ' . $msg . "\n";
1128                         fwrite($log, $output);
1129                         fclose($log);
1130                 }
1131         } else {
1132                 common_ensure_syslog();
1133                 syslog($priority, $msg);
1134         }
1135 }
1136
1137 function common_debug($msg, $filename=NULL) {
1138         if ($filename) {
1139                 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
1140         } else {
1141                 common_log(LOG_DEBUG, $msg);
1142         }
1143 }
1144
1145 function common_log_db_error(&$object, $verb, $filename=NULL) {
1146         $objstr = common_log_objstring($object);
1147         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
1148         common_log(LOG_ERR, $last_error->message . '(' . $verb . ' on ' . $objstr . ')', $filename);
1149 }
1150
1151 function common_log_objstring(&$object) {
1152         if (is_null($object)) {
1153                 return "NULL";
1154         }
1155         $arr = $object->toArray();
1156         $fields = array();
1157         foreach ($arr as $k => $v) {
1158                 $fields[] = "$k='$v'";
1159         }
1160         $objstring = $object->tableName() . '[' . implode(',', $fields) . ']';
1161         return $objstring;
1162 }
1163
1164 function common_valid_http_url($url) {
1165         return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
1166 }
1167
1168 function common_valid_tag($tag) {
1169         if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
1170                 return (Validate::email($matches[1]) ||
1171                                 preg_match('/^([\w-\.]+)$/', $matches[1]));
1172         }
1173         return false;
1174 }
1175
1176 # Does a little before-after block for next/prev page
1177
1178 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {
1179
1180         if ($have_before || $have_after) {
1181                 common_element_start('div', array('id' => 'pagination'));
1182                 common_element_start('ul', array('id' => 'nav_pagination'));
1183         }
1184
1185         if ($have_before) {
1186                 $pargs = array('page' => $page-1);
1187                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1188
1189                 common_element_start('li', 'before');
1190                 common_element('a', array('href' => common_local_url($action, $newargs)),
1191                                            _('« After'));
1192                 common_element_end('li');
1193         }
1194
1195         if ($have_after) {
1196                 $pargs = array('page' => $page+1);
1197                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
1198                 common_element_start('li', 'after');
1199                 common_element('a', array('href' => common_local_url($action, $newargs)),
1200                                                    _('Before »'));
1201                 common_element_end('li');
1202         }
1203
1204         if ($have_before || $have_after) {
1205                 common_element_end('ul');
1206                 common_element_end('div');
1207         }
1208 }
1209
1210 /* Following functions are copied from MediaWiki GlobalFunctions.php
1211  * and written by Evan Prodromou. */
1212
1213 function common_accept_to_prefs($accept, $def = '*/*') {
1214         # No arg means accept anything (per HTTP spec)
1215         if(!$accept) {
1216                 return array($def => 1);
1217         }
1218
1219         $prefs = array();
1220
1221         $parts = explode(',', $accept);
1222
1223         foreach($parts as $part) {
1224                 # FIXME: doesn't deal with params like 'text/html; level=1'
1225                 @list($value, $qpart) = explode(';', $part);
1226                 $match = array();
1227                 if(!isset($qpart)) {
1228                         $prefs[$value] = 1;
1229                 } elseif(preg_match('/q\s*=\s*(\d*\.\d+)/', $qpart, $match)) {
1230                         $prefs[$value] = $match[1];
1231                 }
1232         }
1233
1234         return $prefs;
1235 }
1236
1237 function common_mime_type_match($type, $avail) {
1238         if(array_key_exists($type, $avail)) {
1239                 return $type;
1240         } else {
1241                 $parts = explode('/', $type);
1242                 if(array_key_exists($parts[0] . '/*', $avail)) {
1243                         return $parts[0] . '/*';
1244                 } elseif(array_key_exists('*/*', $avail)) {
1245                         return '*/*';
1246                 } else {
1247                         return NULL;
1248                 }
1249         }
1250 }
1251
1252 function common_negotiate_type($cprefs, $sprefs) {
1253         $combine = array();
1254
1255         foreach(array_keys($sprefs) as $type) {
1256                 $parts = explode('/', $type);
1257                 if($parts[1] != '*') {
1258                         $ckey = common_mime_type_match($type, $cprefs);
1259                         if($ckey) {
1260                                 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
1261                         }
1262                 }
1263         }
1264
1265         foreach(array_keys($cprefs) as $type) {
1266                 $parts = explode('/', $type);
1267                 if($parts[1] != '*' && !array_key_exists($type, $sprefs)) {
1268                         $skey = common_mime_type_match($type, $sprefs);
1269                         if($skey) {
1270                                 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
1271                         }
1272                 }
1273         }
1274
1275         $bestq = 0;
1276         $besttype = "text/html";
1277
1278         foreach(array_keys($combine) as $type) {
1279                 if($combine[$type] > $bestq) {
1280                         $besttype = $type;
1281                         $bestq = $combine[$type];
1282                 }
1283         }
1284
1285         return $besttype;
1286 }
1287
1288 function common_config($main, $sub) {
1289         global $config;
1290         return $config[$main][$sub];
1291 }
1292
1293 function common_copy_args($from) {
1294         $to = array();
1295         $strip = get_magic_quotes_gpc();
1296         foreach ($from as $k => $v) {
1297                 $to[$k] = ($strip) ? stripslashes($v) : $v;
1298         }
1299         return $to;
1300 }
1301
1302 function common_user_uri(&$user) {
1303         return common_local_url('userbyid', array('id' => $user->id));
1304 }
1305
1306 function common_notice_uri(&$notice) {
1307         return common_local_url('shownotice',
1308                 array('notice' => $notice->id));
1309 }
1310
1311 # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1312
1313 function common_confirmation_code($bits) {
1314         # 36 alphanums - lookalikes (0, O, 1, I) = 32 chars = 5 bits
1315         static $codechars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
1316         $chars = ceil($bits/5);
1317         $code = '';
1318         for ($i = 0; $i < $chars; $i++) {
1319                 # XXX: convert to string and back
1320                 $num = hexdec(common_good_rand(1));
1321                 # XXX: randomness is too precious to throw away almost
1322                 # 40% of the bits we get!
1323                 $code .= $codechars[$num%32];
1324         }
1325         return $code;
1326 }
1327
1328 # convert markup to HTML
1329
1330 function common_markup_to_html($c) {
1331         $c = preg_replace('/%%action.(\w+)%%/e', "common_local_url('\\1')", $c);
1332         $c = preg_replace('/%%doc.(\w+)%%/e', "common_local_url('doc', array('title'=>'\\1'))", $c);
1333         $c = preg_replace('/%%(\w+).(\w+)%%/e', 'common_config(\'\\1\', \'\\2\')', $c);
1334         return Markdown($c);
1335 }
1336
1337 function common_profile_avatar_url($profile, $size=AVATAR_PROFILE_SIZE) {
1338         $avatar = $profile->getAvatar($size);
1339         if ($avatar) {
1340                 return common_avatar_display_url($avatar);
1341         } else {
1342                 return common_default_avatar($size);
1343         }
1344 }
1345
1346 function common_profile_uri($profile) {
1347         if (!$profile) {
1348                 return NULL;
1349         }
1350         $user = User::staticGet($profile->id);
1351         if ($user) {
1352                 return $user->uri;
1353         }
1354
1355         $remote = Remote_profile::staticGet($profile->id);
1356         if ($remote) {
1357                 return $remote->uri;
1358         }
1359         # XXX: this is a very bad profile!
1360         return NULL;
1361 }
1362
1363 function common_canonical_sms($sms) {
1364         # strip non-digits
1365         preg_replace('/\D/', '', $sms);
1366         return $sms;
1367 }