summaryrefslogtreecommitdiffstats
path: root/lib/kolab_client_task.php
blob: 7cc8863694427211fce0a94e1622424b3544f84b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
<?php
/*
 +--------------------------------------------------------------------------+
 | This file is part of the Kolab Web Admin Panel                           |
 |                                                                          |
 | Copyright (C) 2011-2012, Kolab Systems AG                                |
 |                                                                          |
 | This program is free software: you can redistribute it and/or modify     |
 | it under the terms of the GNU Affero General Public License as published |
 | by the Free Software Foundation, either version 3 of the License, or     |
 | (at your option) any later version.                                      |
 |                                                                          |
 | This program is distributed in the hope that it will be useful,          |
 | but WITHOUT ANY WARRANTY; without even the implied warranty of           |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the             |
 | GNU Affero General Public License for more details.                      |
 |                                                                          |
 | You should have received a copy of the GNU Affero General Public License |
 | along with this program. If not, see <http://www.gnu.org/licenses/>      |
 +--------------------------------------------------------------------------+
 | Author: Aleksander Machniak <machniak@kolabsys.com>                      |
 | Author: Jeroen van Meeuwen <vanmeeuwen@kolabsys.com>                     |
 +--------------------------------------------------------------------------+
*/


class kolab_client_task
{
    /**
     * @var kolab_client_output
     */
    protected $output;

    /**
     * @var kolab_client_api
     */
    protected $api;

    protected $ajax_only = false;
    protected $page_title = 'Kolab Admin Panel';
    protected $menu = array();

    protected static $translation = array();


    /**
     * Class constructor.
     */
    public function __construct()
    {
        $this->config_init();
        $this->output_init();
        $this->api_init();

        ini_set('session.use_cookies', 'On');
        session_start();

        $this->auth();
    }

    /**
     * Localization initialization.
     */
    private function locale_init()
    {
        $language = $this->get_language();
        $LANG     = array();

        if (!$language) {
            $language = 'en_US';
        }

        @include INSTALL_PATH . '/locale/en_US.php';

        if ($language != 'en_US') {
            @include INSTALL_PATH . "/locale/$language.php";
        }

        setlocale(LC_ALL, $language . '.utf8', 'en_US.utf8');

        self::$translation = $LANG;
    }

    /**
     * Configuration initialization.
     */
    private function config_init()
    {
        $this->config = Conf::get_instance();
    }

    /**
     * Output initialization.
     */
    private function output_init()
    {
        $skin = $this->config_get('skin', 'default');
        $this->output = new kolab_client_output($skin);
    }

    /**
     * API initialization
     */
    private function api_init()
    {
        $url = $this->config_get('api_url', '');

        if (!$url) {
    	    // @TODO: http/https
            $url = 'http://' . $_SERVER['SERVER_NAME'];
            $url .= preg_replace('/\/?\?.*$/', '', $_SERVER['REQUEST_URI']);
            $url .= '/api';
        }

        $this->api = new kolab_client_api($url);
    }

    /**
     * Returns system language (locale) setting.
     *
     * @return string Language code
     */
    private function get_language()
    {
        $aliases = array(
            'de' => 'de_DE',
            'en' => 'en_US',
            'pl' => 'pl_PL',
        );

        // UI language
        $langs = !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
        $langs = explode(',', $langs);

        if (!empty($_SESSION['user']) && !empty($_SESSION['user']['language'])) {
            array_unshift($langs, $_SESSION['user']['language']);
        }

        while ($lang = array_shift($langs)) {
            $lang = explode(';', $lang);
            $lang = $lang[0];
            $lang = str_replace('-', '_', $lang);

            if (file_exists(INSTALL_PATH . "/locale/$lang.php")) {
                return $lang;
            }

            if (isset($aliases[$lang]) && ($alias = $aliases[$lang])
                && file_exists(INSTALL_PATH . "/locale/$alias.php")
            ) {
                return $alias;
            }
        }

        return null;
    }

    /**
     * User authentication (and authorization).
     */
    private function auth()
    {
        if (isset($_POST['login'])) {
            $login = $this->get_input('login', 'POST');

            if ($login['username']) {
                $result = $this->api->login($login['username'], $login['password']);

                if ($token = $result->get('session_token')) {
                    $user = array('token' => $token, 'domain' => $result->get('domain'));

                    $this->api->set_session_token($user['token']);

                    // find user settings
                    $res = $this->api->get('user.info', array('user' => $login['username']));
                    $res = $res->get();

                    if (is_array($res) && ($res = array_shift($res))) {
                        $user['language'] = $res['preferredlanguage'];
                        $user['fullname'] = $res['cn'];
                    }
                    // @TODO: why user.info returns empty result for 'cn=Directory Manager' login?
                    else if (preg_match('/^cn=([a-zA-Z ]+)/', $login['username'], $m)) {
                        $user['fullname'] = $m[1];
                    }

                    // Save user data
                    $_SESSION['user'] = $user;

                    if (($language = $this->get_language()) && $language != 'en_US') {
                        $_SESSION['user']['language'] = $language;
                        $session_config['language']   = $language;
                    }

                    // Configure API session
                    if (!empty($session_config)) {
                        $this->api->post('system.configure', null, $session_config);
                    }

                    header('Location: ?');
                    die;
                }
                else {
                    $code  = $result->get_error_code();
                    $str   = $result->get_error_str();
                    $label = 'loginerror';

                    if ($code == kolab_client_api::ERROR_INTERNAL
                        || $code == kolab_client_api::ERROR_CONNECTION
                    ) {
                        $label = 'internalerror';
                        $this->raise_error(500, 'Login failed. ' . $str);
                    }
                    $this->output->command('display_message', $label, 'error');
                }
            }
        }
        else if (!empty($_SESSION['user']) && !empty($_SESSION['user']['token'])) {
            $this->api->set_session_token($_SESSION['user']['token']);
            return;
        }
    }

    /**
     * Main execution.
     */
    public function run()
    {
        // Initialize locales
        $this->locale_init();

        // Assign self to template variable
        $this->output->assign('engine', $this);

        // Session check
        if (empty($_SESSION['user']) || empty($_SESSION['user']['token'])) {
            $this->action_logout();
        }

        // Run security checks
        $this->input_checks();

        $action = $this->get_input('action', 'GET');

        if ($action) {
            $method = 'action_' . $action;
            if (method_exists($this, $method)) {
                $this->$method();
            }
        }
        else if (method_exists($this, 'action_default')) {
            $this->action_default();
        }
    }

    /**
     * Security checks and input validation.
     */
    public function input_checks()
    {
        $ajax = $this->output->is_ajax();

        // Check AJAX-only tasks
        if ($this->ajax_only && !$ajax) {
            $this->raise_error(500, 'Invalid request type!', null, true);
        }

        // CSRF prevention
        $token  = $ajax ? kolab_utils::get_request_header('X-Session-Token') : $this->get_input('token');
        $task   = $this->get_task();

        if ($task != 'main' && $token != $_SESSION['user']['token']) {
            $this->raise_error(403, 'Invalid request data!', null, true);
        }
    }

    /**
     * Logout action.
     */
    private function action_logout()
    {
        if (!empty($_SESSION['user']) && !empty($_SESSION['user']['token'])) {
            $this->api->logout();
        }
        $_SESSION = array();

        if ($this->output->is_ajax()) {
            $this->output->command('main_logout');
        }
        else {
            $this->output->add_translation('loginerror', 'internalerror');
        }

        $this->output->send('login');
        exit;
    }

    /**
     * Error action (with error logging).
     *
     * @param int    $code   Error code
     * @param string $msg    Error message
     * @param array  $args   Optional arguments (type, file, line)
     * @param bool   $output Enable to send output and finish
     */
    public function raise_error($code, $msg, $args = array(), $output = false)
    {
        $log_line = sprintf("%s Error: %s (%s)",
            isset($args['type']) ? $args['type'] : 'PHP',
            $msg . (isset($args['file']) ? sprintf(' in %s on line %d', $args['file'], $args['line']) : ''),
            $_SERVER['REQUEST_METHOD']);

        if (!write_log('errors', $log_line)) {
            // send error to PHPs error handler if write_log() didn't succeed
            trigger_error($msg, E_USER_ERROR);
        }

        if (!$output) {
            return;
        }

        if ($this->output->is_ajax()) {
            header("HTTP/1.0 $code $msg");
            die;
        }

        $this->output->assign('error_code', $code);
        $this->output->assign('error_message', $msg);
        $this->output->send('error');
        exit;
    }

    /**
     * Output sending.
     */
    public function send()
    {
        $template = $this->get_task();

        if ($this->page_title) {
            $this->output->assign('pagetitle', $this->page_title);
        }

        $this->output->send($template);
        exit;
    }

    /**
     * Returns name of the current task.
     *
     * @return string Task name
     */
    public function get_task()
    {
        $class_name = get_class($this);

        if (preg_match('/^kolab_client_task_([a-z]+)$/', $class_name, $m)) {
            return $m[1];
        }
    }

    /**
     * Returns configuration option value.
     *
     * @param string $name      Option name
     * @param mixed  $fallback  Default value
     *
     * @return mixed Option value
     */
    public function config_get($name, $fallback = null)
    {
        $value = $this->config->get('kolab_wap', $name);
        return $value !== null ? $value : $fallback;
    }

    /**
     * Returns translation of defined label/message.
     *
     * @return string Translated string.
     */
    public static function translate()
    {
        $args = func_get_args();

        if (is_array($args[0])) {
            $args = $args[0];
        }

        $label = $args[0];

        if (isset(self::$translation[$label])) {
	        $content = trim(self::$translation[$label]);
        }
	    else {
	        $content = $label;
        }

        for ($i = 1, $len = count($args); $i < $len; $i++) {
            $content = str_replace('$'.$i, $args[$i], $content);
        }

        return $content;
    }

    /**
     * Returns input parameter value.
     *
     * @param string $name       Parameter name
     * @param string $type       Parameter type (GET|POST|NULL)
     * @param bool   $allow_html Enable to strip invalid/unsecure content
     *
     * @see kolab_utils::get_input
     * @return mixed Input value.
     */
    public static function get_input($name, $type = null, $allow_html = false)
    {
        if ($type == 'GET') {
            $type = kolab_utils::REQUEST_GET;
        }
        else if ($type == 'POST') {
            $type = kolab_utils::REQUEST_POST;
        }
        else {
            $type = kolab_utils::REQUEST_ANY;
        }

        return kolab_utils::get_input($name, $type, $allow_html);
    }

    /**
     * Returns task menu output.
     *
     * @return string HTML output
     */
    protected function menu()
    {
        if (empty($this->menu)) {
            return '';
        }

        $task = $this->get_task();
// @TODO: hide menu items according to capabilities
//        $caps = (array) $this->capabilities();

        foreach ($this->menu as $idx => $label) {
            if (strpos($idx, '.')) {
                $action = $idx;
                $class  = preg_replace('/\.[a-z_-]+$/', '', $idx);
            }
            else {
                $action = $task . '.' . $idx;
                $class  = $idx;
            }

            $menu[$idx] = sprintf('<li class="%s">'
                .'<a href="#%s" onclick="return kadm.command(\'%s\', \'\', this)">%s</a></li>',
                $class, $idx, $action, $this->translate($label));
        }

        return '<ul>' . implode("\n", $menu) . '</ul>';
    }

    /**
     * Adds watermark page definition into main page.
     */
    protected function watermark($name)
    {
        $this->output->command('set_watermark', $name);
    }

    /**
     * Returns list of user types.
     *
     * @return array List of user types
     */
    protected function user_types()
    {
        if (!isset($_SESSION['user_types'])) {
            $result = $this->api->post('user_types.list');
            $list   = $result->get('list');

            if (is_array($list)) {
                $_SESSION['user_types'] = $list;
            }
        }

        return $_SESSION['user_types'];
    }

    /**
     * Returns list of system capabilities.
     *
     * @return array List of system capabilities
     */
    protected function capabilities()
    {
        if (!isset($_SESSION['capabilities'])) {
            $result = $this->api->post('system.capabilities');
            $list   = $result->get('list');

            if (is_array($list)) {
                $_SESSION['capabilities'] = $list;
            }
        }

        $domain = $_SESSION['user']['domain'];

        return $_SESSION['capabilities'][$domain];
    }

    /**
     * Returns system capability
     *
     * @param string $name Capability (key) name
     *
     * @return array Capability value if supported, NULL otherwise
     */
    protected function get_capability($name)
    {
        $caps = $this->capabilities();

        return $caps[$name];
    }

    /**
     * Returns execution time in seconds
     *
     * @param string Execution time
     */
    public function gentime()
    {
        return sprintf('%.4f', microtime(true) - KADM_START);
    }

    /**
     * Returns HTML output of login form
     *
     * @param string HTML output
     */
    public function login_form()
    {
        $post = $this->get_input('login', 'POST');

        $username = kolab_html::label(array(
                'for'     => 'login_name',
                'content' => $this->translate('login.username')), true)
            . kolab_html::input(array(
                'type'  => 'text',
                'id'    => 'login_name',
                'name'  => 'login[username]',
                'value' => $post['username']));

        $password = kolab_html::label(array(
                'for'     => 'login_pass',
                'content' => $this->translate('login.password')), true)
            . kolab_html::input(array(
                'type'  => 'password',
                'id'    => 'login_pass',
                'name'  => 'login[password]',
                'value' => ''));

        $button = kolab_html::input(array(
            'type'  => 'submit',
            'id'    => 'login_submit',
            'value' => $this->translate('login.login')));

        $form = kolab_html::form(array(
            'id'     => 'login_form',
            'name'   => 'login',
            'method' => 'post',
            'action' => '?'),
            kolab_html::span(array('content' => $username))
            . kolab_html::span(array('content' => $password))
            . $button);

        return $form;
    }
}