Passed
Push — master ( 93f4bd...c6f863 )
by Andreas
22:51
created

midcom_application::getCacheDir()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 2
rs 10
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
15
/**
16
 * Main controlling instance of the MidCOM Framework
17
 *
18
 * @property midcom_services_i18n $i18n
19
 * @property midcom_helper__componentloader $componentloader
20
 * @property midcom_services_dbclassloader $dbclassloader
21
 * @property midcom_helper__dbfactory $dbfactory
22
 * @property midcom_helper_head $head
23
 * @property midcom_helper__styleloader $style
24
 * @property midcom_services_auth $auth
25
 * @property midcom_services_permalinks $permalinks
26
 * @property midcom_services_toolbars $toolbars
27
 * @property midcom_services_uimessages $uimessages
28
 * @property midcom_services_metadata $metadata
29
 * @property midcom_services_rcs $rcs
30
 * @property midcom_services__sessioning $session
31
 * @property midcom_services_indexer $indexer
32
 * @property midcom_config $config
33
 * @property midcom_services_cache $cache
34
 * @property midcom\events\dispatcher $dispatcher
35
 * @property midcom_debug $debug
36
 * @package midcom
37
 */
38
class midcom_application extends Kernel
39
{
40
    /**
41
     * Host prefix cache to avoid computing it each time.
42
     *
43
     * @var string
44
     * @see get_host_prefix()
45
     */
46
    private $_cached_host_prefix = '';
47
48
    /**
49
     * Page prefix cache to avoid computing it each time.
50
     *
51
     * @var string
52
     * @see get_page_prefix()
53
     */
54
    private $_cached_page_prefix = '';
55
56
    /**
57
     * @var Request
58
     */
59
    private $request;
60
61
    /**
62
     * Set this variable to true during the handle phase of your component to
63
     * not show the site's style around the component output. This is mainly
64
     * targeted at XML output like RSS feeds and similar things. The output
65
     * handler of the site, excluding the style-init/-finish tags will be executed
66
     * immediately after the handle phase
67
     *
68
     * Changing this flag after the handle phase or for dynamically loaded
69
     * components won't change anything.
70
     *
71
     * @var boolean
72
     */
73
    public $skip_page_style = false;
74
75
    private $project_dir;
76
77
    /**
78
     * @var midcom_config
79
     */
80
    private $cfg;
81
82
    public function __construct(string $environment, bool $debug)
83
    {
84
        midcom_compat_environment::initialize();
85
        $this->request = Request::createFromGlobals();
86
        $this->cfg = new midcom_config;
87
        parent::__construct($environment, $debug);
88
    }
89
90
    public function registerContainerConfiguration(LoaderInterface $loader)
91
    {
92
        $loader->load(__DIR__ . '/config/services.yml');
93
        if ($classes = midcom::get_registered_service_classes()) {
94
            $loader->load(function (ContainerBuilder $container) use ($classes) {
95
                foreach ($classes as $id => $class) {
96
                    $container->findDefinition($id)->setClass($class);
97
                }
98
            });
99
        }
100
        midcom_exception_handler::register();
101
    }
102
103
    protected function initializeContainer()
104
    {
105
        parent::initializeContainer();
106
        $this->container->set('config', $this->cfg);
107
    }
108
109
    public function registerBundles()
110
    {
111
        return [];
112
    }
113
114
    public function getProjectDir()
115
    {
116
        if ($this->project_dir === null) {
117
            if (basename(dirname(__DIR__, 4)) === 'vendor') {
118
                // this is the case where we're installed as a dependency
119
                $this->project_dir = dirname(__DIR__, 5);
120
            } else {
121
                $this->project_dir = dirname(__DIR__, 2);
122
            }
123
        }
124
        return $this->project_dir;
125
    }
126
127 325
    public function getCacheDir()
128
    {
129 325
        return $this->cfg->get('cache_base_directory') ?: parent::getCacheDir();
130
    }
131
132
    /**
133
     * Magic getter for service loading
134
     */
135 737
    public function __get($key)
136
    {
137 737
        return $this->getContainer()->get($key);
138
    }
139
140
    /**
141
     * Magic setter
142
     */
143
    public function __set($key, $value)
144
    {
145
        $this->getContainer()->set($key, $value);
146
    }
147
148
    /* *************************************************************************
149
     * Control framework:
150
     * codeinit      - Handle the current request
151
     * dynamic_load   - Dynamically load and execute a URL
152
     * finish         - Cleanup Work
153
     */
154
155
    /**
156
     * Initialize the URL parser and process the request.
157
     *
158
     * This function must be called before any output starts.
159
     */
160
    public function codeinit()
161
    {
162
        $this->handle($this->request)->send();
163
    }
164
165
    /**
166
     * Dynamically execute a subrequest and insert its output in place of the
167
     * function call.
168
     *
169
     * It tries to load the component referenced with the URL $url and executes
170
     * it as if it was used as primary component.
171
     *
172
     * This is only possible if the system is in the Page-Style output phase. It
173
     * cannot be used within code-init or during the output phase of another
174
     * component.
175
     *
176
     * Example code, executed on a site's homepage, it will load the news listing from
177
     * the given URL and display it using a substyle of the node style that is assigned
178
     * to the loaded one:
179
     *
180
     * <code>
181
     * $blog = '/blog/latest/3/';
182
     * $substyle = 'homepage';
183
     * midcom::get()->dynamic_load("/midcom-substyle-{$substyle}/{$blog}");
184
     * </code>
185
     *
186
     * Results of dynamic_loads are cached with the system cache strategy
187
     *
188
     * @param string $url                The URL, relative to the Midgard Page, that is to be requested.
189
     */
190 16
    public function dynamic_load($url)
191
    {
192 16
        debug_add("Dynamic load of URL {$url}");
193 16
        $url = midcom_connection::get_url('prefix') . $url;
194
195
        // Determine new Context ID and set current context,
196
        // enter that context and prepare its data structure.
197 16
        $oldcontext = midcom_core_context::get();
198 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

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