Welcome to mirror list, hosted at ThFree Co, Russian Federation.

FrontController.php « core - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: cda6d1dae2400415413ef8b8adf6332949f8263a (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
<?php
/**
 * Piwik - Open source web analytics
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 * @category Piwik
 * @package Piwik
 */
use Piwik\Config;
use Piwik\Piwik;
use Piwik\Common;
use Piwik\Access;
use Piwik\PluginsManager;

/**
 * @see core/PluginsManager.php
 * @see core/Translate.php
 * @see core/Option.php
 */
require_once PIWIK_INCLUDE_PATH . '/core/PluginsManager.php';
require_once PIWIK_INCLUDE_PATH . '/core/Translate.php';
require_once PIWIK_INCLUDE_PATH . '/core/Option.php';

/**
 * Front controller.
 * This is the class hit in the first place.
 * It dispatches the request to the right controller.
 *
 * For a detailed explanation, see the documentation on http://piwik.org/docs/plugins/framework-overview
 *
 * @package Piwik
 * @subpackage Piwik_FrontController
 */
class Piwik_FrontController
{
    /**
     * Set to false and the Front Controller will not dispatch the request
     *
     * @var bool
     */
    public static $enableDispatch = true;

    private static $instance = null;

    /**
     * returns singleton
     *
     * @return Piwik_FrontController
     */
    public static function getInstance()
    {
        if (self::$instance == null) {
            self::$instance = new self;
        }
        return self::$instance;
    }

    /**
     * Dispatches the request to the right plugin and executes the requested action on the plugin controller.
     *
     * @throws Exception|Piwik_FrontController_PluginDeactivatedException in case the plugin doesn't exist, the action doesn't exist, there is not enough permission, etc.
     *
     * @param string $module
     * @param string $action
     * @param array $parameters
     * @return mixed The returned value of the calls, often nothing as the module print but don't return data
     * @see fetchDispatch()
     */
    public function dispatch($module = null, $action = null, $parameters = null)
    {
        if (self::$enableDispatch === false) {
            return;
        }

        if (is_null($module)) {
            $defaultModule = 'CoreHome';
            $module = Common::getRequestVar('module', $defaultModule, 'string');
        }

        if (is_null($action)) {
            $action = Common::getRequestVar('action', false);
        }

        if (!Piwik_Session::isFileBasedSessions()
            && ($module !== 'API' || ($action && $action !== 'index'))
        ) {
            Piwik_Session::start();
        }

        if (is_null($parameters)) {
            $parameters = array();
        }

        if (!ctype_alnum($module)) {
            throw new Exception("Invalid module name '$module'");
        }

        if (!PluginsManager::getInstance()->isPluginActivated($module)) {
            throw new Piwik_FrontController_PluginDeactivatedException($module);
        }

        $controllerClassName = 'Piwik_' . $module . '_Controller';

        // FrontController's autoloader
        if (!class_exists($controllerClassName, false)) {
            $moduleController = PIWIK_INCLUDE_PATH . '/plugins/' . $module . '/Controller.php';
            if (!is_readable($moduleController)) {
                throw new Exception("Module controller $moduleController not found!");
            }
            require_once $moduleController; // prefixed by PIWIK_INCLUDE_PATH
        }

        $controller = new $controllerClassName();
        if ($action === false) {
            $action = $controller->getDefaultAction();
        }

        if (!is_callable(array($controller, $action))) {
            throw new Exception("Action '$action' not found in the controller '$controllerClassName'.");
        }

        // Generic hook that plugins can use to modify any input to the function,
        // or even change the plugin being called
        $params = array($controller, $action, $parameters);
        Piwik_PostEvent('FrontController.dispatch', $params);

        try {
            return call_user_func_array(array($params[0], $params[1]), $params[2]);
        } catch (Access_NoAccessException $e) {
            Piwik_PostEvent('FrontController.NoAccessException', array($e), $pending = true);
        } catch (Exception $e) {
            $debugTrace = $e->getTraceAsString();
            $message = Common::sanitizeInputValue($e->getMessage());
            Piwik_ExitWithMessage($message, '' /* $debugTrace */, true);
        }
    }

    /**
     * Often plugins controller display stuff using echo/print.
     * Using this function instead of dispatch() returns the output string form the actions calls.
     *
     * @param string $controllerName
     * @param string $actionName
     * @param array $parameters
     * @return string
     */
    public function fetchDispatch($controllerName = null, $actionName = null, $parameters = null)
    {
        ob_start();
        $output = $this->dispatch($controllerName, $actionName, $parameters);
        // if nothing returned we try to load something that was printed on the screen
        if (empty($output)) {
            $output = ob_get_contents();
        }
        ob_end_clean();
        return $output;
    }

    /**
     * Called at the end of the page generation
     *
     */
    public function __destruct()
    {
        try {
            Piwik::printSqlProfilingReportZend();
            Piwik::printQueryCount();
            Piwik::printTimer();
        } catch (Exception $e) {
        }
    }

    // Should we show exceptions messages directly rather than display an html error page?
    public static function shouldRethrowException()
    {
        // If we are in no dispatch mode, eg. a script reusing Piwik libs,
        // then we should return the exception directly, rather than trigger the event "bad config file"
        // which load the HTML page of the installer with the error.
        // This is at least required for misc/cron/archive.php and useful to all other scripts
        return (defined('PIWIK_ENABLE_DISPATCH') && !PIWIK_ENABLE_DISPATCH)
            || Common::isPhpCliMode()
            || Common::isArchivePhpTriggered();
    }

    /**
     * Loads the config file and assign to the global registry
     * This is overridden in tests to ensure test config file is used
     *
     * @return Exception
     */
    protected function createConfigObject()
    {
        $exceptionToThrow = false;
        try {
            Config::getInstance();
        } catch (Exception $e) {
            Piwik_PostEvent('FrontController.NoConfigurationFile', array($e), $pending = true);
            $exceptionToThrow = $e;
        }
        return $exceptionToThrow;
    }

    /**
     * Must be called before dispatch()
     * - checks that directories are writable,
     * - loads the configuration file,
     * - loads the plugin,
     * - inits the DB connection,
     * - etc.
     *
     * @throws Exception
     * @return void
     */
    public function init()
    {
        static $initialized = false;
        if ($initialized) {
            return;
        }
        $initialized = true;


        try {
            Zend_Registry::set('timer', new Piwik_Timer);

            $directoriesToCheck = array(
                '/tmp/',
                '/tmp/templates_c/',
                '/tmp/cache/',
                '/tmp/assets/',
                '/tmp/tcpdf/'
            );

            Piwik::dieIfDirectoriesNotWritable($directoriesToCheck);
            Common::assignCliParametersToRequest();

            Piwik_Translate::getInstance()->loadEnglishTranslation();

            $exceptionToThrow = $this->createConfigObject();

            if (Piwik_Session::isFileBasedSessions()) {
                Piwik_Session::start();
            }

            $this->handleMaintenanceMode();
            $this->handleSSLRedirection();

            $pluginsManager = PluginsManager::getInstance();
            $pluginsToLoad = Config::getInstance()->Plugins['Plugins'];

            $pluginsManager->loadPlugins($pluginsToLoad);

            if ($exceptionToThrow) {
                throw $exceptionToThrow;
            }


            try {
                Piwik::createDatabaseObject();
            } catch (Exception $e) {
                if (self::shouldRethrowException()) {
                    throw $e;
                }
                Piwik_PostEvent('FrontController.badConfigurationFile', array($e), $pending = true);
                throw $e;
            }

            Piwik::createLogObject();

            // Init the Access object, so that eg. core/Updates/* can enforce Super User and use some APIs
            Access::getInstance();

            Piwik_PostEvent('FrontController.dispatchCoreAndPluginUpdatesScreen');

            PluginsManager::getInstance()->installLoadedPlugins();

            // ensure the current Piwik URL is known for later use
            if (method_exists('Piwik\Piwik', 'getPiwikUrl')) {
                $host = Piwik::getPiwikUrl();
            }

            Piwik_PostEvent('FrontController.initAuthenticationObject');
            try {
                $authAdapter = Zend_Registry::get('auth');
            } catch (Exception $e) {
                throw new Exception("Authentication object cannot be found in the Registry. Maybe the Login plugin is not activated?
									<br />You can activate the plugin by adding:<br />
									<code>Plugins[] = Login</code><br />
									under the <code>[Plugins]</code> section in your config/config.ini.php");
            }
            Access::getInstance()->reloadAccess($authAdapter);

            // Force the auth to use the token_auth if specified, so that embed dashboard
            // and all other non widgetized controller methods works fine
            if (($token_auth = Common::getRequestVar('token_auth', false, 'string')) !== false) {
                Piwik_API_Request::reloadAuthUsingTokenAuth();
            }
            Piwik::raiseMemoryLimitIfNecessary();

            Piwik_Translate::getInstance()->reloadLanguage();
            $pluginsManager->postLoadPlugins();

            Piwik_PostEvent('FrontController.checkForUpdates');
        } catch (Exception $e) {

            if (self::shouldRethrowException()) {
                throw $e;
            }

            $trace = $e->getTraceAsString();
            Piwik_ExitWithMessage($e->getMessage(), false /* $debugTrace */, true);
        }
    }

    protected function handleMaintenanceMode()
    {
        if (Config::getInstance()->General['maintenance_mode'] == 1
            && !Common::isPhpCliMode()
        ) {
            $format = Common::getRequestVar('format', '');

            $message = "Piwik is in scheduled maintenance. Please come back later."
                . " The administrator can disable maintenance by editing the file piwik/config/config.ini.php and removing the following: "
                . " maintenance_mode=1 ";
            if (Config::getInstance()->Tracker['record_statistics'] == 0) {
                $message .= ' and record_statistics=0';
            }

            $exception = new Exception($message);
            // extend explain how to re-enable
            // show error message when record stats = 0
            if (empty($format)) {
                throw $exception;
            }
            $response = new Piwik_API_ResponseBuilder($format);
            echo $response->getResponseException($exception);
            exit;
        }
    }

    protected function handleSSLRedirection()
    {
        if (!Common::isPhpCliMode()
            && Config::getInstance()->General['force_ssl'] == 1
            && !Piwik::isHttps()
            // Specifically disable for the opt out iframe
            && !(Common::getRequestVar('module', '') == 'CoreAdminHome'
                && Common::getRequestVar('action', '') == 'optOut')
        ) {
            $url = Piwik_Url::getCurrentUrl();
            $url = str_replace("http://", "https://", $url);
            Piwik_Url::redirectToUrl($url);
        }
    }
}

/**
 * Exception thrown when the requested plugin is not activated in the config file
 *
 * @package Piwik
 * @subpackage Piwik_FrontController
 */
class Piwik_FrontController_PluginDeactivatedException extends Exception
{
    public function __construct($module)
    {
        parent::__construct("The plugin $module is not enabled. You can activate the plugin on Settings > Plugins page in Piwik.");
    }
}