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