]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/util.php
cbf60619d5d2d30c085831d4a228b8de99953834
[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         global $xw;
97         $xw->endElement();
98 }
99
100 function common_element($tag, $attrs=NULL, $content=NULL) {
101     common_element_start($tag, $attrs);
102         if ($content) {
103                 global $xw;
104                 $xw->text($content);
105         }
106         common_element_end($tag);
107 }
108
109 function common_start_xml($doc=NULL, $public=NULL, $system=NULL) {
110         global $xw;
111         $xw = new XMLWriter();
112         $xw->openURI('php://output');
113         $xw->setIndent(true);
114         $xw->startDocument('1.0', 'UTF-8');
115         if ($doc) {
116                 $xw->writeDTD($doc, $public, $system);
117         }
118 }
119
120 function common_end_xml() {
121         global $xw;
122         $xw->endDocument();
123         $xw->flush();
124 }
125
126 function common_show_header($pagetitle, $callable=NULL, $data=NULL, $notice=NULL) {
127         global $config, $xw;
128
129         header('Content-Type: application/xhtml+xml');
130
131         common_start_xml('html',
132                                          '-//W3C//DTD XHTML 1.0 Strict//EN',
133                                          'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
134
135         # FIXME: correct language for interface
136
137         common_element_start('html', array('xmlns' => 'http://www.w3.org/1999/xhtml',
138                                                                            'xml:lang' => 'en',
139                                                                            'lang' => 'en'));
140
141         common_element_start('head');
142         common_element('title', NULL,
143                                    $pagetitle . " - " . $config['site']['name']);
144         common_element('link', array('rel' => 'stylesheet',
145                                                                  'type' => 'text/css',
146                                                                  'href' => theme_path('display.css'),
147                                                                  'media' => 'screen, projection, tv'));
148         foreach (array(6,7) as $ver) {
149                 if (file_exists(theme_file('ie'.$ver.'.css'))) {
150                         # Yes, IE people should be put in jail.
151                         $xw->writeComment('[if lte IE '.$ver.']><link rel="stylesheet" type="text/css" '.
152                                                           'href="'.theme_path('ie'.$ver.'.css').' /><![endif]');
153                 }
154         }
155         if ($callable) {
156                 if ($data) {
157                         call_user_func($callable, $data);
158                 } else {
159                         call_user_func($callable);
160                 }
161         }
162         common_element_end('head');
163         common_element_start('body');
164         common_element_start('div', array('id' => 'wrap'));
165         common_element_start('div', array('id' => 'header'));
166         common_nav_menu();
167         common_element_start('a', array('href' => common_local_url('public')));
168         common_element('img', array('src' => ($config['site']['logo']) ? 
169                                                                 ($config['site']['logo']) : theme_path('logo.png'),
170                                                                 'alt' => $config['site']['name'],
171                                                                 'id' => 'logo'));
172         if ($notice && common_logged_in()) {
173                 common_notice_form();
174         }
175         common_element_end('div');
176         common_element_start('div', array('id' => 'content'));
177         if ($notice && common_logged_in()) {
178                 common_views_menu();
179         }
180 }
181
182 function common_show_footer() {
183         global $xw, $config;
184         common_element_end('div'); # content div
185         common_foot_menu();
186         common_element_start('div', 'footer');
187         common_license_block();
188         common_element_end('div');
189         common_element_end('div');
190         common_element_end('body');
191         common_element_end('html');
192         common_end_xml();
193 }
194
195 function common_text($txt) {
196         global $xw;
197         $xw->text($txt);
198 }
199
200 function common_raw($xml) {
201         global $xw;
202         $xw->writeRaw($xml);
203 }
204
205 function common_license_block() {
206         global $config, $xw;
207         common_element_start('p', 'license');
208         common_element_start('a', array('class' => 'license',
209                                                                         'rel' => 'license',
210                                                                         href => $config['license']['url']));
211         common_element('img', array('class' => 'license',
212                                                                 'src' => $config['license']['image'],
213                                                                 'alt' => $config['license']['title']));
214         common_element_end('a');
215         common_text(_t('Unless otherwise specified, contents of this site are copyright by the contributors and available under the '));
216         common_element('a', array('class' => 'license',
217                                                           'rel' => 'license',
218                                                           href => $config['license']['url']),
219                                    $config['license']['title']);
220         common_text(_t('. Contributors should be attributed by full name or nickname.'));
221         common_element_end('p');
222 }
223
224 function common_nav_menu() {
225         $user = common_current_user();
226         common_element_start('ul', array('id' => 'nav'));
227         common_menu_item(common_local_url('public'), _t('Public'));
228         if ($user) {
229                 common_menu_item(common_local_url('profilesettings'),
230                                                  _t('Settings'));
231                 common_menu_item(common_local_url('logout'),
232                                                  _t('Logout'));
233         } else {
234                 common_menu_item(common_local_url('login'), _t('Login'));
235                 common_menu_item(common_local_url('register'), _t('Register'));
236         }
237         common_element_end('ul');
238 }
239
240 function common_views_menu() {
241         common_menu_item(common_local_url('all', array('nickname' =>
242                                                                                                    $user->nickname)),
243                                          _t('Home'));
244         common_menu_item(common_local_url('showstream', array('nickname' =>
245                                                                                                                   $user->nickname)),
246                                          _t('Profile'),  $user->fullname || $user->nickname);
247 }
248
249 function common_foot_menu() {
250         common_element_start('ul', array('id' => 'nav_sub'));
251         common_menu_item(common_local_url('doc', array('title' => 'about')),
252                                          _t('About'));
253         common_menu_item(common_local_url('doc', array('title' => 'help')),
254                                          _t('Help'));
255         common_menu_item(common_local_url('doc', array('title' => 'privacy')),
256                                          _t('Privacy'));
257         common_menu_item(common_local_url('doc', array('title' => 'source')),
258                                          _t('Source'));
259         common_element_end('ul');
260 }
261
262 function common_menu_item($url, $text, $title=NULL) {
263         $attrs['href'] = $url;
264         if ($title) {
265                 $attrs['title'] = $title;
266         }
267         common_element_start('li', 'menuitem');
268         common_element('a', $attrs, $text);
269         common_element_end('li');
270 }
271
272 function common_input($id, $label, $value=NULL) {
273         common_element_start('p');
274         common_element('label', array('for' => $id), $label);
275         $attrs = array('name' => $id,
276                                    'type' => 'text',
277                                    'id' => $id);
278         if ($value) {
279                 $attrs['value'] = htmlspecialchars($value);
280         }
281         common_element('input', $attrs);
282         common_element_end('p');
283 }
284
285 function common_hidden($id, $value) {
286         common_element('input', array('name' => $id,
287                                                                   'type' => 'hidden',
288                                                                   'id' => $id,
289                                                                   'value' => $value));
290 }
291
292 function common_password($id, $label) {
293         common_element_start('p');
294         common_element('label', array('for' => $id), $label);
295         $attrs = array('name' => $id,
296                                    'type' => 'password',
297                                    'id' => $id);
298         common_element('input', $attrs);
299         common_element_end('p');
300 }
301
302 function common_submit($id, $label) {
303         global $xw;
304         common_element_start('p');
305         common_element_start('label', array('for' => $id));
306         $xw->writeRaw('&nbsp;');
307         common_element_end('label');
308         common_element('input', array('type' => 'submit',
309                                                                   'id' => $id,
310                                                                   'name' => $id,
311                                                                   'value' => $label,
312                                                                   'class' => 'button'));
313         common_element_end('p');
314 }
315
316 function common_textarea($id, $label, $content=NULL) {
317         common_element_start('p');
318         common_element('label', array('for' => $id), $label);
319         common_element('textarea', array('rows' => 3,
320                                                                          'cols' => 40,
321                                                                          'name' => $id,
322                                                                          'id' => $id,
323                                                                          'class' => 'width50'),
324                                    ($content) ? $content : ' ');
325         common_element_end('p');
326 }
327
328 # salted, hashed passwords are stored in the DB
329
330 function common_munge_password($id, $password) {
331         return md5($id . $password);
332 }
333
334 # check if a username exists and has matching password
335 function common_check_user($nickname, $password) {
336         $user = User::staticGet('nickname', $nickname);
337         if (is_null($user)) {
338                 return false;
339         } else {
340                 return (0 == strcmp(common_munge_password($password, $user->id),
341                                                         $user->password));
342         }
343 }
344
345 # is the current user logged in?
346 function common_logged_in() {
347         return (!is_null(common_current_user()));
348 }
349
350 function common_have_session() {
351         return (0 != strcmp(session_id(), ''));
352 }
353
354 function common_ensure_session() {
355         if (!common_have_session()) {
356                 @session_start();
357         }
358 }
359
360 function common_set_user($nickname) {
361         if (is_null($nickname) && common_have_session()) {
362                 unset($_SESSION['userid']);
363                 return true;
364         } else {
365                 $user = User::staticGet('nickname', $nickname);
366                 if ($user) {
367                         common_ensure_session();
368                         $_SESSION['userid'] = $user->id;
369                         return true;
370                 } else {
371                         return false;
372                 }
373         }
374         return false;
375 }
376
377 # who is the current user?
378 function common_current_user() {
379         static $user = NULL; # FIXME: global memcached
380         if (is_null($user)) {
381                 common_ensure_session();
382                 $id = $_SESSION['userid'];
383                 if ($id) {
384                         $user = User::staticGet($id);
385                 }
386         }
387         return $user;
388 }
389
390 # get canonical version of nickname for comparison
391 function common_canonical_nickname($nickname) {
392         # XXX: UTF-8 canonicalization (like combining chars)
393         return $nickname;
394 }
395
396 # get canonical version of email for comparison
397 function common_canonical_email($email) {
398         # XXX: canonicalize UTF-8
399         # XXX: lcase the domain part
400         return $email;
401 }
402
403 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$_+!*();/?:~-]))');
404
405 function common_render_content($text, $notice) {
406         $r = htmlspecialchars($text);
407         $id = $notice->profile_id;
408         $r = preg_replace('@https?://\S+@', '<a href="\0" class="extlink">\0</a>', $r);
409         $r = preg_replace('/(^|\b)@([\w-]+)($|\b)/e', "'\\1@'.common_at_link($id, '\\2').'\\3'", $r);
410         # XXX: # tags
411         # XXX: machine tags
412         return $r;
413 }
414
415 function common_at_link($sender_id, $nickname) {
416         # Try to find profiles this profile is subscribed to that have this nickname
417         $recipient = new Profile();
418         # XXX: chokety and bad
419         $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = '.$sender_id.' and subscribed = id)', 'AND');
420         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
421         if ($recipient->find(TRUE)) {
422                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistenee">'.$nickname.'</a>';
423         }
424         # Try to find profiles that listen to this profile and that have this nickname
425         $recipient = new Profile();
426         # XXX: chokety and bad
427         $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = '.$sender_id.' and subscriber = id)', 'AND');
428         $recipient->whereAdd('nickname = "' . trim($nickname) . '"', 'AND');
429         if ($recipient->find(TRUE)) {
430                 return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink tolistener">'.$nickname.'</a>';
431         }
432         # If this is a local user, try to find a local user with that nickname.
433         $sender = User::staticGet($sender_id);
434         if ($sender) {
435                 $recipient_user = User::staticGet('nickname', $nickname);
436                 if ($recipient_user) {
437                         $recipient = $recipient->getProfile();
438                         return '<a href="'.htmlspecialchars($recipient->profileurl).'" class="atlink usertouser">'.$nickname.'</a>';
439                 }
440         }
441         # Otherwise, no links. @messages from local users to remote users,
442         # or from remote users to other remote users, are just
443         # outside our ability to make intelligent guesses about
444         return $nickname;
445 }
446
447 // where should the avatar go for this user?
448
449 function common_avatar_filename($id, $extension, $size=NULL, $extra=NULL) {
450         global $config;
451
452         if ($size) {
453                 return $id . '-' . $size . (($extra) ? ('-' . $extra) : '') . $extension;
454         } else {
455                 return $id . '-original' . (($extra) ? ('-' . $extra) : '') . $extension;
456         }
457 }
458
459 function common_avatar_path($filename) {
460         global $config;
461         return INSTALLDIR . '/avatar/' . $filename;
462 }
463
464 function common_avatar_url($filename) {
465         return common_path('avatar/'.$filename);
466 }
467
468 function common_default_avatar($size) {
469         static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
470                                                           AVATAR_STREAM_SIZE => 'stream',
471                                                           AVATAR_MINI_SIZE => 'mini');
472         global $config;
473
474         return common_path($config['avatar']['default'][$sizenames[$size]]);
475 }
476
477 function common_local_url($action, $args=NULL) {
478         global $config;
479         if ($config['site']['fancy']) {
480                 return common_fancy_url($action, $args);
481         } else {
482                 return common_simple_url($action, $args);
483         }
484 }
485
486 function common_fancy_url($action, $args=NULL) {
487         switch (strtolower($action)) {
488          case 'public':
489                 return common_path('');
490          case 'publicrss':
491                 return common_path('rss');
492          case 'doc':
493                 return common_path('doc/'.$args['title']);
494          case 'login':
495          case 'logout':
496          case 'register':
497          case 'subscribe':
498          case 'unsubscribe':
499                 return common_path('main/'.$action);
500          case 'avatar':
501          case 'password':
502                 return common_path('settings/'.$action);
503          case 'profilesettings':
504                 return common_path('settings/profile');
505          case 'newnotice':
506                 return common_path('notice/new');
507          case 'shownotice':
508                 return common_path('notice/'.$args['notice']);
509          case 'subscriptions':
510          case 'subscribed':
511          case 'xrds':           
512          case 'all':
513          case 'foaf':
514                 return common_path($args['nickname'].'/'.$action);
515          case 'allrss':
516                 return common_path($args['nickname'].'/all/rss');
517          case 'userrss':
518                 return common_path($args['nickname'].'/rss');
519          case 'showstream':
520                 return common_path($args['nickname']);
521          default:
522                 return common_simple_url($action, $args);
523         }
524 }
525
526 function common_simple_url($action, $args=NULL) {
527         global $config;
528         /* XXX: pretty URLs */
529         $extra = '';
530         if ($args) {
531                 foreach ($args as $key => $value) {
532                         $extra .= "&${key}=${value}";
533                 }
534         }
535         return common_path("index.php?action=${action}${extra}");
536 }
537
538 function common_path($relative) {
539         global $config;
540         $pathpart = ($config['site']['path']) ? $config['site']['path']."/" : '';
541         return "http://".$config['site']['server'].'/'.$pathpart.$relative;
542 }
543
544 function common_date_string($dt) {
545         // XXX: do some sexy date formatting
546         // return date(DATE_RFC822, $dt);
547         return $dt;
548 }
549
550 function common_date_w3dtf($dt) {
551         $t = strtotime($dt);
552         return date(DATE_W3C, $t);
553 }
554
555 function common_redirect($url, $code=307) {
556         static $status = array(301 => "Moved Permanently",
557                                                    302 => "Found",
558                                                    303 => "See Other",
559                                                    307 => "Temporary Redirect");
560         header("Status: ${code} $status[$code]");
561         header("Location: $url");
562         common_element('a', array('href' => $url), $url);
563 }
564
565 function common_broadcast_notice($notice, $remote=false) {
566         // XXX: optionally use a queue system like http://code.google.com/p/microapps/wiki/NQDQ
567         if (!$remote) {
568                 # Make sure we have the OMB stuff
569                 require_once(INSTALLDIR.'/lib/omb.php');
570                 omb_broadcast_remote_subscribers($notice);
571         }
572         // XXX: broadcast notices to Jabber
573         // XXX: broadcast notices to SMS
574         // XXX: broadcast notices to other IM
575         return true;
576 }
577
578
579 function common_profile_url($nickname) {
580         return common_local_url('showstream', array('nickname' => $nickname));
581 }
582
583 # Don't call if nobody's logged in
584
585 function common_notice_form() {
586         $user = common_current_user();
587         assert(!is_null($user));
588         common_element_start('form', array('id' => 'status_form',
589                                                                            'method' => 'POST',
590                                                                            'action' => common_local_url('newnotice')));
591         common_element('label', array('for' => 'status_update',
592                                                                   'id' => 'status_label'),
593                                    _t('What\'s up, ').$user->nickname.'?');
594         common_element('textarea', 'status_textarea');
595         common_element('input', array('id' => 'status_submit',
596                                                                   'type' => 'submit',
597                                                                   'value' => _t('Send')));
598         common_element_end('form');
599 }
600
601 function common_mint_tag($extra) {
602         global $config;
603         return
604           'tag:'.$config['tag']['authority'].','.
605           $config['tag']['date'].':'.$config['tag']['prefix'].$extra;
606 }
607
608 # Should make up a reasonable root URL
609
610 function common_root_url() {
611         return common_path('');
612 }
613
614 # returns $bytes bytes of random data as a hexadecimal string
615 # "good" here is a goal and not a guarantee
616
617 function common_good_rand($bytes) {
618         # XXX: use random.org...?
619         if (file_exists('/dev/urandom')) {
620                 return common_urandom($bytes);
621         } else { # FIXME: this is probably not good enough
622                 return common_mtrand($bytes);
623         }
624 }
625
626 function common_urandom($bytes) {
627         $h = fopen('/dev/urandom', 'rb');
628         # should not block
629         $src = fread($h, $bytes);
630         fclose($h);
631         $enc = '';
632         for ($i = 0; $i < $bytes; $i++) {
633                 $enc .= sprintf("%02x", (ord($src[$i])));
634         }
635         return $enc;
636 }
637
638 function common_mtrand($bytes) {
639         $enc = '';
640         for ($i = 0; $i < $bytes; $i++) {
641                 $enc .= sprintf("%02x", mt_rand(0, 255));
642         }
643         return $enc;
644 }
645
646 function common_set_returnto($url) {
647         common_ensure_session();
648         $_SESSION['returnto'] = $url;
649 }
650
651 function common_get_returnto() {
652         common_ensure_session();
653         return $_SESSION['returnto'];
654 }
655
656 function common_timestamp() {
657         return date('YmdHis');
658 }
659
660 // XXX: set up gettext
661
662 function _t($str) {
663         return $str;
664 }
665
666 function common_ensure_syslog() {
667         static $initialized = false;
668         if (!$initialized) {
669                 global $config;
670                 define_syslog_variables();
671                 openlog($config['syslog']['appname'], 0, LOG_USER);
672                 $initialized = true;
673         }
674 }
675
676 function common_log($priority, $msg, $filename=NULL) {
677         common_ensure_syslog();
678         syslog($priority, $msg);
679 }
680
681 function common_debug($msg, $filename=NULL) {
682         if ($filename) {
683                 common_log(LOG_DEBUG, basename($filename).' - '.$msg);
684         } else {
685                 common_log(LOG_DEBUG, $msg);
686         }
687 }
688
689 function common_valid_http_url($url) {
690         return Validate::uri($url, array('allowed_schemes' => array('http', 'https')));
691 }
692
693 function common_valid_tag($tag) {
694         if (preg_match('/^tag:(.*?),(\d{4}(-\d{2}(-\d{2})?)?):(.*)$/', $tag, $matches)) {
695                 return (Validate::email($matches[1]) ||
696                                 preg_match('/^([\w-\.]+)$/', $matches[1]));
697         }
698         return false;
699 }
700
701 # Does a little before-after block for next/prev page
702
703 function common_pagination($have_before, $have_after, $page, $action, $args=NULL) {             
704         
705         if ($have_before || $have_after) {
706                 common_element_start('div', array('id' => 'pagination'));
707                 common_element_start('ul', array('id' => 'nav_pagination'));
708         }
709         
710         if ($have_before) {
711                 $pargs = array('page' => $page-1);
712                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
713                                                                                  
714                 common_element_start('li', 'before');
715                 common_element('a', array('href' => common_local_url($action, $newargs)),
716                                            _t('« Before'));
717                 common_element_end('li');
718         }
719
720         if ($have_after) {
721                 $pargs = array('page' => $page+1);
722                 $newargs = ($args) ? array_merge($args,$pargs) : $pargs;
723                 common_element_start('li', 'after');
724                 common_element('a', array('href' => common_local_url($action, $newargs)),
725                                                    _t('After »'));
726                 common_element_end('li');
727         }
728         
729         if ($have_before || $have_after) {
730                 common_element_end('ul');
731                 common_element_end('div');
732         }
733 }