PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / 5.0.3
Matomo Analytics – Powerful, Privacy-First Insights for WordPress v5.0.3
5.12.1 5.12.0 5.11.1 5.11.0 5.10.2 5.10.1 trunk 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.1.0 1.1.1 1.1.2 1.1.3 1.2.0 1.3.0 1.3.1 1.3.2 4.0.0 4.0.1 4.0.2 4.0.3 4.0.4 4.1.0 4.1.1 4.1.2 4.1.3 4.10.0 4.11.0 4.12.0 4.13.0 4.13.2 4.13.3 4.13.4 4.13.5 4.14.0 4.14.1 4.14.2 4.15.0 4.15.1 4.15.2 4.15.3 4.2.0 4.3.0 4.3.1 4.4.1 4.4.2 4.5.0 4.6.0 5.0.1 5.0.2 5.0.3 5.0.4 5.0.5 5.0.6 5.0.7 5.0.8 5.1.0 5.1.1 5.1.2 5.1.3 5.1.4 5.1.5 5.1.6 5.1.7 5.10.0 5.2.0 5.2.1 5.2.2 5.3.0 5.3.1 5.3.2 5.3.3 5.6.0 5.6.1 5.7.0 5.7.1 5.8.0 5.8.1 5.8.2
matomo / app / core / SettingsPiwik.php
matomo / app / core Last commit date
API 2 years ago Access 2 years ago Application 2 years ago Archive 2 years ago ArchiveProcessor 2 years ago Archiver 2 years ago AssetManager 2 years ago Auth 2 years ago Category 2 years ago Changes 2 years ago CliMulti 2 years ago Columns 2 years ago Concurrency 2 years ago Config 2 years ago Container 2 years ago CronArchive 2 years ago DataAccess 2 years ago DataFiles 2 years ago DataTable 2 years ago Db 2 years ago DeviceDetector 2 years ago Email 2 years ago Exception 2 years ago Http 2 years ago Intl 2 years ago Log 2 years ago Mail 2 years ago Measurable 2 years ago Menu 2 years ago Metrics 2 years ago Notification 2 years ago Period 2 years ago Plugin 2 years ago ProfessionalServices 2 years ago Report 2 years ago ReportRenderer 2 years ago Scheduler 2 years ago Segment 2 years ago Session 2 years ago Settings 2 years ago Tracker 2 years ago Translation 2 years ago Twig 2 years ago UpdateCheck 2 years ago Updater 2 years ago Updates 2 years ago Validators 2 years ago View 2 years ago ViewDataTable 2 years ago Visualization 2 years ago Widget 2 years ago .htaccess 2 years ago Access.php 2 years ago Archive.php 2 years ago ArchiveProcessor.php 2 years ago AssetManager.php 2 years ago Auth.php 2 years ago AuthResult.php 2 years ago BaseFactory.php 2 years ago Cache.php 2 years ago CacheId.php 2 years ago CliMulti.php 2 years ago Common.php 2 years ago Config.php 2 years ago Console.php 2 years ago Context.php 2 years ago Cookie.php 2 years ago CronArchive.php 2 years ago DI.php 2 years ago DataArray.php 2 years ago DataTable.php 2 years ago Date.php 2 years ago Db.php 2 years ago DbHelper.php 2 years ago Development.php 2 years ago ErrorHandler.php 2 years ago EventDispatcher.php 2 years ago ExceptionHandler.php 2 years ago FileIntegrity.php 2 years ago Filechecks.php 2 years ago Filesystem.php 2 years ago FrontController.php 2 years ago Http.php 2 years ago IP.php 2 years ago Log.php 2 years ago LogDeleter.php 2 years ago Mail.php 2 years ago Metrics.php 2 years ago NoAccessException.php 2 years ago Nonce.php 2 years ago Notification.php 2 years ago NumberFormatter.php 2 years ago Option.php 2 years ago Period.php 2 years ago Piwik.php 2 years ago Plugin.php 2 years ago Profiler.php 2 years ago ProxyHeaders.php 2 years ago ProxyHttp.php 2 years ago QuickForm2.php 2 years ago RankingQuery.php 2 years ago ReportRenderer.php 2 years ago Request.php 2 years ago Segment.php 2 years ago Sequence.php 2 years ago Session.php 2 years ago SettingsPiwik.php 2 years ago SettingsServer.php 2 years ago Singleton.php 2 years ago Site.php 2 years ago SiteContentDetector.php 2 years ago SupportedBrowser.php 2 years ago TCPDF.php 2 years ago Theme.php 2 years ago Timer.php 2 years ago Tracker.php 2 years ago Twig.php 2 years ago Unzip.php 2 years ago UpdateCheck.php 2 years ago Updater.php 2 years ago UpdaterErrorException.php 2 years ago Updates.php 2 years ago Url.php 2 years ago UrlHelper.php 2 years ago Version.php 2 years ago View.php 2 years ago bootstrap.php 2 years ago dispatch.php 2 years ago testMinimumPhpVersion.php 2 years ago
SettingsPiwik.php
436 lines
1 <?php
2
3 /**
4 * Matomo - free/libre analytics platform
5 *
6 * @link https://matomo.org
7 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
8 *
9 */
10 namespace Piwik;
11
12 use Exception;
13 use Piwik\Cache as PiwikCache;
14 use Piwik\Config\GeneralConfig;
15 use Piwik\Container\StaticContainer;
16 /**
17 * Contains helper methods that can be used to get common Piwik settings.
18 *
19 */
20 class SettingsPiwik
21 {
22 public const OPTION_PIWIK_URL = 'piwikUrl';
23 /**
24 * Get salt from [General] section. Should ONLY be used as a seed to create hashes
25 *
26 * NOTE: Keep this salt secret! Never output anywhere or share it etc.
27 *
28 * @return string|null
29 */
30 public static function getSalt() : ?string
31 {
32 static $salt = null;
33 if (is_null($salt)) {
34 $salt = \Piwik\Config::getInstance()->General['salt'] ?? '';
35 }
36 return $salt;
37 }
38 /**
39 * Should Piwik check that the login & password have minimum length and valid characters?
40 *
41 * @return bool True if checks enabled; false otherwise
42 */
43 public static function isUserCredentialsSanityCheckEnabled() : bool
44 {
45 return \Piwik\Config::getInstance()->General['disable_checks_usernames_attributes'] == 0;
46 }
47 /**
48 * Should Piwik show the update notification to superusers only?
49 *
50 * @return bool True if show to superusers only; false otherwise
51 */
52 public static function isShowUpdateNotificationToSuperUsersOnlyEnabled() : bool
53 {
54 return \Piwik\Config::getInstance()->General['show_update_notification_to_superusers_only'] == 1;
55 }
56 /**
57 * Returns every stored segment to pre-process for each site during cron archiving.
58 *
59 * @return array The list of stored segments that apply to all sites.
60 */
61 public static function getKnownSegmentsToArchive() : array
62 {
63 $cacheId = 'KnownSegmentsToArchive';
64 $cache = PiwikCache::getTransientCache();
65 if ($cache->contains($cacheId)) {
66 return $cache->fetch($cacheId);
67 }
68 $segments = \Piwik\Config::getInstance()->Segments;
69 $segmentsToProcess = isset($segments['Segments']) ? $segments['Segments'] : array();
70 /**
71 * Triggered during the cron archiving process to collect segments that
72 * should be pre-processed for all websites. The archiving process will be launched
73 * for each of these segments when archiving data.
74 *
75 * This event can be used to add segments to be pre-processed. If your plugin depends
76 * on data from a specific segment, this event could be used to provide enhanced
77 * performance.
78 *
79 * _Note: If you just want to add a segment that is managed by the user, use the
80 * SegmentEditor API._
81 *
82 * **Example**
83 *
84 * Piwik::addAction('Segments.getKnownSegmentsToArchiveAllSites', function (&$segments) {
85 * $segments[] = 'country=jp;city=Tokyo';
86 * });
87 *
88 * @param array &$segmentsToProcess List of segment definitions, eg,
89 *
90 * array(
91 * 'browserCode=ff;resolution=800x600',
92 * 'country=jp;city=Tokyo'
93 * )
94 *
95 * Add segments to this array in your event handler.
96 */
97 \Piwik\Piwik::postEvent('Segments.getKnownSegmentsToArchiveAllSites', array(&$segmentsToProcess));
98 $segmentsToProcess = array_unique($segmentsToProcess);
99 $cache->save($cacheId, $segmentsToProcess);
100 return $segmentsToProcess;
101 }
102 /**
103 * Returns the list of stored segments to pre-process for an individual site when executing
104 * cron archiving.
105 *
106 * @param int $idSite The ID of the site to get stored segments for.
107 * @return string[] The list of stored segments that apply to the requested site.
108 */
109 public static function getKnownSegmentsToArchiveForSite($idSite) : array
110 {
111 $cacheId = 'KnownSegmentsToArchiveForSite' . $idSite;
112 $cache = PiwikCache::getTransientCache();
113 if ($cache->contains($cacheId)) {
114 return $cache->fetch($cacheId);
115 }
116 $segments = array();
117 /**
118 * Triggered during the cron archiving process to collect segments that
119 * should be pre-processed for one specific site. The archiving process will be launched
120 * for each of these segments when archiving data for that one site.
121 *
122 * This event can be used to add segments to be pre-processed for one site.
123 *
124 * _Note: If you just want to add a segment that is managed by the user, you should use the
125 * SegmentEditor API._
126 *
127 * **Example**
128 *
129 * Piwik::addAction('Segments.getKnownSegmentsToArchiveForSite', function (&$segments, $idSite) {
130 * $segments[] = 'country=jp;city=Tokyo';
131 * });
132 *
133 * @param array &$segmentsToProcess List of segment definitions, eg,
134 *
135 * array(
136 * 'browserCode=ff;resolution=800x600',
137 * 'country=JP;city=Tokyo'
138 * )
139 *
140 * Add segments to this array in your event handler.
141 * @param int $idSite The ID of the site to get segments for.
142 */
143 \Piwik\Piwik::postEvent('Segments.getKnownSegmentsToArchiveForSite', array(&$segments, $idSite));
144 $segments = array_unique($segments);
145 $cache->save($cacheId, $segments);
146 return $segments;
147 }
148 /**
149 * Number of websites to show in the Website selector
150 *
151 * @return int
152 */
153 public static function getWebsitesCountToDisplay() : int
154 {
155 $count = max(\Piwik\Config::getInstance()->General['site_selector_max_sites'], \Piwik\Config::getInstance()->General['autocomplete_min_sites']);
156 return (int) $count;
157 }
158 /**
159 * Returns the URL to this Piwik instance, eg. **http://demo.piwik.org/** or **http://example.org/piwik/**.
160 *
161 * @return string|false return false if no value is configured and we are in PHP CLI mode
162 * @api
163 */
164 public static function getPiwikUrl()
165 {
166 $url = \Piwik\Option::get(self::OPTION_PIWIK_URL);
167 $isPiwikCoreDispatching = defined('PIWIK_ENABLE_DISPATCH') && PIWIK_ENABLE_DISPATCH;
168 if (\Piwik\Common::isPhpCliMode() || \Piwik\SettingsServer::isArchivePhpTriggered() || !$isPiwikCoreDispatching) {
169 return $url;
170 }
171 $currentUrl = \Piwik\Common::sanitizeInputValue(\Piwik\Url::getCurrentUrlWithoutFileName());
172 // when script is called from /misc/cron/archive.php, Piwik URL is /index.php
173 $currentUrl = str_replace("/misc/cron", "", $currentUrl);
174 if (empty($url) || $currentUrl !== $url) {
175 $host = \Piwik\Url::getHostFromUrl($currentUrl);
176 if (strlen($currentUrl) >= strlen('http://a/') && \Piwik\Url::isValidHost($host) && !\Piwik\Url::isLocalHost($host)) {
177 self::overwritePiwikUrl($currentUrl);
178 }
179 $url = $currentUrl;
180 }
181 if (\Piwik\ProxyHttp::isHttps()) {
182 $url = str_replace("http://", "https://", $url);
183 }
184 return $url;
185 }
186 /**
187 * @return bool
188 */
189 public static function isMatomoInstalled() : bool
190 {
191 $config = \Piwik\Config::getInstance()->getLocalPath();
192 $exists = file_exists($config);
193 // Piwik is not installed if the config file is not found
194 if (!$exists) {
195 return false;
196 }
197 $general = \Piwik\Config::getInstance()->General;
198 $isInstallationInProgress = false;
199 if (array_key_exists('installation_in_progress', $general)) {
200 $isInstallationInProgress = (bool) $general['installation_in_progress'];
201 }
202 if ($isInstallationInProgress) {
203 return false;
204 }
205 // Check that the database section is really set, ie. file is not empty
206 if (empty(\Piwik\Config::getInstance()->database['username'])) {
207 return false;
208 }
209 return true;
210 }
211 /**
212 * Check if outgoing internet connections are enabled
213 * This is often disable in an intranet environment
214 *
215 * @return bool
216 */
217 public static function isInternetEnabled() : bool
218 {
219 return (bool) \Piwik\Config::getInstance()->General['enable_internet_features'];
220 }
221 /**
222 * Detect whether user has enabled auto updates. Please note this config is a bit misleading. It is currently
223 * actually used for 2 things: To disable making any connections back to Piwik, and to actually disable the auto
224 * update of core and plugins.
225 * @return bool
226 */
227 public static function isAutoUpdateEnabled() : bool
228 {
229 $enableAutoUpdate = (bool) \Piwik\Config::getInstance()->General['enable_auto_update'];
230 if (self::isInternetEnabled() === true && $enableAutoUpdate === true) {
231 return true;
232 }
233 return false;
234 }
235 /**
236 * Detects whether an auto update can be made. An update is possible if the user is not on multiple servers and if
237 * automatic updates are actually enabled. If a user is running Piwik on multiple servers an update is not possible
238 * as it would be installed only on one server instead of all of them. Also if a user has disabled automatic updates
239 * we cannot perform any automatic updates.
240 *
241 * @return bool
242 */
243 public static function isAutoUpdatePossible() : bool
244 {
245 return !self::isMultiServerEnvironment() && self::isAutoUpdateEnabled();
246 }
247 /**
248 * Returns `true` if Piwik is running on more than one server. For example in a load balanced environment. In this
249 * case we should not make changes to the config and not install a plugin via the UI as it would be only executed
250 * on one server.
251 * @return bool
252 */
253 public static function isMultiServerEnvironment() : bool
254 {
255 $is = \Piwik\Config::getInstance()->General['multi_server_environment'];
256 return !empty($is);
257 }
258 /**
259 * Returns `true` if segmentation is allowed for this user, `false` if otherwise.
260 *
261 * @return bool
262 * @api
263 */
264 public static function isSegmentationEnabled() : bool
265 {
266 return !\Piwik\Piwik::isUserIsAnonymous() || \Piwik\Config::getInstance()->General['anonymous_user_enable_use_segments_API'];
267 }
268 /**
269 * Returns true if unique visitors should be processed for the given period type.
270 *
271 * Unique visitor processing is controlled by the `[General] enable_processing_unique_visitors_...`
272 * INI config options. By default, unique visitors are processed only for day/week/month periods.
273 *
274 * @param string $periodLabel `"day"`, `"week"`, `"month"`, `"year"` or `"range"`
275 * @return bool
276 * @api
277 */
278 public static function isUniqueVisitorsEnabled(string $periodLabel) : bool
279 {
280 $generalSettings = \Piwik\Config::getInstance()->General;
281 $settingName = "enable_processing_unique_visitors_{$periodLabel}";
282 $result = !empty($generalSettings[$settingName]) && $generalSettings[$settingName] == 1;
283 // check enable_processing_unique_visitors_year_and_range for backwards compatibility
284 if (($periodLabel === 'year' || $periodLabel === 'range') && isset($generalSettings['enable_processing_unique_visitors_year_and_range'])) {
285 $result |= $generalSettings['enable_processing_unique_visitors_year_and_range'] == 1;
286 }
287 return $result;
288 }
289 /**
290 * If Piwik uses per-domain config file, make sure CustomLogo is unique
291 * @param string $path
292 * @return string
293 * @throws \Piwik\Exception\DI\DependencyException
294 * @throws \Piwik\Exception\DI\NotFoundException
295 * @throws Exception
296 */
297 public static function rewriteMiscUserPathWithInstanceId(string $path) : string
298 {
299 $tmp = StaticContainer::get('path.misc.user');
300 $path = self::rewritePathAppendPiwikInstanceId($path, $tmp);
301 return $path;
302 }
303 /**
304 * Returns true if the Piwik server appears to be working.
305 *
306 * If the Piwik server is in an error state (eg. some directories are not writable and Piwik displays error message),
307 * or if the Piwik server is "offline",
308 * this will return false..
309 *
310 * @param string $piwikServerUrl
311 * @param bool $acceptInvalidSSLCertificates
312 * @return void
313 * @throws Exception
314 */
315 public static function checkPiwikServerWorking(string $piwikServerUrl, bool $acceptInvalidSSLCertificates = false) : void
316 {
317 // Now testing if the webserver is running
318 try {
319 $fetched = \Piwik\Http::sendHttpRequestBy('curl', $piwikServerUrl, $timeout = 45, $userAgent = null, $destinationPath = null, $file = null, $followDepth = 0, $acceptLanguage = false, $acceptInvalidSSLCertificates);
320 } catch (Exception $e) {
321 $fetched = "ERROR fetching: " . $e->getMessage();
322 }
323 // this will match when Piwik not installed yet, or favicon not customised
324 $expectedStringAlt = 'plugins/CoreHome/images/favicon.png';
325 // this will match when Piwik is installed and favicon has been customised
326 $expectedString = 'misc/user/';
327 // see checkPiwikIsNotInstalled()
328 $expectedStringAlreadyInstalled = 'piwik-is-already-installed';
329 $expectedStringNotFound = strpos($fetched, $expectedString) === false && strpos($fetched, $expectedStringAlt) === false && strpos($fetched, $expectedStringAlreadyInstalled) === false;
330 $hasError = false !== strpos($fetched, PAGE_TITLE_WHEN_ERROR);
331 if ($hasError || $expectedStringNotFound) {
332 throw new Exception("\nMatomo should be running at: " . $piwikServerUrl . " but this URL returned an unexpected response: '" . $fetched . "'\n\n");
333 }
334 }
335 /**
336 * Returns true if Piwik is deployed using git
337 * FAQ: http://piwik.org/faq/how-to-install/faq_18271/
338 *
339 * @return bool
340 */
341 public static function isGitDeployment() : bool
342 {
343 return file_exists(PIWIK_INCLUDE_PATH . '/.git/HEAD');
344 }
345 /**
346 * @return string
347 */
348 public static function getCurrentGitBranch() : string
349 {
350 $file = PIWIK_INCLUDE_PATH . '/.git/HEAD';
351 if (!file_exists($file)) {
352 return '';
353 }
354 $firstLineOfGitHead = file($file);
355 if (empty($firstLineOfGitHead)) {
356 return '';
357 }
358 $firstLineOfGitHead = $firstLineOfGitHead[0];
359 $parts = explode('/', $firstLineOfGitHead);
360 if (empty($parts[2])) {
361 return '';
362 }
363 $currentGitBranch = trim($parts[2]);
364 return $currentGitBranch;
365 }
366 /**
367 * @param string $pathToRewrite
368 * @param string $leadingPathToAppendHostnameTo
369 * @return string
370 * @throws Exception
371 */
372 protected static function rewritePathAppendPiwikInstanceId(string $pathToRewrite, string $leadingPathToAppendHostnameTo) : string
373 {
374 $instanceId = self::getPiwikInstanceId();
375 if (empty($instanceId)) {
376 return $pathToRewrite;
377 }
378 if (($posTmp = strrpos($pathToRewrite, $leadingPathToAppendHostnameTo)) === false) {
379 throw new Exception("The path {$pathToRewrite} was expected to contain the string {$leadingPathToAppendHostnameTo}");
380 }
381 $tmpToReplace = $leadingPathToAppendHostnameTo . $instanceId . '/';
382 // replace only the latest occurrence (in case path contains twice /tmp)
383 $pathToRewrite = substr_replace($pathToRewrite, $tmpToReplace, $posTmp, strlen($leadingPathToAppendHostnameTo));
384 return $pathToRewrite;
385 }
386 /**
387 * @throws Exception
388 * @return string|false return string or false if not set
389 */
390 public static function getPiwikInstanceId()
391 {
392 // until Matomo is installed, we use hostname as instance_id
393 if (!self::isMatomoInstalled() && \Piwik\Common::isPhpCliMode()) {
394 // enterprise:install use case
395 return \Piwik\Config::getHostname();
396 }
397 // config.ini.php not ready yet, instance_id will not be set
398 if (!\Piwik\Config::getInstance()->existsLocalConfig()) {
399 return false;
400 }
401 $instanceId = GeneralConfig::getConfigValue('instance_id');
402 if (!empty($instanceId)) {
403 return preg_replace('/[^\\w\\.-]/', '', $instanceId);
404 }
405 // do not rewrite the path as Matomo uses the standard config.ini.php file
406 return false;
407 }
408 /**
409 * @param string $currentUrl
410 */
411 public static function overwritePiwikUrl(string $currentUrl) : void
412 {
413 \Piwik\Option::set(self::OPTION_PIWIK_URL, $currentUrl, $autoLoad = true);
414 }
415 /**
416 * @return bool
417 */
418 public static function isHttpsForced() : bool
419 {
420 if (!self::isMatomoInstalled()) {
421 // Only enable this feature after Piwik is already installed
422 return false;
423 }
424 return \Piwik\Config::getInstance()->General['force_ssl'] == 1;
425 }
426 /**
427 * Note: this config settig is also checked in the InterSites plugin
428 *
429 * @return bool
430 */
431 public static function isSameFingerprintAcrossWebsites() : bool
432 {
433 return (bool) \Piwik\Config::getInstance()->Tracker['enable_fingerprinting_across_websites'];
434 }
435 }
436