PluginProbe ʕ •ᴥ•ʔ
Matomo Analytics – Powerful, Privacy-First Insights for WordPress / trunk
Matomo Analytics – Powerful, Privacy-First Insights for WordPress vtrunk
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 1 month ago Access 3 months ago Application 1 month ago Archive 1 month ago ArchiveProcessor 1 month ago Archiver 2 years ago AssetManager 1 month ago Auth 6 months ago Category 6 months ago Changes 1 month ago CliMulti 1 year ago Columns 1 month ago Concurrency 1 month ago Config 1 month ago Container 1 month ago CronArchive 3 months ago DataAccess 1 month ago DataFiles 2 years ago DataTable 3 weeks ago Db 3 weeks ago DeviceDetector 1 year ago Email 2 years ago Exception 4 months ago Http 4 months ago Intl 3 months ago Log 2 years ago Mail 1 year ago Measurable 6 months ago Menu 1 month ago Metrics 3 months ago Notification 6 months ago Period 1 month ago Plugin 3 weeks ago Policy 1 month ago ProfessionalServices 1 year ago Report 1 year ago ReportRenderer 3 months ago Request 3 months ago Scheduler 1 month ago Segment 1 month ago Session 3 weeks ago Settings 1 month ago Tracker 3 weeks ago Translation 1 month ago Twig 1 year ago UpdateCheck 3 months ago Updater 1 month ago Updates 1 week ago Validators 1 year ago View 1 month ago ViewDataTable 3 weeks ago Visualization 1 year ago Widget 1 month ago .htaccess 2 years ago Access.php 1 month ago Archive.php 1 month ago ArchiveProcessor.php 1 month ago AssetManager.php 1 month ago Auth.php 6 months ago AuthResult.php 6 months ago BaseFactory.php 2 years ago Cache.php 2 years ago CacheId.php 4 months ago CliMulti.php 1 month ago Common.php 3 weeks ago Config.php 1 month ago Console.php 3 months ago Context.php 2 years ago Cookie.php 1 year ago CronArchive.php 1 month ago DI.php 3 months ago DataArray.php 1 month ago DataTable.php 1 month ago Date.php 1 month ago Db.php 1 month ago DbHelper.php 1 month ago Development.php 1 year ago ErrorHandler.php 6 months ago EventDispatcher.php 1 month ago ExceptionHandler.php 4 months ago FileIntegrity.php 1 month ago Filechecks.php 1 year ago Filesystem.php 1 month ago FrontController.php 4 months ago Http.php 1 month ago IP.php 1 year ago Log.php 3 months ago LogDeleter.php 1 year ago Mail.php 1 year ago Metrics.php 1 month ago NoAccessException.php 2 years ago Nonce.php 6 months ago Notification.php 1 month ago NumberFormatter.php 5 months ago Option.php 5 months ago Period.php 1 month ago Piwik.php 1 month ago Plugin.php 1 month ago Process.php 1 month ago Profiler.php 6 months ago ProxyHeaders.php 4 months ago ProxyHttp.php 5 months ago QuickForm2.php 3 months ago RankingQuery.php 1 month ago ReportRenderer.php 1 month ago Request.php 1 month ago Segment.php 1 month ago Sequence.php 6 months ago Session.php 3 weeks ago SettingsPiwik.php 1 month ago SettingsServer.php 1 year ago Singleton.php 2 years ago Site.php 1 month ago SiteContentDetector.php 1 month ago SupportedBrowser.php 2 years ago TCPDF.php 1 year ago Theme.php 1 year ago Timer.php 1 month ago Tracker.php 1 month ago Twig.php 1 month ago Unzip.php 1 year ago UpdateCheck.php 1 month ago Updater.php 1 month ago UpdaterErrorException.php 2 years ago Updates.php 3 months ago Url.php 3 months ago UrlHelper.php 1 month ago Version.php 1 week ago View.php 1 month ago bootstrap.php 1 year ago dispatch.php 2 years ago testMinimumPhpVersion.php 6 months ago
SettingsPiwik.php
399 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 * Returns true if 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 return false..
291 *
292 * @throws Exception
293 */
294 public static function checkPiwikServerWorking(string $piwikServerUrl, bool $acceptInvalidSSLCertificates = \false) : void
295 {
296 // Now testing if the webserver is running
297 try {
298 $fetched = \Piwik\Http::sendHttpRequestBy('curl', $piwikServerUrl, $timeout = 45, $userAgent = null, $destinationPath = null, $file = null, $followDepth = 0, $acceptLanguage = \false, $acceptInvalidSSLCertificates);
299 } catch (Exception $e) {
300 $fetched = "ERROR fetching: " . $e->getMessage();
301 }
302 // this will match when Piwik not installed yet, or favicon not customised
303 $expectedStringAlt = 'plugins/CoreHome/images/favicon.png';
304 // this will match when Piwik is installed and favicon has been customised
305 $expectedString = 'misc/user/';
306 // see checkPiwikIsNotInstalled()
307 $expectedStringAlreadyInstalled = 'piwik-is-already-installed';
308 $expectedStringNotFound = strpos($fetched, $expectedString) === \false && strpos($fetched, $expectedStringAlt) === \false && strpos($fetched, $expectedStringAlreadyInstalled) === \false;
309 $hasError = \false !== strpos($fetched, PAGE_TITLE_WHEN_ERROR);
310 if ($hasError || $expectedStringNotFound) {
311 throw new Exception("\nMatomo should be running at: " . $piwikServerUrl . " but this URL returned an unexpected response: '" . $fetched . "'\n\n");
312 }
313 }
314 /**
315 * Returns true if Piwik is deployed using git
316 * FAQ: https://piwik.org/faq/how-to-install/faq_18271/
317 */
318 public static function isGitDeployment() : bool
319 {
320 return file_exists(PIWIK_INCLUDE_PATH . '/.git/HEAD');
321 }
322 public static function getCurrentGitBranch() : string
323 {
324 $file = PIWIK_INCLUDE_PATH . '/.git/HEAD';
325 if (!file_exists($file)) {
326 return '';
327 }
328 $firstLineOfGitHead = file($file);
329 if (empty($firstLineOfGitHead)) {
330 return '';
331 }
332 $firstLineOfGitHead = $firstLineOfGitHead[0];
333 $parts = explode('/', $firstLineOfGitHead);
334 if (empty($parts[2])) {
335 return '';
336 }
337 $currentGitBranch = trim($parts[2]);
338 return $currentGitBranch;
339 }
340 /**
341 * @throws Exception
342 */
343 protected static function rewritePathAppendPiwikInstanceId(string $pathToRewrite, string $leadingPathToAppendHostnameTo) : string
344 {
345 $instanceId = self::getPiwikInstanceId();
346 if (empty($instanceId)) {
347 return $pathToRewrite;
348 }
349 if (($posTmp = strrpos($pathToRewrite, $leadingPathToAppendHostnameTo)) === \false) {
350 throw new Exception("The path {$pathToRewrite} was expected to contain the string {$leadingPathToAppendHostnameTo}");
351 }
352 $tmpToReplace = $leadingPathToAppendHostnameTo . $instanceId . '/';
353 // replace only the latest occurrence (in case path contains twice /tmp)
354 $pathToRewrite = substr_replace($pathToRewrite, $tmpToReplace, $posTmp, strlen($leadingPathToAppendHostnameTo));
355 return $pathToRewrite;
356 }
357 /**
358 * @throws Exception
359 * @return string|false return string or false if not set
360 */
361 public static function getPiwikInstanceId()
362 {
363 // until Matomo is installed, we use hostname as instance_id
364 if (!self::isMatomoInstalled() && \Piwik\Common::isPhpCliMode()) {
365 // enterprise:install use case
366 return \Piwik\Config::getHostname();
367 }
368 // config.ini.php not ready yet, instance_id will not be set
369 if (!\Piwik\Config::getInstance()->existsLocalConfig()) {
370 return \false;
371 }
372 $instanceId = GeneralConfig::getConfigValue('instance_id');
373 if (!empty($instanceId)) {
374 return preg_replace('/[^\\w\\.-]/', '', $instanceId);
375 }
376 // do not rewrite the path as Matomo uses the standard config.ini.php file
377 return \false;
378 }
379 public static function overwritePiwikUrl(string $currentUrl) : void
380 {
381 \Piwik\Option::set(self::OPTION_PIWIK_URL, $currentUrl, $autoLoad = \true);
382 }
383 public static function isHttpsForced() : bool
384 {
385 if (!self::isMatomoInstalled()) {
386 // Only enable this feature after Piwik is already installed
387 return \false;
388 }
389 return \Piwik\Config::getInstance()->General['force_ssl'] == 1;
390 }
391 /**
392 * Note: this config settig is also checked in the InterSites plugin
393 */
394 public static function isSameFingerprintAcrossWebsites() : bool
395 {
396 return (bool) \Piwik\Config::getInstance()->Tracker['enable_fingerprinting_across_websites'];
397 }
398 }
399