/
Piwik.php
2774 lines (2513 loc) · 70.3 KB
/
Piwik.php
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?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
*/
/**
* @see core/Translate.php
*/
require_once PIWIK_INCLUDE_PATH . '/core/Translate.php';
/**
* Main piwik helper class.
* Contains static functions you can call from the plugins.
*
* @package Piwik
*/
class Piwik
{
const CLASSES_PREFIX = 'Piwik_';
const COMPRESSED_FILE_LOCATION = '/tmp/assets/';
/**
* Piwik periods
* @var array
*/
public static $idPeriods = array(
'day' => 1,
'week' => 2,
'month' => 3,
'year' => 4,
'range' => 5,
);
/**
* Should we process and display Unique Visitors?
* -> Always process for day/week/month periods
* For Year and Range, only process if it was enabled in the config file,
*
* @param string $periodLabel Period label (e.g., 'day')
* @return bool
*/
static public function isUniqueVisitorsEnabled($periodLabel)
{
$generalSettings = Piwik_Config::getInstance()->General;
$settingName = "enable_processing_unique_visitors_$periodLabel";
$result = !empty($generalSettings[$settingName]) && $generalSettings[$settingName] == 1;
// check enable_processing_unique_visitors_year_and_range for backwards compatibility
if (($periodLabel == 'year' || $periodLabel == 'range')
&& isset($generalSettings['enable_processing_unique_visitors_year_and_range']))
{
$result |= $generalSettings['enable_processing_unique_visitors_year_and_range'] == 1;
}
return $result;
}
/**
* Prefix class name (if needed)
*
* @param string $class
* @return string
*/
static public function prefixClass( $class )
{
if(!strncmp($class, Piwik::CLASSES_PREFIX, strlen(Piwik::CLASSES_PREFIX)))
{
return $class;
}
return Piwik::CLASSES_PREFIX.$class;
}
/**
* Unprefix class name (if needed)
*
* @param string $class
* @return string
*/
static public function unprefixClass( $class )
{
$lenPrefix = strlen(Piwik::CLASSES_PREFIX);
if(!strncmp($class, Piwik::CLASSES_PREFIX, $lenPrefix))
{
return substr($class, $lenPrefix);
}
return $class;
}
/**
* Installation helper
*/
static public function install()
{
Piwik_Common::mkdir(PIWIK_USER_PATH . '/' . Piwik_Config::getInstance()->smarty['compile_dir']);
}
/**
* Uninstallation helper
*/
static public function uninstall()
{
Piwik_Db_Schema::getInstance()->dropTables();
}
/**
* Returns true if Piwik is installed
*
* @since 0.6.3
*
* @return bool True if installed; false otherwise
*/
static public function isInstalled()
{
try {
return Piwik_Db_Schema::getInstance()->hasTables();
} catch(Exception $e) {
return false;
}
}
/**
* Called on Core install, update, plugin enable/disable
* Will clear all cache that could be affected by the change in configuration being made
*/
static public function deleteAllCacheOnUpdate()
{
Piwik_AssetManager::removeMergedAssets();
Piwik_View::clearCompiledTemplates();
Piwik_Tracker_Cache::deleteTrackerCache();
}
/**
* Cache for result of getPiwikUrl.
* Can be overwritten for testing purposes only.
*
* @var string
*/
static public $piwikUrlCache = null;
/**
* Returns the cached the Piwik URL, eg. http://demo.piwik.org/ or http://example.org/piwik/
* If not found, then tries to cache it and returns the value.
*
* If the Piwik URL changes (eg. Piwik moved to new server), the value will automatically be refreshed in the cache.
*
* @return string
*/
static public function getPiwikUrl()
{
// Only set in tests
if (self::$piwikUrlCache !== null)
{
return self::$piwikUrlCache;
}
$key = 'piwikUrl';
$url = Piwik_GetOption($key);
if(Piwik_Common::isPhpCliMode()
// in case archive.php is triggered with domain localhost
|| Piwik_Common::isArchivePhpTriggered()
|| defined('PIWIK_MODE_ARCHIVE'))
{
return $url;
}
$currentUrl = Piwik_Common::sanitizeInputValue(Piwik_Url::getCurrentUrlWithoutFileName());
if(empty($url)
// if URL changes, always update the cache
|| $currentUrl != $url)
{
if(strlen($currentUrl) >= strlen('http://a/'))
{
Piwik_SetOption($key, $currentUrl, $autoload = true);
}
$url = $currentUrl;
}
return $url;
}
/**
* Returns true if this appears to be a secure HTTPS connection
*
* @return bool
*/
static public function isHttps()
{
return Piwik_Url::getCurrentScheme() === 'https';
}
/**
* Set response header, e.g., HTTP/1.0 200 Ok
*
* @param string $status Status
* @return bool
*/
static public function setHttpStatus($status)
{
if(substr_compare(PHP_SAPI, '-fcgi', -5))
{
@header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status);
}
else
{
// FastCGI
@header('Status: ' . $status);
}
}
/**
* Workaround IE bug when downloading certain document types over SSL and
* cache control headers are present, e.g.,
*
* Cache-Control: no-cache
* Cache-Control: no-store,max-age=0,must-revalidate
* Pragma: no-cache
*
* @see http://support.microsoft.com/kb/316431/
* @see RFC2616
*
* @param string $override One of "public", "private", "no-cache", or "no-store". (optional)
*/
static public function overrideCacheControlHeaders($override = null)
{
if($override || self::isHttps())
{
@header('Pragma: ');
@header('Expires: ');
if(in_array($override, array('public', 'private', 'no-cache', 'no-store')))
{
@header("Cache-Control: $override, must-revalidate");
}
else
{
@header('Cache-Control: must-revalidate');
}
}
}
/*
* File and directory operations
*/
/**
* Copy recursively from $source to $target.
*
* @param string $source eg. './tmp/latest'
* @param string $target eg. '.'
* @param bool $excludePhp
*/
static public function copyRecursive($source, $target, $excludePhp=false )
{
if ( is_dir( $source ) )
{
Piwik_Common::mkdir( $target, false );
$d = dir( $source );
while ( false !== ( $entry = $d->read() ) )
{
if ( $entry == '.' || $entry == '..' )
{
continue;
}
$sourcePath = $source . '/' . $entry;
if ( is_dir( $sourcePath ) )
{
self::copyRecursive( $sourcePath, $target . '/' . $entry, $excludePhp );
continue;
}
$destPath = $target . '/' . $entry;
self::copy($sourcePath, $destPath, $excludePhp);
}
$d->close();
}
else
{
self::copy($source, $target, $excludePhp);
}
}
/**
* Copy individual file from $source to $target.
*
* @param string $source eg. './tmp/latest/index.php'
* @param string $dest eg. './index.php'
* @param bool $excludePhp
* @throws Exception
* @return bool
*/
static public function copy($source, $dest, $excludePhp=false)
{
static $phpExtensions = array('php', 'tpl');
if($excludePhp)
{
$path_parts = pathinfo($source);
if(in_array($path_parts['extension'], $phpExtensions))
{
return true;
}
}
if(!@copy( $source, $dest ))
{
@chmod($dest, 0755);
if(!@copy( $source, $dest ))
{
$message = "Error while creating/copying file to <code>$dest</code>. <br />"
. self::getErrorMessageMissingPermissions(Piwik_Common::getPathToPiwikRoot());
throw new Exception($message);
}
}
return true;
}
/**
* Returns friendly error message explaining how to fix permissions
*
* @param string $path to the directory missing permissions
* @return string Error message
*/
static public function getErrorMessageMissingPermissions($path)
{
$message = "Please check that the web server has enough permission to write to these files/directories:<br />";
if(Piwik_Common::isWindows())
{
$message .= "On Windows, check that the folder is not read only and is writable.
You can try to execute:<br />";
}
else
{
$message .= "For example, on a Linux server if your Apache httpd user
is www-data, you can try to execute:<br />"
. "<code>chown -R www-data:www-data ".$path."</code><br />";
}
$message .= self::getMakeWritableCommand($path);
return $message;
}
/**
* Recursively delete a directory
*
* @param string $dir Directory name
* @param boolean $deleteRootToo Delete specified top-level directory as well
*/
static public function unlinkRecursive($dir, $deleteRootToo)
{
if(!$dh = @opendir($dir))
{
return;
}
while (false !== ($obj = readdir($dh)))
{
if($obj == '.' || $obj == '..')
{
continue;
}
if (!@unlink($dir . '/' . $obj))
{
self::unlinkRecursive($dir.'/'.$obj, true);
}
}
closedir($dh);
if ($deleteRootToo)
{
@rmdir($dir);
}
return;
}
/**
* Recursively find pathnames that match a pattern
* @see glob()
*
* @param string $sDir directory
* @param string $sPattern pattern
* @param int $nFlags glob() flags
* @return array
*/
public static function globr($sDir, $sPattern, $nFlags = NULL)
{
if(($aFiles = _glob("$sDir/$sPattern", $nFlags)) == false)
{
$aFiles = array();
}
if(($aDirs = _glob("$sDir/*", GLOB_ONLYDIR)) != false)
{
foreach ($aDirs as $sSubDir)
{
$aSubFiles = self::globr($sSubDir, $sPattern, $nFlags);
$aFiles = array_merge($aFiles, $aSubFiles);
}
}
return $aFiles;
}
/**
* Returns the help text displayed to suggest which command to run to give writable access to a file or directory
*
* @param string $realpath
* @return string
*/
static private function getMakeWritableCommand($realpath)
{
if(Piwik_Common::isWindows())
{
return "<code>cacls $realpath /t /g ".get_current_user().":f</code><br />";
}
return "<code>chmod -R 0755 $realpath</code><br />";
}
/**
* Checks that the directories Piwik needs write access are actually writable
* Displays a nice error page if permissions are missing on some directories
*
* @param array $directoriesToCheck Array of directory names to check
*/
static public function checkDirectoriesWritableOrDie( $directoriesToCheck = null )
{
$resultCheck = Piwik::checkDirectoriesWritable( $directoriesToCheck );
if( array_search(false, $resultCheck) === false )
{
return;
}
$directoryList = '';
foreach($resultCheck as $dir => $bool)
{
$realpath = Piwik_Common::realpath($dir);
if(!empty($realpath) && $bool === false)
{
$directoryList .= self::getMakeWritableCommand($realpath);
}
}
// Also give the chown since the chmod is only 755
if(!Piwik_Common::isWindows())
{
$realpath = Piwik_Common::realpath(PIWIK_INCLUDE_PATH . '/');
$directoryList = "<code>chown -R www-data:www-data ".$realpath."</code><br/>" . $directoryList;
}
// The error message mentions chmod 777 in case users can't chown
$directoryMessage = "<p><b>Piwik couldn't write to some directories</b>.</p>
<p>Try to Execute the following commands on your server, to allow Write access on these directories:</p>"
. "<blockquote>$directoryList</blockquote>"
. "<p>If this doesn't work, you can try to create the directories with your FTP software, and set the CHMOD to 0755 (or 0777 if 0755 is not enough). To do so with your FTP software, right click on the directories then click permissions.</p>"
. "<p>After applying the modifications, you can <a href='index.php'>refresh the page</a>.</p>"
. "<p>If you need more help, try <a href='?module=Proxy&action=redirect&url=http://piwik.org'>Piwik.org</a>.</p>";
Piwik_ExitWithMessage($directoryMessage, false, true);
}
/**
* Checks if directories are writable and create them if they do not exist.
*
* @param array $directoriesToCheck array of directories to check - if not given default Piwik directories that needs write permission are checked
* @return array directory name => true|false (is writable)
*/
static public function checkDirectoriesWritable($directoriesToCheck = null)
{
if( $directoriesToCheck == null )
{
$directoriesToCheck = array(
'/config/',
'/tmp/',
'/tmp/templates_c/',
'/tmp/cache/',
'/tmp/assets/',
'/tmp/latest/',
'/tmp/tcpdf/',
'/tmp/sessions/',
);
}
$resultCheck = array();
foreach($directoriesToCheck as $directoryToCheck)
{
if( !preg_match('/^'.preg_quote(PIWIK_USER_PATH, '/').'/', $directoryToCheck) )
{
$directoryToCheck = PIWIK_USER_PATH . $directoryToCheck;
}
if(!file_exists($directoryToCheck))
{
Piwik_Common::mkdir($directoryToCheck);
}
$directory = Piwik_Common::realpath($directoryToCheck);
$resultCheck[$directory] = false;
if($directory !== false // realpath() returns FALSE on failure
&& is_writable($directoryToCheck))
{
$resultCheck[$directory] = true;
}
}
return $resultCheck;
}
/**
* Check if this installation can be auto-updated.
* For performance, we look for clues rather than an exhaustive test.
*
* @return bool
*/
static public function canAutoUpdate()
{
if(!is_writable(PIWIK_INCLUDE_PATH . '/') ||
!is_writable(PIWIK_DOCUMENT_ROOT . '/index.php') ||
!is_writable(PIWIK_INCLUDE_PATH . '/core') ||
!is_writable(PIWIK_USER_PATH . '/config/global.ini.php'))
{
return false;
}
return true;
}
/**
* Returns the help message when the auto update can't run because of missing permissions
*
* @return string
*/
static public function getAutoUpdateMakeWritableMessage()
{
$realpath = Piwik_Common::realpath(PIWIK_INCLUDE_PATH . '/');
$message = '';
$message .= "<code>chown -R www-data:www-data ".$realpath."</code><br />";
$message .= "<code>chmod -R 0755 ".$realpath."</code><br />";
$message .= 'After you execute these commands (or change permissions via your FTP software), refresh the page and you should be able to use the "Automatic Update" feature.';
return $message;
}
/**
* Generate default robots.txt, favicon.ico, etc to suppress
* 404 (Not Found) errors in the web server logs, if Piwik
* is installed in the web root (or top level of subdomain).
*
* @see misc/crossdomain.xml
*/
static public function createWebRootFiles()
{
$filesToCreate = array(
'/robots.txt',
'/favicon.ico',
);
foreach($filesToCreate as $file)
{
@file_put_contents(PIWIK_DOCUMENT_ROOT . $file, '');
}
}
/**
* Generate Apache .htaccess files to restrict access
*/
static public function createHtAccessFiles()
{
// deny access to these folders
$directoriesToProtect = array(
'/config',
'/core',
'/lang',
'/tmp',
);
foreach($directoriesToProtect as $directoryToProtect)
{
Piwik_Common::createHtAccess(PIWIK_INCLUDE_PATH . $directoryToProtect, $overwrite = true);
}
// Allow/Deny lives in different modules depending on the Apache version
$allow = "<IfModule mod_access.c>\nAllow from all\n</IfModule>\n<IfModule !mod_access_compat>\n<IfModule mod_authz_host.c>\nAllow from all\n</IfModule>\n</IfModule>\n<IfModule mod_access_compat>\nAllow from all\n</IfModule>\n";
$deny = "<IfModule mod_access.c>\nDeny from all\n</IfModule>\n<IfModule !mod_access_compat>\n<IfModule mod_authz_host.c>\nDeny from all\n</IfModule>\n</IfModule>\n<IfModule mod_access_compat>\nDeny from all\n</IfModule>\n";
// more selective allow/deny filters
$allowAny = "<Files \"*\">\n".$allow."Satisfy any\n</Files>\n";
$allowStaticAssets = "<Files ~ \"\\.(test\.php|gif|ico|jpg|png|js|css|swf)$\">\n".$allow."Satisfy any\n</Files>\n";
$denyDirectPhp = "<Files ~ \"\\.(php|php4|php5|inc|tpl|in)$\">\n".$deny."</Files>\n";
$directoriesToProtect = array(
'/js' => $allowAny,
'/libs' => $denyDirectPhp . $allowStaticAssets,
'/plugins' => $denyDirectPhp . $allowStaticAssets,
'/themes' => $denyDirectPhp . $allowStaticAssets,
);
foreach($directoriesToProtect as $directoryToProtect => $content)
{
Piwik_Common::createHtAccess(PIWIK_INCLUDE_PATH . $directoryToProtect, $overwrite = true, $content);
}
}
/**
* Generate IIS web.config files to restrict access
*
* Note: for IIS 7 and above
*/
static public function createWebConfigFiles()
{
@file_put_contents(PIWIK_INCLUDE_PATH . '/web.config',
'<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<security>
<requestFiltering>
<hiddenSegments>
<add segment="config" />
<add segment="core" />
<add segment="lang" />
<add segment="tmp" />
</hiddenSegments>
<fileExtensions>
<add fileExtension=".tpl" allowed="false" />
<add fileExtension=".php4" allowed="false" />
<add fileExtension=".php5" allowed="false" />
<add fileExtension=".inc" allowed="false" />
<add fileExtension=".in" allowed="false" />
</fileExtensions>
</requestFiltering>
</security>
<directoryBrowse enabled="false" />
<defaultDocument>
<files>
<remove value="index.php" />
<add value="index.php" />
</files>
</defaultDocument>
</system.webServer>
</configuration>');
// deny direct access to .php files
$directoriesToProtect = array(
'/libs',
'/plugins',
);
foreach($directoriesToProtect as $directoryToProtect)
{
@file_put_contents(PIWIK_INCLUDE_PATH . $directoryToProtect . '/web.config',
'<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<security>
<requestFiltering>
<denyUrlSequences>
<add sequence=".php" />
</denyUrlSequences>
</requestFiltering>
</security>
</system.webServer>
</configuration>');
}
}
/**
* Get file integrity information (in PIWIK_INCLUDE_PATH).
*
* @return array(bool, string, ...) Return code (true/false), followed by zero or more error messages
*/
static public function getFileIntegrityInformation()
{
$messages = array();
$messages[] = true;
// ignore dev environments
if(file_exists(PIWIK_INCLUDE_PATH . '/.git'))
{
$messages[] = Piwik_Translate('General_WarningFileIntegritySkipped');
return $messages;
}
$manifest = PIWIK_INCLUDE_PATH . '/config/manifest.inc.php';
if(!file_exists($manifest))
{
$messages[] = Piwik_Translate('General_WarningFileIntegrityNoManifest');
return $messages;
}
require_once $manifest;
$files = Manifest::$files;
$hasMd5file = function_exists('md5_file');
$hasMd5 = function_exists('md5');
foreach($files as $path => $props)
{
$file = PIWIK_INCLUDE_PATH . '/' . $path;
if(!file_exists($file))
{
$messages[] = Piwik_Translate('General_ExceptionMissingFile', $file);
}
else if(filesize($file) != $props[0])
{
if(!$hasMd5 || in_array(substr($path, -4), array('.gif', '.ico', '.jpg', '.png', '.swf')))
{
// files that contain binary data (e.g., images) must match the file size
$messages[] = Piwik_Translate('General_ExceptionFilesizeMismatch', array($file, $props[0], filesize($file)));
}
else
{
// convert end-of-line characters and re-test text files
$content = @file_get_contents($file);
$content = str_replace("\r\n", "\n", $content);
if((strlen($content) != $props[0])
|| (@md5($content) !== $props[1]))
{
$messages[] = Piwik_Translate('General_ExceptionFilesizeMismatch', array($file, $props[0], filesize($file)));
}
}
}
else if($hasMd5file && (@md5_file($file) !== $props[1]))
{
$messages[] = Piwik_Translate('General_ExceptionFileIntegrity', $file);
}
}
if(count($messages) > 1)
{
$messages[0] = false;
}
if(!$hasMd5file)
{
$messages[] = Piwik_Translate('General_WarningFileIntegrityNoMd5file');
}
return $messages;
}
/**
* Test if php output is compressed
*
* @return bool True if php output is (or suspected/likely) to be compressed
*/
static public function isPhpOutputCompressed()
{
// Off = ''; On = '1'; otherwise, it's a buffer size
$zlibOutputCompression = ini_get('zlib.output_compression');
// could be ob_gzhandler, ob_deflatehandler, etc
$outputHandler = ini_get('output_handler');
// output handlers can be stacked
$obHandlers = array_filter( ob_list_handlers(), create_function('$var', 'return $var !== "default output handler";') );
// user defined handler via wrapper
$autoPrependFile = ini_get('auto_prepend_file');
$autoAppendFile = ini_get('auto_append_file');
return !empty($zlibOutputCompression) ||
!empty($outputHandler) ||
!empty($obHandlers) ||
!empty($autoPrependFile) ||
!empty($autoAppendFile);
}
/**
* Serve static files through php proxy.
*
* It performs the following actions:
* - Checks the file is readable or returns "HTTP/1.0 404 Not Found"
* - Returns "HTTP/1.1 304 Not Modified" after comparing the HTTP_IF_MODIFIED_SINCE
* with the modification date of the static file
* - Will try to compress the static file according to HTTP_ACCEPT_ENCODING. Compressed files are store in
* the /tmp directory. If compressing extensions are not available, a manually gzip compressed file
* can be provided in the /tmp directory. It has to bear the same name with an added .gz extension.
* Using manually compressed static files requires you to manually update the compressed file when
* the static file is updated.
* - Overrides server cache control config to allow caching
* - Sends Very Accept-Encoding to tell proxies to store different version of the static file according
* to users encoding capacities.
*
* Warning:
* Compressed filed are stored in the /tmp directory.
* If this method is used with two files bearing the same name but located in different locations,
* there is a risk of conflict. One file could be served with the content of the other.
* A future upgrade of this method would be to recreate the directory structure of the static file
* within a /tmp/compressed-static-files directory.
*
* @param string $file The location of the static file to serve
* @param string $contentType The content type of the static file.
* @param bool $expireFarFuture If set to true, will set Expires: header in far future.
* Should be set to false for files that don't have a cache buster (eg. piwik.js)
*/
static public function serveStaticFile($file, $contentType, $expireFarFuture = true)
{
if (file_exists($file))
{
// conditional GET
$modifiedSince = '';
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']))
{
$modifiedSince = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
// strip any trailing data appended to header
if (false !== ($semicolon = strpos($modifiedSince, ';')))
{
$modifiedSince = substr($modifiedSince, 0, $semicolon);
}
}
$fileModifiedTime = @filemtime($file);
$lastModified = gmdate('D, d M Y H:i:s', $fileModifiedTime) . ' GMT';
// set HTTP response headers
self::overrideCacheControlHeaders('public');
@header('Vary: Accept-Encoding');
@header('Content-Disposition: inline; filename='.basename($file));
if($expireFarFuture)
{
// Required by proxy caches potentially in between the browser and server to cache the request indeed
@header("Expires: ".gmdate('D, d M Y H:i:s', time() + 86400 * 100) . ' GMT');
}
// Returns 304 if not modified since
if ($modifiedSince === $lastModified)
{
self::setHttpStatus('304 Not Modified');
}
else
{
// optional compression
$compressed = false;
$encoding = '';
$compressedFileLocation = PIWIK_USER_PATH . self::COMPRESSED_FILE_LOCATION . basename($file);
$phpOutputCompressionEnabled = self::isPhpOutputCompressed();
if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && !$phpOutputCompressionEnabled)
{
$acceptEncoding = $_SERVER['HTTP_ACCEPT_ENCODING'];
if (extension_loaded('zlib') && function_exists('file_get_contents') && function_exists('file_put_contents'))
{
if (preg_match('/(?:^|, ?)(deflate)(?:,|$)/', $acceptEncoding, $matches))
{
$encoding = 'deflate';
$filegz = $compressedFileLocation .'.deflate';
}
else if (preg_match('/(?:^|, ?)((x-)?gzip)(?:,|$)/', $acceptEncoding, $matches))
{
$encoding = $matches[1];
$filegz = $compressedFileLocation .'.gz';
}
if (!empty($encoding))
{
// compress-on-demand and use cache
if(!file_exists($filegz) || ($fileModifiedTime > @filemtime($filegz)))
{
$data = file_get_contents($file);
if ($encoding == 'deflate')
{
$data = gzdeflate($data, 9);
}
else if ($encoding == 'gzip' || $encoding == 'x-gzip')
{
$data = gzencode($data, 9);
}
file_put_contents($filegz, $data);
}
$compressed = true;
$file = $filegz;
}
}
else
{
// manually compressed
$filegz = $compressedFileLocation .'.gz';
if (preg_match('/(?:^|, ?)((x-)?gzip)(?:,|$)/', $acceptEncoding, $matches) && file_exists($filegz) && ($fileModifiedTime < @filemtime($filegz)))
{
$encoding = $matches[1];
$compressed = true;
$file = $filegz;
}
}
}
@header('Last-Modified: ' . $lastModified);
if(!$phpOutputCompressionEnabled)
{
@header('Content-Length: ' . filesize($file));
}
if(!empty($contentType))
{
@header('Content-Type: '.$contentType);
}
if($compressed)
{
@header('Content-Encoding: ' . $encoding);
}
if(!_readfile($file))
{
self::setHttpStatus('505 Internal server error');
}
}
}
else
{
self::setHttpStatus('404 Not Found');
}
}
/**
* Create CSV (or other delimited) files
*
* @param string $filePath filename to create
* @param array $fileSpec File specifications (delimiter, line terminator, etc)
* @param array $rows Array of array corresponding to rows of values
* @throws Exception if unable to create or write to file
*/
static public function createCSVFile($filePath, $fileSpec, $rows)
{
// Set up CSV delimiters, quotes, etc
$delim = $fileSpec['delim'];
$quote = $fileSpec['quote'];
$eol = $fileSpec['eol'];
$null = $fileSpec['null'];
$escapespecial_cb = $fileSpec['escapespecial_cb'];
$fp = @fopen($filePath, 'wb');
if (!$fp)
{
throw new Exception('Error creating the tmp file '.$filePath.', please check that the webserver has write permission to write this file.');
}
foreach ($rows as $row)
{
$output = '';
foreach($row as $value)
{
if(!isset($value) || is_null($value) || $value === false)
{
$output .= $null.$delim;
}
else
{
$output .= $quote.$escapespecial_cb($value).$quote.$delim;
}
}
// Replace delim with eol
$output = substr_replace($output, $eol, -1);
$ret = fwrite($fp, $output);
if (!$ret) {
fclose($fp);
throw new Exception('Error writing to the tmp file '.$filePath);
}
}
fclose($fp);
@chmod($filePath, 0777);
}
/*
* PHP environment settings
*/
/**
* Set maximum script execution time.
*
* @param int $executionTime max execution time in seconds (0 = no limit)
*/
static public function setMaxExecutionTime($executionTime)
{
// in the event one or the other is disabled...
@ini_set('max_execution_time', $executionTime);
@set_time_limit($executionTime);
}
/**
* Get php memory_limit (in Megabytes)
*
* Prior to PHP 5.2.1, or on Windows, --enable-memory-limit is not a
* compile-time default, so ini_get('memory_limit') may return false.
*
* @see http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
* @return int|false memory limit in megabytes, or false if there is no limit
*/
static public function getMemoryLimitValue()
{
if(($memory = ini_get('memory_limit')) > 0)
{
// handle shorthand byte options (case-insensitive)