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