Completed
Push — master ( 8cd050...5f288c )
by Andreas
22:58
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\bundle\midcomBundle;
15
16
/**
17
 * Main controlling instance of the MidCOM Framework
18
 *
19
 * @property midcom_services_i18n $i18n
20
 * @property midcom_helper__componentloader $componentloader
21
 * @property midcom_services_dbclassloader $dbclassloader
22
 * @property midcom_helper__dbfactory $dbfactory
23
 * @property midcom_helper_head $head
24
 * @property midcom_helper__styleloader $style
25
 * @property midcom_services_auth $auth
26
 * @property midcom_services_permalinks $permalinks
27
 * @property midcom_services_toolbars $toolbars
28
 * @property midcom_services_uimessages $uimessages
29
 * @property midcom_services_metadata $metadata
30
 * @property midcom_services_rcs $rcs
31
 * @property midcom_services__sessioning $session
32
 * @property midcom_services_indexer $indexer
33
 * @property midcom_config $config
34
 * @property midcom_services_cache $cache
35
 * @property Symfony\Component\EventDispatcher\EventDispatcher $dispatcher
36
 * @property midcom_debug $debug
37
 * @package midcom
38
 */
39
class midcom_application extends Kernel
40
{
41
    /**
42
     * Host prefix cache to avoid computing it each time.
43
     *
44
     * @var string
45
     * @see get_host_prefix()
46
     */
47
    private $_cached_host_prefix = '';
48
49
    /**
50
     * Page prefix cache to avoid computing it each time.
51
     *
52
     * @var string
53
     * @see get_page_prefix()
54
     */
55
    private $_cached_page_prefix = '';
56
57
    /**
58
     * @var Request
59
     */
60
    private $request;
61
62
    /**
63
     * Set this variable to true during the handle phase of your component to
64
     * not show the site's style around the component output. This is mainly
65
     * targeted at XML output like RSS feeds and similar things. The output
66
     * handler of the site, excluding the style-init/-finish tags will be executed
67
     * immediately after the handle phase
68
     *
69
     * Changing this flag after the handle phase or for dynamically loaded
70
     * components won't change anything.
71
     *
72
     * @var boolean
73
     */
74
    public $skip_page_style = false;
75
76
    private $project_dir;
77
78
    /**
79
     * @var midcom_config
80
     */
81
    private $cfg;
82
83
    public function __construct(string $environment, bool $debug)
84
    {
85
        midcom_compat_environment::initialize();
86
        $this->request = Request::createFromGlobals();
87
        $this->cfg = new midcom_config;
88
        parent::__construct($environment, $debug);
89
    }
90
91
    public function registerContainerConfiguration(LoaderInterface $loader)
92
    {
93
        if (file_exists($this->getProjectDir() . '/config/services.yml')) {
94
            $loader->load($this->getProjectDir() . '/config/services.yml');
95
        }
96
        if ($classes = midcom::get_registered_service_classes()) {
97
            $loader->load(function (ContainerBuilder $container) use ($classes) {
98
                foreach ($classes as $id => $class) {
99
                    $container->findDefinition($id)->setClass($class);
100
                }
101
            });
102
        }
103
    }
104
105
    protected function initializeContainer()
106
    {
107
        parent::initializeContainer();
108
        $this->container->set('config', $this->cfg);
109
    }
110
111
    public function registerBundles()
112
    {
113
        return [new midcomBundle($this->cfg)];
114
    }
115
116
    public function getProjectDir()
117
    {
118
        if ($this->project_dir === null) {
119
            if (basename(dirname(__DIR__, 4)) === 'vendor') {
120
                // this is the case where we're installed as a dependency
121
                $this->project_dir = dirname(__DIR__, 5);
122
            } else {
123
                $this->project_dir = dirname(__DIR__, 2);
124
            }
125
        }
126
        return $this->project_dir;
127
    }
128
129 324
    public function getCacheDir()
130
    {
131 324
        return $this->cfg->get('cache_base_directory') ?: parent::getCacheDir();
132
    }
133
134
    /**
135
     * Magic getter for service loading
136
     */
137 679
    public function __get($key)
138
    {
139 679
        return $this->getContainer()->get($key);
140
    }
141
142
    /**
143
     * Magic setter
144
     */
145
    public function __set($key, $value)
146
    {
147
        $this->getContainer()->set($key, $value);
148
    }
149
150
    /* *************************************************************************
151
     * Control framework:
152
     * codeinit      - Handle the current request
153
     * dynamic_load   - Dynamically load and execute a URL
154
     * finish         - Cleanup Work
155
     */
156
157
    /**
158
     * Initialize the URL parser and process the request.
159
     *
160
     * This function must be called before any output starts.
161
     */
162
    public function codeinit()
163
    {
164
        try {
165
            $this->handle($this->request)->send();
166
        } catch (Error $e) {
167
            $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

167
            $this->getHttpKernel()->/** @scrutinizer ignore-call */ terminateWithException($e);
Loading history...
168
        }
169
    }
170
171
    /**
172
     * Dynamically execute a subrequest and insert its output in place of the
173
     * function call.
174
     *
175
     * It tries to load the component referenced with the URL $url and executes
176
     * it as if it was used as primary component.
177
     *
178
     * This is only possible if the system is in the Page-Style output phase. It
179
     * cannot be used within code-init or during the output phase of another
180
     * component.
181
     *
182
     * Example code, executed on a site's homepage, it will load the news listing from
183
     * the given URL and display it using a substyle of the node style that is assigned
184
     * to the loaded one:
185
     *
186
     * <code>
187
     * $blog = '/blog/latest/3/';
188
     * $substyle = 'homepage';
189
     * midcom::get()->dynamic_load("/midcom-substyle-{$substyle}/{$blog}");
190
     * </code>
191
     *
192
     * Results of dynamic_loads are cached with the system cache strategy
193
     *
194
     * @param string $url                The URL, relative to the Midgard Page, that is to be requested.
195
     */
196 16
    public function dynamic_load(string $url, string $substyle = '')
197
    {
198 16
        debug_add("Dynamic load of URL {$url}");
199 16
        $url = midcom_connection::get_url('prefix') . $url;
200
201
        // Determine new Context ID and set current context,
202
        // enter that context and prepare its data structure.
203 16
        $oldcontext = midcom_core_context::get();
204 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

204
        $context = midcom_core_context::enter($url, /** @scrutinizer ignore-type */ $oldcontext->get_key(MIDCOM_CONTEXT_ROOTTOPIC));
Loading history...
205 16
        if ($substyle) {
206
            $context->set_key(MIDCOM_CONTEXT_SUBSTYLE, $substyle);
207
        }
208
209 16
        $request = $this->request->duplicate([], null, []);
210 16
        $request->attributes->set('context', $context);
211
212 16
        $cached = $this->cache->content->check_dl_hit($request);
213 16
        if ($cached !== false) {
214
            echo $cached;
215
            midcom_core_context::leave();
216
            return;
217
        }
218
219 16
        $backup = $this->skip_page_style;
220 16
        $this->skip_page_style = true;
221
        try {
222 16
            $response = $this->handle($request, HttpKernelInterface::SUB_REQUEST, false);
223 12
        } catch (midcom_error $e) {
224 12
            if ($e instanceof midcom_error_notfound || $e instanceof midcom_error_forbidden) {
225 12
                $e->log();
226 12
                midcom_core_context::leave();
227 12
                return;
228
            }
229
            throw $e;
230 4
        } finally {
231 16
            $this->skip_page_style = $backup;
232
        }
233
234 4
        $dl_cache_data = $response->getContent();
235 4
        echo $dl_cache_data;
236
237
        /* Cache DL the content */
238 4
        $this->cache->content->store_dl_content($context->id, $dl_cache_data, $request);
239
240 4
        midcom_core_context::leave();
241 4
    }
242
243
    /**
244
     * Exit from the framework, execute after all output has been made.
245
     *
246
     * <b>WARNING:</b> Anything done after calling this method will be lost.
247
     */
248
    public function finish()
249
    {
250
        debug_add("End of MidCOM run: " . $this->request->server->get('REQUEST_URI'));
251
        _midcom_stop_request();
252
    }
253
254
    /* *************************************************************************
255
     * Framework Access Helper functions
256
     */
257
258
    /**
259
     * Retrieves the name of the current host, fully qualified with protocol and
260
     * port (http[s]://www.my.domain.com[:1234])
261
     */
262 23
    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...
263
    {
264 23
        return $this->request->getSchemeAndHttpHost();
265
    }
266
267
    /**
268
     * Return the prefix required to build relative links on the current site.
269
     * This includes the http[s] prefix, the hosts port (if necessary) and the
270
     * base url of the Midgard Page. Be aware, that this does *not* point to the
271
     * base host of the site.
272
     *
273
     * e.g. something like http[s]://www.domain.com[:8080]/host_prefix/page_prefix/
274
     */
275
    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...
276
    {
277
        if (!$this->_cached_page_prefix) {
278
            $host_name = $this->get_host_name();
279
            $this->_cached_page_prefix = $host_name . midcom_connection::get_url('self');
280
        }
281
282
        return $this->_cached_page_prefix;
283
    }
284
285
    /**
286
     * Return the prefix required to build relative links on the current site.
287
     * This includes the http[s] prefix, the hosts port (if necessary) and the
288
     * base url of the main host. This is not necessarily the currently active
289
     * MidCOM Page however, use the get_page_prefix() function for that.
290
     *
291
     * e.g. something like http[s]://www.domain.com[:8080]/host_prefix/
292
     */
293 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...
294
    {
295 7
        if (!$this->_cached_host_prefix) {
296 1
            $host_name = $this->get_host_name();
297 1
            $host_prefix = midcom_connection::get_url('prefix');
298 1
            if (substr($host_prefix, 0, 1) != '/') {
299
                $host_prefix = "/{$host_prefix}";
300
            }
301 1
            if (substr($host_prefix, -1, 1) != '/') {
302
                $host_prefix .= '/';
303
            }
304 1
            $this->_cached_host_prefix = "{$host_name}{$host_prefix}";
305
        }
306
307 7
        return $this->_cached_host_prefix;
308
    }
309
310
    /* *************************************************************************
311
     * Generic Helper Functions not directly related with MidCOM:
312
     *
313
     * relocate           - executes a HTTP relocation to the given URL
314
     */
315
316
    /**
317
     * Sends a header out to the client.
318
     *
319
     * This function is syntactically identical to
320
     * the regular PHP header() function, but is integrated into the framework. Every
321
     * Header you sent must go through this function or it might be lost later on;
322
     * this is especially important with caching.
323
     *
324
     * @param string $header    The header to send.
325
     * @param integer $response_code HTTP response code to send with the header
326
     */
327 17
    public function header($header, $response_code = null)
328
    {
329 17
        $this->cache->content->register_sent_header($header);
330 17
        midcom_compat_environment::get()->header($header, true, $response_code);
331 17
    }
332
333
    /**
334
     * Relocate to another URL.
335
     *
336
     * Note, that this function automatically makes the page uncacheable, calls
337
     * midcom_finish and exit, so it will never return. If the headers have already
338
     * been sent, this will leave you with a partially completed page, so beware.
339
     *
340
     * @param string $url    The URL to redirect to, will be preprocessed as outlined above.
341
     * @param int $response_code HTTP response code to send with the relocation, from 3xx series
342
     */
343
    public function relocate($url, $response_code = 302)
344
    {
345
        $response = new midcom_response_relocate($url, $response_code);
346
        $response->send();
347
        $this->finish();
348
    }
349
350
    /**
351
     * Raise some PHP limits for resource-intensive tasks
352
     */
353 8
    public function disable_limits()
354
    {
355 8
        $stat = @ini_set('max_execution_time', $this->config->get('midcom_max_execution_time'));
356 8
        if (false === $stat) {
357
            debug_add('ini_set("max_execution_time", ' . $this->config->get('midcom_max_execution_time') . ') returned false', MIDCOM_LOG_WARN);
358
        }
359 8
        $stat = @ini_set('memory_limit', $this->config->get('midcom_max_memory'));
360 8
        if (false === $stat) {
361
            debug_add('ini_set("memory_limit", ' . $this->config->get('midcom_max_memory') . ') returned false', MIDCOM_LOG_WARN);
362
        }
363 8
    }
364
}
365