Completed
Pull Request — master (#24)
by Lars
12:05
created

index.php ➔ __()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
$config_file = dirname(__FILE__) . DIRECTORY_SEPARATOR . '/../config.local.php';
3
4
if (!file_exists($config_file)) {
5
    die('The config.local.php file is missing. Please create it.');
6
}
7
8
require_once $config_file;
9
10
/**
11
 * An error-handler which converts all errors (regardless of level) into exceptions.
12
 * It respects error_reporting settings.
13
 */
14
function intraface_exceptions_error_handler($severity, $message, $filename, $lineno) {
15
    throw new ErrorException($message, 0, $severity, $filename, $lineno);
16
}
17
18
set_error_handler('intraface_exceptions_error_handler', error_reporting());
19
20
require_once dirname(__FILE__) . '/../../../vendor/autoload.php';
21
require_once 'Intraface/common.php';
22
spl_autoload_register('k_autoload');
23
24
class Intraface_AuthenticatedUser extends k_AuthenticatedUser
25
{
26
    protected $language;
27
28
    function __construct($name, k_Language $lang)
29
    {
30
        $this->language = $lang;
31
        parent::__construct($name);
32
    }
33
34
    function language()
35
    {
36
        return $this->language;
37
    }
38
}
39
40
// session_start();
41
42
class DanishLanguage implements k_Language
43
{
44
    function name()
45
    {
46
        return 'Danish';
47
    }
48
49
    function isoCode()
50
    {
51
        return 'dk';
52
    }
53
}
54
55
class EnglishLanguage implements k_Language
56
{
57
    function name()
58
    {
59
        return 'English';
60
    }
61
62
    function isoCode()
63
    {
64
        return 'uk';
65
    }
66
}
67
68
class Intraface_LanguageLoader implements k_LanguageLoader {
69
    // @todo The language will often not be set on runtime, e.g. an
70
    //       intranet where the user can chose him or her own language?
71
    //       How could one accommodate for this?
72
    function load(k_Context $context)
73
    {
74
        $supported = array("da" => true, "en-US" => true);
75
76
        if ($context->identity()->anonymous()) {
77
            $language = HTTP::negotiateLanguage($supported);
78
            if (PEAR::isError($language)) {
79
                // fallback language in case of unable to negotiate
80
                return new DanishLanguage();
81
            }
82
83
            if ($language == 'da') {
84
                return new DanishLanguage();
85
            }
86
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
87
        } elseif ($context->identity()->language() == 'da') {
88
            return new DanishLanguage();
89
        }
90
91
        // @todo at the moment the system does not take the
92
        //       settings in the system into account - only
93
        //       the way the browser is setup.
94
        $language = HTTP::negotiateLanguage($supported);
95
        if (PEAR::isError($language)) {
96
            // fallback language in case of unable to negotiate
97
            return new DanishLanguage();
98
        }
99
100
        if ($language == 'da') {
101
            return new DanishLanguage();
102
        }
103
104
        // fallback language
105
        return new EnglishLanguage();
106
    }
107
}
108
109
class k_Translation2Translator implements k_Translator
110
{
111
    protected $translation2;
112
    protected $page_id;
113
    protected $page;
114
115
    function __construct($lang, $page_id = NULL)
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
116
    {
117
        $factory = new Intraface_Factory;
118
        $cache = $factory->new_Translation2_Cache();
119
120
        if ($page_id == NULL) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
121
            $cache_key = 'common';
122
        } else {
123
            $cache_key = $page_id;
124
        }
125
126
        if ($data = $cache->get($cache_key, 'translation-'.$lang)) {
127
            $this->page = unserialize($data);
128
        } else {
129
            $translation2 = $factory->new_Translation2();
130
            $res = $translation2->setLang($lang);
131
132
            if (PEAR::isError($res)) {
133
                throw new Exception('Could not setLang():' . $res->getMessage());
134
            }
135
136
            $this->page = $translation2->getPage('common');
137
            if ($page_id != NULL) {
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
138
                $this->page = array_merge($this->page, $translation2->getPage($page_id));
139
            }
140
141
            $cache->save(serialize($this->page), $cache_key, 'translation-'.$lang);
142
        }
143
144
        $this->page_id = $page_id;
145
        $this->lang = $lang;
0 ignored issues
show
Bug introduced by
The property lang does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
146
    }
147
148
    function translate($phrase, k_Language $language = null)
149
    {
150
        if (isset($this->page[$phrase])) {
151
            return utf8_encode($this->page[$phrase]);
152
        }
153
154
        $logger = new ErrorHandler_Observer_File(TRANSLATION_ERROR_LOG);
155
        $details = array(
156
                'date' => date('r'),
157
                'type' => 'Translation2',
158
                'message' => 'Missing translation for "'.$phrase.'" on pageID: "'.$this->page_id.'", LangID: "'.$this->lang.'"',
159
                'file' => '[unknown]',
160
                'line' => '[unknown]'
161
            );
162
163
        $logger->update($details);
164
165
        return $phrase;
166
167
    }
168
169
    public function get($phrase)
170
    {
171
        return $this->translate($phrase);
172
    }
173
}
174
175
class Intraface_TranslatorLoader implements k_TranslatorLoader
176
{
177
    function load(k_Context $context)
178
    {
179
        $subspace = explode('/', $context->subspace());
180
        if (count($subspace) > 3 && $subspace[1] == 'restricted' && $subspace[2] == 'module' && !empty($subspace[3])) {
181
            $module = $subspace[3];
182
        } else {
183
            $module = NULL;
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
184
        }
185
        return new k_Translation2Translator($context->language()->isoCode(), $module);
186
    }
187
}
188
189
class Intraface_IdentityLoader implements k_IdentityLoader
190
{
191
    function load(k_Context $context)
192
    {
193
        if ($context->session('intraface_identity')) {
194
            return $context->session('intraface_identity');
195
        }
196
        return new k_Anonymous();
197
    }
198
}
199
200
class NotAuthorizedComponent extends k_Component
201
{
202
    function dispatch()
203
    {
204
        // redirect to login-page
205
        return new k_TemporaryRedirect($this->url('/login', array('continue' => $this->requestUri())));
206
    }
207
}
208
209
class Intraface_Document extends k_Document
210
{
211
    public $options;
212
    function options()
213
    {
214
        if (empty($this->options)) return array();
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
215
        return $this->options;
216
    }
217
}
218
219 View Code Duplication
class Intraface_TemplateFactory extends k_DefaultTemplateFactory
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
220
{
221
    function create($filename)
222
    {
223
        $filename = $filename . '.tpl.php';
224
        $__template_filename__ = k_search_include_path($filename);
225
        if (!is_file($__template_filename__)) {
226
            throw new Exception("Failed opening '".$filename."' for inclusion. (include_path=".ini_get('include_path').")");
227
        }
228
        return new k_Template($__template_filename__);
229
    }
230
}
231
232
$components = new k_InjectorAdapter($bucket, new Intraface_Document);
233
$components->setImplementation('k_DefaultNotAuthorizedComponent', 'NotAuthorizedComponent');
234
235
/**
236
 * Translates a string.
237
 */
238
function __($str) {
0 ignored issues
show
Coding Style introduced by
__ uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
239
  return $GLOBALS['k_current_context']->translator()->translate($str);
240
}
241
242
if (realpath($_SERVER['SCRIPT_FILENAME']) == __FILE__) {
243
    try {
244
        k()
245
        // Use container for wiring of components
246
        ->setComponentCreator($components)
247
        // Enable file logging
248
        ->setLog(K2_LOG)
249
        // Uncomment the next line to enable in-browser debugging
250
        //->setDebug(K2_DEBUG)
251
        // Dispatch request
252
        ->setIdentityLoader(new Intraface_IdentityLoader())
253
        ->setLanguageLoader(new Intraface_LanguageLoader())
254
        ->setTranslatorLoader(new Intraface_TranslatorLoader())
255
        ->run('Intraface_Controller_Index')
256
        ->out();
257
    } catch (Exception $e) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
258
259
        $render = new Ilib_Errorhandler_Handler_File(Log::factory('file', ERROR_LOG, 'INTRAFACE'));
260
        $render->handle($e);
261
262
        if (SERVER_STATUS != 'PRODUCTION') {
263
            $render = new Ilib_Errorhandler_Handler_Echo();
264
            $render->handle($e);
265
            die;
266
        }
267
268
        die('<h1>An error orrured!</h1> <P>We have been notified about the problem, but you are always welcome to contact us on [email protected].</p><p>We apologize for the inconvenience.</p> <pre style="color: white;">'.$e.'</pre>');
269
    }
270
}
271