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