Passed
Push — master ( bee4ae...fc5262 )
by Andreas
16:28
created

midcom_application::get_host_prefix()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4.128

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 5
nop 0
dl 0
loc 15
ccs 8
cts 10
cp 0.8
crap 4.128
rs 9.9666
c 0
b 0
f 0
1
<?php
2
/**
3
 * @package midcom
4
 * @author The Midgard Project, http://www.midgard-project.org
5
 * @copyright The Midgard Project, http://www.midgard-project.org
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 */
8
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\HttpKernel\HttpKernelInterface;
11
use Symfony\Component\HttpKernel\Kernel;
12
use Symfony\Component\Config\Loader\LoaderInterface;
13
use Symfony\Component\DependencyInjection\ContainerBuilder;
14
use midcom\dependencyInjection\loggerPass;
15
use midcom\dependencyInjection\componentPass;
16
17
/**
18
 * Main controlling instance of the MidCOM Framework
19
 *
20
 * @property midcom_services_i18n $i18n
21
 * @property midcom_helper__componentloader $componentloader
22
 * @property midcom_services_dbclassloader $dbclassloader
23
 * @property midcom_helper__dbfactory $dbfactory
24
 * @property midcom_helper_head $head
25
 * @property midcom_helper__styleloader $style
26
 * @property midcom_services_auth $auth
27
 * @property midcom_services_permalinks $permalinks
28
 * @property midcom_services_toolbars $toolbars
29
 * @property midcom_services_uimessages $uimessages
30
 * @property midcom_services_metadata $metadata
31
 * @property midcom_services_rcs $rcs
32
 * @property midcom_services__sessioning $session
33
 * @property midcom_services_indexer $indexer
34
 * @property midcom_config $config
35
 * @property midcom_services_cache $cache
36
 * @property midcom\events\dispatcher $dispatcher
37
 * @property midcom_debug $debug
38
 * @package midcom
39
 */
40
class midcom_application extends Kernel
41
{
42
    /**
43
     * Host prefix cache to avoid computing it each time.
44
     *
45
     * @var string
46
     * @see get_host_prefix()
47
     */
48
    private $_cached_host_prefix = '';
49
50
    /**
51
     * Page prefix cache to avoid computing it each time.
52
     *
53
     * @var string
54
     * @see get_page_prefix()
55
     */
56
    private $_cached_page_prefix = '';
57
58
    /**
59
     * @var Request
60
     */
61
    private $request;
62
63
    /**
64
     * Set this variable to true during the handle phase of your component to
65
     * not show the site's style around the component output. This is mainly
66
     * targeted at XML output like RSS feeds and similar things. The output
67
     * handler of the site, excluding the style-init/-finish tags will be executed
68
     * immediately after the handle phase
69
     *
70
     * Changing this flag after the handle phase or for dynamically loaded
71
     * components won't change anything.
72
     *
73
     * @var boolean
74
     */
75
    public $skip_page_style = false;
76
77
    private $project_dir;
78
79
    /**
80
     * @var midcom_config
81
     */
82
    private $cfg;
83
84
    public function __construct(string $environment, bool $debug)
85
    {
86
        midcom_compat_environment::initialize();
87
        $this->request = Request::createFromGlobals();
88
        $this->cfg = new midcom_config;
89
        parent::__construct($environment, $debug);
90
    }
91
92
    public function registerContainerConfiguration(LoaderInterface $loader)
93
    {
94
        $loader->load(__DIR__ . '/config/services.yml');
95
        if ($classes = midcom::get_registered_service_classes()) {
96
            $loader->load(function (ContainerBuilder $container) use ($classes) {
97
                foreach ($classes as $id => $class) {
98
                    $container->findDefinition($id)->setClass($class);
99
                }
100
            });
101
        }
102
    }
103
104
    protected function initializeContainer()
105
    {
106
        parent::initializeContainer();
107
        $this->container->set('config', $this->cfg);
108
    }
109
110
    protected function build(ContainerBuilder $container)
111
    {
112
        parent::build($container);
113
        $container->addCompilerPass(new loggerPass($this->cfg));
114
        $container->addCompilerPass(new componentPass($this->cfg));
115
    }
116
117
    public function registerBundles()
118
    {
119
        return [];
120
    }
121
122
    public function getProjectDir()
123
    {
124
        if ($this->project_dir === null) {
125
            if (basename(dirname(__DIR__, 4)) === 'vendor') {
126
                // this is the case where we're installed as a dependency
127
                $this->project_dir = dirname(__DIR__, 5);
128
            } else {
129
                $this->project_dir = dirname(__DIR__, 2);
130
            }
131
        }
132
        return $this->project_dir;
133
    }
134
135 325
    public function getCacheDir()
136
    {
137 325
        return $this->cfg->get('cache_base_directory') ?: parent::getCacheDir();
138
    }
139
140
    /**
141
     * Magic getter for service loading
142
     */
143 735
    public function __get($key)
144
    {
145 735
        return $this->getContainer()->get($key);
146
    }
147
148
    /**
149
     * Magic setter
150
     */
151
    public function __set($key, $value)
152
    {
153
        $this->getContainer()->set($key, $value);
154
    }
155
156
    /* *************************************************************************
157
     * Control framework:
158
     * codeinit      - Handle the current request
159
     * dynamic_load   - Dynamically load and execute a URL
160
     * finish         - Cleanup Work
161
     */
162
163
    /**
164
     * Initialize the URL parser and process the request.
165
     *
166
     * This function must be called before any output starts.
167
     */
168
    public function codeinit()
169
    {
170
        try {
171
            $this->handle($this->request)->send();
172
        } catch (Error $e) {
173
            $this->getHttpKernel()->terminateWithException($e);
0 ignored issues
show
Bug introduced by
The method terminateWithException() does not exist on Symfony\Component\HttpKernel\HttpKernelInterface. It seems like you code against a sub-type of Symfony\Component\HttpKernel\HttpKernelInterface such as Symfony\Component\HttpKernel\HttpKernel. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

173
            $this->getHttpKernel()->/** @scrutinizer ignore-call */ terminateWithException($e);
Loading history...
174
        }
175
    }
176
177
    /**
178
     * Dynamically execute a subrequest and insert its output in place of the
179
     * function call.
180
     *
181
     * It tries to load the component referenced with the URL $url and executes
182
     * it as if it was used as primary component.
183
     *
184
     * This is only possible if the system is in the Page-Style output phase. It
185
     * cannot be used within code-init or during the output phase of another
186
     * component.
187
     *
188
     * Example code, executed on a site's homepage, it will load the news listing from
189
     * the given URL and display it using a substyle of the node style that is assigned
190
     * to the loaded one:
191
     *
192
     * <code>
193
     * $blog = '/blog/latest/3/';
194
     * $substyle = 'homepage';
195
     * midcom::get()->dynamic_load("/midcom-substyle-{$substyle}/{$blog}");
196
     * </code>
197
     *
198
     * Results of dynamic_loads are cached with the system cache strategy
199
     *
200
     * @param string $url                The URL, relative to the Midgard Page, that is to be requested.
201
     */
202 16
    public function dynamic_load($url)
203
    {
204 16
        debug_add("Dynamic load of URL {$url}");
205 16
        $url = midcom_connection::get_url('prefix') . $url;
206
207
        // Determine new Context ID and set current context,
208
        // enter that context and prepare its data structure.
209 16
        $oldcontext = midcom_core_context::get();
210 16
        $context = midcom_core_context::enter($url, $oldcontext->get_key(MIDCOM_CONTEXT_ROOTTOPIC));
0 ignored issues
show
Bug introduced by
It seems like $oldcontext->get_key(MIDCOM_CONTEXT_ROOTTOPIC) can also be of type false; however, parameter $topic of midcom_core_context::enter() does only seem to accept midcom_db_topic|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

210
        $context = midcom_core_context::enter($url, /** @scrutinizer ignore-type */ $oldcontext->get_key(MIDCOM_CONTEXT_ROOTTOPIC));
Loading history...
211
212 16
        $request = $this->request->duplicate([], null, []);
213 16
        $request->attributes->set('context', $context);
214
215 16
        $cached = $this->cache->content->check_dl_hit($request);
216 16
        if ($cached !== false) {
217
            echo $cached;
218
            midcom_core_context::leave();
219
            return;
220
        }
221
222 16
        $backup = $this->skip_page_style;
223 16
        $this->skip_page_style = true;
224
        try {
225 16
            $response = $this->handle($request, HttpKernelInterface::SUB_REQUEST, false);
226 12
        } catch (midcom_error $e) {
227 12
            if ($e instanceof midcom_error_notfound || $e instanceof midcom_error_forbidden) {
228 12
                $e->log();
229 12
                midcom_core_context::leave();
230 12
                return;
231
            }
232
            throw $e;
233 4
        } finally {
234 16
            $this->skip_page_style = $backup;
235
        }
236
237 4
        $dl_cache_data = $response->getContent();
238 4
        echo $dl_cache_data;
239
240
        /* Cache DL the content */
241 4
        $this->cache->content->store_dl_content($context->id, $dl_cache_data, $request);
242
243 4
        midcom_core_context::leave();
244 4
    }
245
246
    /**
247
     * Exit from the framework, execute after all output has been made.
248
     *
249
     * <b>WARNING:</b> Anything done after calling this method will be lost.
250
     */
251
    public function finish()
252
    {
253
        debug_add("End of MidCOM run: " . $this->request->server->get('REQUEST_URI'));
254
        _midcom_stop_request();
255
    }
256
257
    /* *************************************************************************
258
     * Framework Access Helper functions
259
     */
260
261
    /**
262
     * Retrieves the name of the current host, fully qualified with protocol and
263
     * port (http[s]://www.my.domain.com[:1234])
264
     */
265 37
    function get_host_name() : string
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
266
    {
267 37
        return $this->request->getSchemeAndHttpHost();
268
    }
269
270
    /**
271
     * Return the prefix required to build relative links on the current site.
272
     * This includes the http[s] prefix, the hosts port (if necessary) and the
273
     * base url of the Midgard Page. Be aware, that this does *not* point to the
274
     * base host of the site.
275
     *
276
     * e.g. something like http[s]://www.domain.com[:8080]/host_prefix/page_prefix/
277
     */
278
    function get_page_prefix() : string
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
279
    {
280
        if (!$this->_cached_page_prefix) {
281
            $host_name = $this->get_host_name();
282
            $this->_cached_page_prefix = $host_name . midcom_connection::get_url('self');
283
        }
284
285
        return $this->_cached_page_prefix;
286
    }
287
288
    /**
289
     * Return the prefix required to build relative links on the current site.
290
     * This includes the http[s] prefix, the hosts port (if necessary) and the
291
     * base url of the main host. This is not necessarily the currently active
292
     * MidCOM Page however, use the get_page_prefix() function for that.
293
     *
294
     * e.g. something like http[s]://www.domain.com[:8080]/host_prefix/
295
     */
296 7
    function get_host_prefix() : string
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
297
    {
298 7
        if (!$this->_cached_host_prefix) {
299 1
            $host_name = $this->get_host_name();
300 1
            $host_prefix = midcom_connection::get_url('prefix');
301 1
            if (substr($host_prefix, 0, 1) != '/') {
302
                $host_prefix = "/{$host_prefix}";
303
            }
304 1
            if (substr($host_prefix, -1, 1) != '/') {
305
                $host_prefix .= '/';
306
            }
307 1
            $this->_cached_host_prefix = "{$host_name}{$host_prefix}";
308
        }
309
310 7
        return $this->_cached_host_prefix;
311
    }
312
313
    /* *************************************************************************
314
     * Generic Helper Functions not directly related with MidCOM:
315
     *
316
     * relocate           - executes a HTTP relocation to the given URL
317
     */
318
319
    /**
320
     * Sends a header out to the client.
321
     *
322
     * This function is syntactically identical to
323
     * the regular PHP header() function, but is integrated into the framework. Every
324
     * Header you sent must go through this function or it might be lost later on;
325
     * this is especially important with caching.
326
     *
327
     * @param string $header    The header to send.
328
     * @param integer $response_code HTTP response code to send with the header
329
     */
330 17
    public function header($header, $response_code = null)
331
    {
332 17
        $this->cache->content->register_sent_header($header);
333 17
        midcom_compat_environment::get()->header($header, true, $response_code);
334 17
    }
335
336
    /**
337
     * Relocate to another URL.
338
     *
339
     * Note, that this function automatically makes the page uncacheable, calls
340
     * midcom_finish and exit, so it will never return. If the headers have already
341
     * been sent, this will leave you with a partially completed page, so beware.
342
     *
343
     * @param string $url    The URL to redirect to, will be preprocessed as outlined above.
344
     * @param int $response_code HTTP response code to send with the relocation, from 3xx series
345
     */
346
    public function relocate($url, $response_code = 302)
347
    {
348
        $response = new midcom_response_relocate($url, $response_code);
349
        $response->send();
350
        $this->finish();
351
    }
352
353
    /**
354
     * Raise some PHP limits for resource-intensive tasks
355
     */
356 8
    public function disable_limits()
357
    {
358 8
        $stat = @ini_set('max_execution_time', $this->config->get('midcom_max_execution_time'));
359 8
        if (false === $stat) {
360
            debug_add('ini_set("max_execution_time", ' . $this->config->get('midcom_max_execution_time') . ') returned false', MIDCOM_LOG_WARN);
361
        }
362 8
        $stat = @ini_set('memory_limit', $this->config->get('midcom_max_memory'));
363 8
        if (false === $stat) {
364
            debug_add('ini_set("memory_limit", ' . $this->config->get('midcom_max_memory') . ') returned false', MIDCOM_LOG_WARN);
365
        }
366 8
    }
367
}
368