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