Config.php 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * Configuration handling.
  5. *
  6. * @package PhpMyAdmin
  7. */
  8. namespace PhpMyAdmin;
  9. use DirectoryIterator;
  10. use PhpMyAdmin\Core;
  11. use PhpMyAdmin\Error;
  12. use PhpMyAdmin\LanguageManager;
  13. use PhpMyAdmin\ThemeManager;
  14. use PhpMyAdmin\Url;
  15. use PhpMyAdmin\UserPreferences;
  16. use PhpMyAdmin\Util;
  17. use PhpMyAdmin\Utils\HttpRequest;
  18. /**
  19. * Indication for error handler (see end of this file).
  20. */
  21. $GLOBALS['pma_config_loading'] = false;
  22. /**
  23. * Configuration class
  24. *
  25. * @package PhpMyAdmin
  26. */
  27. class Config
  28. {
  29. /**
  30. * @var string default config source
  31. */
  32. var $default_source = './libraries/config.default.php';
  33. /**
  34. * @var array default configuration settings
  35. */
  36. var $default = array();
  37. /**
  38. * @var array configuration settings, without user preferences applied
  39. */
  40. var $base_settings = array();
  41. /**
  42. * @var array configuration settings
  43. */
  44. var $settings = array();
  45. /**
  46. * @var string config source
  47. */
  48. var $source = '';
  49. /**
  50. * @var int source modification time
  51. */
  52. var $source_mtime = 0;
  53. var $default_source_mtime = 0;
  54. var $set_mtime = 0;
  55. /**
  56. * @var boolean
  57. */
  58. var $error_config_file = false;
  59. /**
  60. * @var boolean
  61. */
  62. var $error_config_default_file = false;
  63. /**
  64. * @var array
  65. */
  66. var $default_server = array();
  67. /**
  68. * @var boolean whether init is done or not
  69. * set this to false to force some initial checks
  70. * like checking for required functions
  71. */
  72. var $done = false;
  73. /**
  74. * @var UserPreferences
  75. */
  76. private $userPreferences;
  77. /**
  78. * constructor
  79. *
  80. * @param string $source source to read config from
  81. */
  82. public function __construct($source = null)
  83. {
  84. $this->settings = array('is_setup' => false);
  85. // functions need to refresh in case of config file changed goes in
  86. // PhpMyAdmin\Config::load()
  87. $this->load($source);
  88. // other settings, independent from config file, comes in
  89. $this->checkSystem();
  90. $this->base_settings = $this->settings;
  91. $this->userPreferences = new UserPreferences();
  92. }
  93. /**
  94. * sets system and application settings
  95. *
  96. * @return void
  97. */
  98. public function checkSystem()
  99. {
  100. $this->set('PMA_VERSION', '4.8.5');
  101. /* Major version */
  102. $this->set(
  103. 'PMA_MAJOR_VERSION',
  104. implode('.', array_slice(explode('.', $this->get('PMA_VERSION'), 3), 0, 2))
  105. );
  106. $this->checkWebServerOs();
  107. $this->checkWebServer();
  108. $this->checkGd2();
  109. $this->checkClient();
  110. $this->checkUpload();
  111. $this->checkUploadSize();
  112. $this->checkOutputCompression();
  113. }
  114. /**
  115. * whether to use gzip output compression or not
  116. *
  117. * @return void
  118. */
  119. public function checkOutputCompression()
  120. {
  121. // If zlib output compression is set in the php configuration file, no
  122. // output buffering should be run
  123. if (ini_get('zlib.output_compression')) {
  124. $this->set('OBGzip', false);
  125. }
  126. // enable output-buffering (if set to 'auto')
  127. if (strtolower($this->get('OBGzip')) == 'auto') {
  128. $this->set('OBGzip', true);
  129. }
  130. }
  131. /**
  132. * Sets the client platform based on user agent
  133. *
  134. * @param string $user_agent the user agent
  135. *
  136. * @return void
  137. */
  138. private function _setClientPlatform($user_agent)
  139. {
  140. if (mb_strstr($user_agent, 'Win')) {
  141. $this->set('PMA_USR_OS', 'Win');
  142. } elseif (mb_strstr($user_agent, 'Mac')) {
  143. $this->set('PMA_USR_OS', 'Mac');
  144. } elseif (mb_strstr($user_agent, 'Linux')) {
  145. $this->set('PMA_USR_OS', 'Linux');
  146. } elseif (mb_strstr($user_agent, 'Unix')) {
  147. $this->set('PMA_USR_OS', 'Unix');
  148. } elseif (mb_strstr($user_agent, 'OS/2')) {
  149. $this->set('PMA_USR_OS', 'OS/2');
  150. } else {
  151. $this->set('PMA_USR_OS', 'Other');
  152. }
  153. }
  154. /**
  155. * Determines platform (OS), browser and version of the user
  156. * Based on a phpBuilder article:
  157. *
  158. * @see http://www.phpbuilder.net/columns/tim20000821.php
  159. *
  160. * @return void
  161. */
  162. public function checkClient()
  163. {
  164. if (Core::getenv('HTTP_USER_AGENT')) {
  165. $HTTP_USER_AGENT = Core::getenv('HTTP_USER_AGENT');
  166. } else {
  167. $HTTP_USER_AGENT = '';
  168. }
  169. // 1. Platform
  170. $this->_setClientPlatform($HTTP_USER_AGENT);
  171. // 2. browser and version
  172. // (must check everything else before Mozilla)
  173. $is_mozilla = preg_match(
  174. '@Mozilla/([0-9]\.[0-9]{1,2})@',
  175. $HTTP_USER_AGENT,
  176. $mozilla_version
  177. );
  178. if (preg_match(
  179. '@Opera(/| )([0-9]\.[0-9]{1,2})@',
  180. $HTTP_USER_AGENT,
  181. $log_version
  182. )) {
  183. $this->set('PMA_USR_BROWSER_VER', $log_version[2]);
  184. $this->set('PMA_USR_BROWSER_AGENT', 'OPERA');
  185. } elseif (preg_match(
  186. '@(MS)?IE ([0-9]{1,2}\.[0-9]{1,2})@',
  187. $HTTP_USER_AGENT,
  188. $log_version
  189. )) {
  190. $this->set('PMA_USR_BROWSER_VER', $log_version[2]);
  191. $this->set('PMA_USR_BROWSER_AGENT', 'IE');
  192. } elseif (preg_match(
  193. '@Trident/(7)\.0@',
  194. $HTTP_USER_AGENT,
  195. $log_version
  196. )) {
  197. $this->set('PMA_USR_BROWSER_VER', intval($log_version[1]) + 4);
  198. $this->set('PMA_USR_BROWSER_AGENT', 'IE');
  199. } elseif (preg_match(
  200. '@OmniWeb/([0-9]{1,3})@',
  201. $HTTP_USER_AGENT,
  202. $log_version
  203. )) {
  204. $this->set('PMA_USR_BROWSER_VER', $log_version[1]);
  205. $this->set('PMA_USR_BROWSER_AGENT', 'OMNIWEB');
  206. // Konqueror 2.2.2 says Konqueror/2.2.2
  207. // Konqueror 3.0.3 says Konqueror/3
  208. } elseif (preg_match(
  209. '@(Konqueror/)(.*)(;)@',
  210. $HTTP_USER_AGENT,
  211. $log_version
  212. )) {
  213. $this->set('PMA_USR_BROWSER_VER', $log_version[2]);
  214. $this->set('PMA_USR_BROWSER_AGENT', 'KONQUEROR');
  215. // must check Chrome before Safari
  216. } elseif ($is_mozilla
  217. && preg_match('@Chrome/([0-9.]*)@', $HTTP_USER_AGENT, $log_version)
  218. ) {
  219. $this->set('PMA_USR_BROWSER_VER', $log_version[1]);
  220. $this->set('PMA_USR_BROWSER_AGENT', 'CHROME');
  221. // newer Safari
  222. } elseif ($is_mozilla
  223. && preg_match('@Version/(.*) Safari@', $HTTP_USER_AGENT, $log_version)
  224. ) {
  225. $this->set(
  226. 'PMA_USR_BROWSER_VER', $log_version[1]
  227. );
  228. $this->set('PMA_USR_BROWSER_AGENT', 'SAFARI');
  229. // older Safari
  230. } elseif ($is_mozilla
  231. && preg_match('@Safari/([0-9]*)@', $HTTP_USER_AGENT, $log_version)
  232. ) {
  233. $this->set(
  234. 'PMA_USR_BROWSER_VER', $mozilla_version[1] . '.' . $log_version[1]
  235. );
  236. $this->set('PMA_USR_BROWSER_AGENT', 'SAFARI');
  237. // Firefox
  238. } elseif (! mb_strstr($HTTP_USER_AGENT, 'compatible')
  239. && preg_match('@Firefox/([\w.]+)@', $HTTP_USER_AGENT, $log_version)
  240. ) {
  241. $this->set(
  242. 'PMA_USR_BROWSER_VER', $log_version[1]
  243. );
  244. $this->set('PMA_USR_BROWSER_AGENT', 'FIREFOX');
  245. } elseif (preg_match('@rv:1\.9(.*)Gecko@', $HTTP_USER_AGENT)) {
  246. $this->set('PMA_USR_BROWSER_VER', '1.9');
  247. $this->set('PMA_USR_BROWSER_AGENT', 'GECKO');
  248. } elseif ($is_mozilla) {
  249. $this->set('PMA_USR_BROWSER_VER', $mozilla_version[1]);
  250. $this->set('PMA_USR_BROWSER_AGENT', 'MOZILLA');
  251. } else {
  252. $this->set('PMA_USR_BROWSER_VER', 0);
  253. $this->set('PMA_USR_BROWSER_AGENT', 'OTHER');
  254. }
  255. }
  256. /**
  257. * Whether GD2 is present
  258. *
  259. * @return void
  260. */
  261. public function checkGd2()
  262. {
  263. if ($this->get('GD2Available') == 'yes') {
  264. $this->set('PMA_IS_GD2', 1);
  265. return;
  266. }
  267. if ($this->get('GD2Available') == 'no') {
  268. $this->set('PMA_IS_GD2', 0);
  269. return;
  270. }
  271. if (!function_exists('imagecreatetruecolor')) {
  272. $this->set('PMA_IS_GD2', 0);
  273. return;
  274. }
  275. if (function_exists('gd_info')) {
  276. $gd_nfo = gd_info();
  277. if (mb_strstr($gd_nfo["GD Version"], '2.')) {
  278. $this->set('PMA_IS_GD2', 1);
  279. } else {
  280. $this->set('PMA_IS_GD2', 0);
  281. }
  282. } else {
  283. $this->set('PMA_IS_GD2', 0);
  284. }
  285. }
  286. /**
  287. * Whether the Web server php is running on is IIS
  288. *
  289. * @return void
  290. */
  291. public function checkWebServer()
  292. {
  293. // some versions return Microsoft-IIS, some Microsoft/IIS
  294. // we could use a preg_match() but it's slower
  295. if (Core::getenv('SERVER_SOFTWARE')
  296. && stristr(Core::getenv('SERVER_SOFTWARE'), 'Microsoft')
  297. && stristr(Core::getenv('SERVER_SOFTWARE'), 'IIS')
  298. ) {
  299. $this->set('PMA_IS_IIS', 1);
  300. } else {
  301. $this->set('PMA_IS_IIS', 0);
  302. }
  303. }
  304. /**
  305. * Whether the os php is running on is windows or not
  306. *
  307. * @return void
  308. */
  309. public function checkWebServerOs()
  310. {
  311. // Default to Unix or Equiv
  312. $this->set('PMA_IS_WINDOWS', 0);
  313. // If PHP_OS is defined then continue
  314. if (defined('PHP_OS')) {
  315. if (stristr(PHP_OS, 'win') && !stristr(PHP_OS, 'darwin')) {
  316. // Is it some version of Windows
  317. $this->set('PMA_IS_WINDOWS', 1);
  318. } elseif (stristr(PHP_OS, 'OS/2')) {
  319. // Is it OS/2 (No file permissions like Windows)
  320. $this->set('PMA_IS_WINDOWS', 1);
  321. }
  322. }
  323. }
  324. /**
  325. * detects if Git revision
  326. * @param string &$git_location (optional) verified git directory
  327. * @return boolean
  328. */
  329. public function isGitRevision(&$git_location = NULL)
  330. {
  331. // PMA config check
  332. if (! $this->get('ShowGitRevision')) {
  333. return false;
  334. }
  335. // caching
  336. if (
  337. isset($_SESSION['is_git_revision'])
  338. && array_key_exists('git_location', $_SESSION)
  339. ) {
  340. // Define location using cached value
  341. $git_location = $_SESSION['git_location'];
  342. return $_SESSION['is_git_revision'];
  343. }
  344. // find out if there is a .git folder
  345. // or a .git file (--separate-git-dir)
  346. $git = '.git';
  347. if (is_dir($git)) {
  348. if (@is_file($git . '/config')) {
  349. $git_location = $git;
  350. } else {
  351. $_SESSION['git_location'] = null;
  352. $_SESSION['is_git_revision'] = false;
  353. return false;
  354. }
  355. } elseif (is_file($git)) {
  356. $contents = file_get_contents($git);
  357. $gitmatch = array();
  358. // Matches expected format
  359. if (! preg_match('/^gitdir: (.*)$/',
  360. $contents, $gitmatch)) {
  361. $_SESSION['git_location'] = null;
  362. $_SESSION['is_git_revision'] = false;
  363. return false;
  364. } else {
  365. if (@is_dir($gitmatch[1])) {
  366. //Detected git external folder location
  367. $git_location = $gitmatch[1];
  368. } else {
  369. $_SESSION['git_location'] = null;
  370. $_SESSION['is_git_revision'] = false;
  371. return false;
  372. }
  373. }
  374. } else {
  375. $_SESSION['git_location'] = null;
  376. $_SESSION['is_git_revision'] = false;
  377. return false;
  378. }
  379. // Define session for caching
  380. $_SESSION['git_location'] = $git_location;
  381. $_SESSION['is_git_revision'] = true;
  382. return true;
  383. }
  384. /**
  385. * detects Git revision, if running inside repo
  386. *
  387. * @return void
  388. */
  389. public function checkGitRevision()
  390. {
  391. // find out if there is a .git folder
  392. $git_folder = '';
  393. if (! $this->isGitRevision($git_folder)) {
  394. $this->set('PMA_VERSION_GIT', 0);
  395. return;
  396. }
  397. if (! $ref_head = @file_get_contents($git_folder . '/HEAD')) {
  398. $this->set('PMA_VERSION_GIT', 0);
  399. return;
  400. }
  401. if ($common_dir_contents = @file_get_contents($git_folder . '/commondir')) {
  402. $git_folder = $git_folder . DIRECTORY_SEPARATOR . trim($common_dir_contents);
  403. }
  404. $branch = false;
  405. // are we on any branch?
  406. if (strstr($ref_head, '/')) {
  407. // remove ref: prefix
  408. $ref_head = substr(trim($ref_head), 5);
  409. if (substr($ref_head, 0, 11) === 'refs/heads/') {
  410. $branch = substr($ref_head, 11);
  411. } else {
  412. $branch = basename($ref_head);
  413. }
  414. $ref_file = $git_folder . '/' . $ref_head;
  415. if (@file_exists($ref_file)) {
  416. $hash = @file_get_contents($ref_file);
  417. if (! $hash) {
  418. $this->set('PMA_VERSION_GIT', 0);
  419. return;
  420. }
  421. $hash = trim($hash);
  422. } else {
  423. // deal with packed refs
  424. $packed_refs = @file_get_contents($git_folder . '/packed-refs');
  425. if (! $packed_refs) {
  426. $this->set('PMA_VERSION_GIT', 0);
  427. return;
  428. }
  429. // split file to lines
  430. $ref_lines = explode("\n", $packed_refs);
  431. foreach ($ref_lines as $line) {
  432. // skip comments
  433. if ($line[0] == '#') {
  434. continue;
  435. }
  436. // parse line
  437. $parts = explode(' ', $line);
  438. // care only about named refs
  439. if (count($parts) != 2) {
  440. continue;
  441. }
  442. // have found our ref?
  443. if ($parts[1] == $ref_head) {
  444. $hash = $parts[0];
  445. break;
  446. }
  447. }
  448. if (! isset($hash)) {
  449. $this->set('PMA_VERSION_GIT', 0);
  450. // Could not find ref
  451. return;
  452. }
  453. }
  454. } else {
  455. $hash = trim($ref_head);
  456. }
  457. $commit = false;
  458. if (! preg_match('/^[0-9a-f]{40}$/i', $hash)) {
  459. $commit = false;
  460. } elseif (isset($_SESSION['PMA_VERSION_COMMITDATA_' . $hash])) {
  461. $commit = $_SESSION['PMA_VERSION_COMMITDATA_' . $hash];
  462. } elseif (function_exists('gzuncompress')) {
  463. $git_file_name = $git_folder . '/objects/'
  464. . substr($hash, 0, 2) . '/' . substr($hash, 2);
  465. if (@file_exists($git_file_name) ) {
  466. if (! $commit = @file_get_contents($git_file_name)) {
  467. $this->set('PMA_VERSION_GIT', 0);
  468. return;
  469. }
  470. $commit = explode("\0", gzuncompress($commit), 2);
  471. $commit = explode("\n", $commit[1]);
  472. $_SESSION['PMA_VERSION_COMMITDATA_' . $hash] = $commit;
  473. } else {
  474. $pack_names = array();
  475. // work with packed data
  476. $packs_file = $git_folder . '/objects/info/packs';
  477. if (@file_exists($packs_file)
  478. && $packs = @file_get_contents($packs_file)
  479. ) {
  480. // File exists. Read it, parse the file to get the names of the
  481. // packs. (to look for them in .git/object/pack directory later)
  482. foreach (explode("\n", $packs) as $line) {
  483. // skip blank lines
  484. if (strlen(trim($line)) == 0) {
  485. continue;
  486. }
  487. // skip non pack lines
  488. if ($line[0] != 'P') {
  489. continue;
  490. }
  491. // parse names
  492. $pack_names[] = substr($line, 2);
  493. }
  494. } else {
  495. // '.git/objects/info/packs' file can be missing
  496. // (atlease in mysGit)
  497. // File missing. May be we can look in the .git/object/pack
  498. // directory for all the .pack files and use that list of
  499. // files instead
  500. $dirIterator = new DirectoryIterator(
  501. $git_folder . '/objects/pack'
  502. );
  503. foreach ($dirIterator as $file_info) {
  504. $file_name = $file_info->getFilename();
  505. // if this is a .pack file
  506. if ($file_info->isFile() && substr($file_name, -5) == '.pack'
  507. ) {
  508. $pack_names[] = $file_name;
  509. }
  510. }
  511. }
  512. $hash = strtolower($hash);
  513. foreach ($pack_names as $pack_name) {
  514. $index_name = str_replace('.pack', '.idx', $pack_name);
  515. // load index
  516. $index_data = @file_get_contents(
  517. $git_folder . '/objects/pack/' . $index_name
  518. );
  519. if (! $index_data) {
  520. continue;
  521. }
  522. // check format
  523. if (substr($index_data, 0, 4) != "\377tOc") {
  524. continue;
  525. }
  526. // check version
  527. $version = unpack('N', substr($index_data, 4, 4));
  528. if ($version[1] != 2) {
  529. continue;
  530. }
  531. // parse fanout table
  532. $fanout = unpack(
  533. "N*",
  534. substr($index_data, 8, 256 * 4)
  535. );
  536. // find where we should search
  537. $firstbyte = intval(substr($hash, 0, 2), 16);
  538. // array is indexed from 1 and we need to get
  539. // previous entry for start
  540. if ($firstbyte == 0) {
  541. $start = 0;
  542. } else {
  543. $start = $fanout[$firstbyte];
  544. }
  545. $end = $fanout[$firstbyte + 1];
  546. // stupid linear search for our sha
  547. $found = false;
  548. $offset = 8 + (256 * 4);
  549. for ($position = $start; $position < $end; $position++) {
  550. $sha = strtolower(
  551. bin2hex(
  552. substr($index_data, $offset + ($position * 20), 20)
  553. )
  554. );
  555. if ($sha == $hash) {
  556. $found = true;
  557. break;
  558. }
  559. }
  560. if (! $found) {
  561. continue;
  562. }
  563. // read pack offset
  564. $offset = 8 + (256 * 4) + (24 * $fanout[256]);
  565. $pack_offset = unpack(
  566. 'N',
  567. substr($index_data, $offset + ($position * 4), 4)
  568. );
  569. $pack_offset = $pack_offset[1];
  570. // open pack file
  571. $pack_file = fopen(
  572. $git_folder . '/objects/pack/' . $pack_name, 'rb'
  573. );
  574. if ($pack_file === false) {
  575. continue;
  576. }
  577. // seek to start
  578. fseek($pack_file, $pack_offset);
  579. // parse header
  580. $header = ord(fread($pack_file, 1));
  581. $type = ($header >> 4) & 7;
  582. $hasnext = ($header & 128) >> 7;
  583. $size = $header & 0xf;
  584. $offset = 4;
  585. while ($hasnext) {
  586. $byte = ord(fread($pack_file, 1));
  587. $size |= ($byte & 0x7f) << $offset;
  588. $hasnext = ($byte & 128) >> 7;
  589. $offset += 7;
  590. }
  591. // we care only about commit objects
  592. if ($type != 1) {
  593. continue;
  594. }
  595. // read data
  596. $commit = fread($pack_file, $size);
  597. $commit = gzuncompress($commit);
  598. $commit = explode("\n", $commit);
  599. $_SESSION['PMA_VERSION_COMMITDATA_' . $hash] = $commit;
  600. fclose($pack_file);
  601. }
  602. }
  603. }
  604. $httpRequest = new HttpRequest();
  605. // check if commit exists in Github
  606. if ($commit !== false
  607. && isset($_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash])
  608. ) {
  609. $is_remote_commit = $_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash];
  610. } else {
  611. $link = 'https://www.phpmyadmin.net/api/commit/' . $hash . '/';
  612. $is_found = $httpRequest->create($link, 'GET');
  613. switch($is_found) {
  614. case false:
  615. $is_remote_commit = false;
  616. $_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash] = false;
  617. break;
  618. case null:
  619. // no remote link for now, but don't cache this as Github is down
  620. $is_remote_commit = false;
  621. break;
  622. default:
  623. $is_remote_commit = true;
  624. $_SESSION['PMA_VERSION_REMOTECOMMIT_' . $hash] = true;
  625. if ($commit === false) {
  626. // if no local commit data, try loading from Github
  627. $commit_json = json_decode($is_found);
  628. }
  629. break;
  630. }
  631. }
  632. $is_remote_branch = false;
  633. if ($is_remote_commit && $branch !== false) {
  634. // check if branch exists in Github
  635. if (isset($_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash])) {
  636. $is_remote_branch = $_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash];
  637. } else {
  638. $link = 'https://www.phpmyadmin.net/api/tree/' . $branch . '/';
  639. $is_found = $httpRequest->create($link, 'GET', true);
  640. switch($is_found) {
  641. case true:
  642. $is_remote_branch = true;
  643. $_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash] = true;
  644. break;
  645. case false:
  646. $is_remote_branch = false;
  647. $_SESSION['PMA_VERSION_REMOTEBRANCH_' . $hash] = false;
  648. break;
  649. case null:
  650. // no remote link for now, but don't cache this as Github is down
  651. $is_remote_branch = false;
  652. break;
  653. }
  654. }
  655. }
  656. if ($commit !== false) {
  657. $author = array('name' => '', 'email' => '', 'date' => '');
  658. $committer = array('name' => '', 'email' => '', 'date' => '');
  659. do {
  660. $dataline = array_shift($commit);
  661. $datalinearr = explode(' ', $dataline, 2);
  662. $linetype = $datalinearr[0];
  663. if (in_array($linetype, array('author', 'committer'))) {
  664. $user = $datalinearr[1];
  665. preg_match('/([^<]+)<([^>]+)> ([0-9]+)( [^ ]+)?/', $user, $user);
  666. $user2 = array(
  667. 'name' => trim($user[1]),
  668. 'email' => trim($user[2]),
  669. 'date' => date('Y-m-d H:i:s', $user[3]));
  670. if (isset($user[4])) {
  671. $user2['date'] .= $user[4];
  672. }
  673. $$linetype = $user2;
  674. }
  675. } while ($dataline != '');
  676. $message = trim(implode(' ', $commit));
  677. } elseif (isset($commit_json) && isset($commit_json->author) && isset($commit_json->committer) && isset($commit_json->message)) {
  678. $author = array(
  679. 'name' => $commit_json->author->name,
  680. 'email' => $commit_json->author->email,
  681. 'date' => $commit_json->author->date);
  682. $committer = array(
  683. 'name' => $commit_json->committer->name,
  684. 'email' => $commit_json->committer->email,
  685. 'date' => $commit_json->committer->date);
  686. $message = trim($commit_json->message);
  687. } else {
  688. $this->set('PMA_VERSION_GIT', 0);
  689. return;
  690. }
  691. $this->set('PMA_VERSION_GIT', 1);
  692. $this->set('PMA_VERSION_GIT_COMMITHASH', $hash);
  693. $this->set('PMA_VERSION_GIT_BRANCH', $branch);
  694. $this->set('PMA_VERSION_GIT_MESSAGE', $message);
  695. $this->set('PMA_VERSION_GIT_AUTHOR', $author);
  696. $this->set('PMA_VERSION_GIT_COMMITTER', $committer);
  697. $this->set('PMA_VERSION_GIT_ISREMOTECOMMIT', $is_remote_commit);
  698. $this->set('PMA_VERSION_GIT_ISREMOTEBRANCH', $is_remote_branch);
  699. }
  700. /**
  701. * loads default values from default source
  702. *
  703. * @return boolean success
  704. */
  705. public function loadDefaults()
  706. {
  707. $cfg = array();
  708. if (! @file_exists($this->default_source)) {
  709. $this->error_config_default_file = true;
  710. return false;
  711. }
  712. $old_error_reporting = error_reporting(0);
  713. ob_start();
  714. $GLOBALS['pma_config_loading'] = true;
  715. $eval_result = include $this->default_source;
  716. $GLOBALS['pma_config_loading'] = false;
  717. ob_end_clean();
  718. error_reporting($old_error_reporting);
  719. if ($eval_result === false) {
  720. $this->error_config_default_file = true;
  721. return false;
  722. }
  723. $this->default_source_mtime = filemtime($this->default_source);
  724. $this->default_server = $cfg['Servers'][1];
  725. unset($cfg['Servers']);
  726. $this->default = $cfg;
  727. $this->settings = array_replace_recursive($this->settings, $cfg);
  728. $this->error_config_default_file = false;
  729. return true;
  730. }
  731. /**
  732. * loads configuration from $source, usually the config file
  733. * should be called on object creation
  734. *
  735. * @param string $source config file
  736. *
  737. * @return bool
  738. */
  739. public function load($source = null)
  740. {
  741. $this->loadDefaults();
  742. if (null !== $source) {
  743. $this->setSource($source);
  744. }
  745. if (! $this->checkConfigSource()) {
  746. return false;
  747. }
  748. $cfg = array();
  749. /**
  750. * Parses the configuration file, we throw away any errors or
  751. * output.
  752. */
  753. $old_error_reporting = error_reporting(0);
  754. ob_start();
  755. $GLOBALS['pma_config_loading'] = true;
  756. $eval_result = include $this->getSource();
  757. $GLOBALS['pma_config_loading'] = false;
  758. ob_end_clean();
  759. error_reporting($old_error_reporting);
  760. if ($eval_result === false) {
  761. $this->error_config_file = true;
  762. } else {
  763. $this->error_config_file = false;
  764. $this->source_mtime = filemtime($this->getSource());
  765. }
  766. /**
  767. * Ignore keys with / as we do not use these
  768. *
  769. * These can be confusing for user configuration layer as it
  770. * flatten array using / and thus don't see difference between
  771. * $cfg['Export/method'] and $cfg['Export']['method'], while rest
  772. * of thre code uses the setting only in latter form.
  773. *
  774. * This could be removed once we consistently handle both values
  775. * in the functional code as well.
  776. *
  777. * It could use array_filter(...ARRAY_FILTER_USE_KEY), but it's not
  778. * supported on PHP 5.5 and HHVM.
  779. */
  780. $matched_keys = array_filter(
  781. array_keys($cfg),
  782. function ($key) {return strpos($key, '/') === false;}
  783. );
  784. $cfg = array_intersect_key($cfg, array_flip($matched_keys));
  785. /**
  786. * Backward compatibility code
  787. */
  788. if (!empty($cfg['DefaultTabTable'])) {
  789. $cfg['DefaultTabTable'] = str_replace(
  790. '_properties',
  791. '',
  792. str_replace(
  793. 'tbl_properties.php',
  794. 'tbl_sql.php',
  795. $cfg['DefaultTabTable']
  796. )
  797. );
  798. }
  799. if (!empty($cfg['DefaultTabDatabase'])) {
  800. $cfg['DefaultTabDatabase'] = str_replace(
  801. '_details',
  802. '',
  803. str_replace(
  804. 'db_details.php',
  805. 'db_sql.php',
  806. $cfg['DefaultTabDatabase']
  807. )
  808. );
  809. }
  810. $this->settings = array_replace_recursive($this->settings, $cfg);
  811. return true;
  812. }
  813. /**
  814. * Sets the connection collation
  815. *
  816. * @return void
  817. */
  818. private function _setConnectionCollation()
  819. {
  820. $collation_connection = $this->get('DefaultConnectionCollation');
  821. if (! empty($collation_connection)
  822. && $collation_connection != $GLOBALS['collation_connection']
  823. ) {
  824. $GLOBALS['dbi']->setCollation($collation_connection);
  825. }
  826. }
  827. /**
  828. * Loads user preferences and merges them with current config
  829. * must be called after control connection has been established
  830. *
  831. * @return void
  832. */
  833. public function loadUserPreferences()
  834. {
  835. // index.php should load these settings, so that phpmyadmin.css.php
  836. // will have everything available in session cache
  837. $server = isset($GLOBALS['server'])
  838. ? $GLOBALS['server']
  839. : (!empty($GLOBALS['cfg']['ServerDefault'])
  840. ? $GLOBALS['cfg']['ServerDefault']
  841. : 0);
  842. $cache_key = 'server_' . $server;
  843. if ($server > 0 && !defined('PMA_MINIMUM_COMMON')) {
  844. $config_mtime = max($this->default_source_mtime, $this->source_mtime);
  845. // cache user preferences, use database only when needed
  846. if (! isset($_SESSION['cache'][$cache_key]['userprefs'])
  847. || $_SESSION['cache'][$cache_key]['config_mtime'] < $config_mtime
  848. ) {
  849. $prefs = $this->userPreferences->load();
  850. $_SESSION['cache'][$cache_key]['userprefs']
  851. = $this->userPreferences->apply($prefs['config_data']);
  852. $_SESSION['cache'][$cache_key]['userprefs_mtime'] = $prefs['mtime'];
  853. $_SESSION['cache'][$cache_key]['userprefs_type'] = $prefs['type'];
  854. $_SESSION['cache'][$cache_key]['config_mtime'] = $config_mtime;
  855. }
  856. } elseif ($server == 0
  857. || ! isset($_SESSION['cache'][$cache_key]['userprefs'])
  858. ) {
  859. $this->set('user_preferences', false);
  860. return;
  861. }
  862. $config_data = $_SESSION['cache'][$cache_key]['userprefs'];
  863. // type is 'db' or 'session'
  864. $this->set(
  865. 'user_preferences',
  866. $_SESSION['cache'][$cache_key]['userprefs_type']
  867. );
  868. $this->set(
  869. 'user_preferences_mtime',
  870. $_SESSION['cache'][$cache_key]['userprefs_mtime']
  871. );
  872. // load config array
  873. $this->settings = array_replace_recursive($this->settings, $config_data);
  874. $GLOBALS['cfg'] = array_replace_recursive($GLOBALS['cfg'], $config_data);
  875. if (defined('PMA_MINIMUM_COMMON')) {
  876. return;
  877. }
  878. // settings below start really working on next page load, but
  879. // changes are made only in index.php so everything is set when
  880. // in frames
  881. // save theme
  882. /** @var ThemeManager $tmanager */
  883. $tmanager = ThemeManager::getInstance();
  884. if ($tmanager->getThemeCookie() || isset($_REQUEST['set_theme'])) {
  885. if ((! isset($config_data['ThemeDefault'])
  886. && $tmanager->theme->getId() != 'original')
  887. || isset($config_data['ThemeDefault'])
  888. && $config_data['ThemeDefault'] != $tmanager->theme->getId()
  889. ) {
  890. // new theme was set in common.inc.php
  891. $this->setUserValue(
  892. null,
  893. 'ThemeDefault',
  894. $tmanager->theme->getId(),
  895. 'original'
  896. );
  897. }
  898. } else {
  899. // no cookie - read default from settings
  900. if ($this->settings['ThemeDefault'] != $tmanager->theme->getId()
  901. && $tmanager->checkTheme($this->settings['ThemeDefault'])
  902. ) {
  903. $tmanager->setActiveTheme($this->settings['ThemeDefault']);
  904. $tmanager->setThemeCookie();
  905. }
  906. }
  907. // save language
  908. if (isset($_COOKIE['pma_lang']) || isset($_POST['lang'])) {
  909. if ((! isset($config_data['lang'])
  910. && $GLOBALS['lang'] != 'en')
  911. || isset($config_data['lang'])
  912. && $GLOBALS['lang'] != $config_data['lang']
  913. ) {
  914. $this->setUserValue(null, 'lang', $GLOBALS['lang'], 'en');
  915. }
  916. } else {
  917. // read language from settings
  918. if (isset($config_data['lang'])) {
  919. $language = LanguageManager::getInstance()->getLanguage(
  920. $config_data['lang']
  921. );
  922. if ($language !== false) {
  923. $language->activate();
  924. $this->setCookie('pma_lang', $language->getCode());
  925. }
  926. }
  927. }
  928. // set connection collation
  929. $this->_setConnectionCollation();
  930. }
  931. /**
  932. * Sets config value which is stored in user preferences (if available)
  933. * or in a cookie.
  934. *
  935. * If user preferences are not yet initialized, option is applied to
  936. * global config and added to a update queue, which is processed
  937. * by {@link loadUserPreferences()}
  938. *
  939. * @param string $cookie_name can be null
  940. * @param string $cfg_path configuration path
  941. * @param mixed $new_cfg_value new value
  942. * @param mixed $default_value default value
  943. *
  944. * @return true|PhpMyAdmin\Message
  945. */
  946. public function setUserValue($cookie_name, $cfg_path, $new_cfg_value,
  947. $default_value = null
  948. ) {
  949. $result = true;
  950. // use permanent user preferences if possible
  951. $prefs_type = $this->get('user_preferences');
  952. if ($prefs_type) {
  953. if ($default_value === null) {
  954. $default_value = Core::arrayRead($cfg_path, $this->default);
  955. }
  956. $result = $this->userPreferences->persistOption($cfg_path, $new_cfg_value, $default_value);
  957. }
  958. if ($prefs_type != 'db' && $cookie_name) {
  959. // fall back to cookies
  960. if ($default_value === null) {
  961. $default_value = Core::arrayRead($cfg_path, $this->settings);
  962. }
  963. $this->setCookie($cookie_name, $new_cfg_value, $default_value);
  964. }
  965. Core::arrayWrite($cfg_path, $GLOBALS['cfg'], $new_cfg_value);
  966. Core::arrayWrite($cfg_path, $this->settings, $new_cfg_value);
  967. return $result;
  968. }
  969. /**
  970. * Reads value stored by {@link setUserValue()}
  971. *
  972. * @param string $cookie_name cookie name
  973. * @param mixed $cfg_value config value
  974. *
  975. * @return mixed
  976. */
  977. public function getUserValue($cookie_name, $cfg_value)
  978. {
  979. $cookie_exists = isset($_COOKIE) && !empty($_COOKIE[$cookie_name]);
  980. $prefs_type = $this->get('user_preferences');
  981. if ($prefs_type == 'db') {
  982. // permanent user preferences value exists, remove cookie
  983. if ($cookie_exists) {
  984. $this->removeCookie($cookie_name);
  985. }
  986. } elseif ($cookie_exists) {
  987. return $_COOKIE[$cookie_name];
  988. }
  989. // return value from $cfg array
  990. return $cfg_value;
  991. }
  992. /**
  993. * set source
  994. *
  995. * @param string $source source
  996. *
  997. * @return void
  998. */
  999. public function setSource($source)
  1000. {
  1001. $this->source = trim($source);
  1002. }
  1003. /**
  1004. * check config source
  1005. *
  1006. * @return boolean whether source is valid or not
  1007. */
  1008. public function checkConfigSource()
  1009. {
  1010. if (! $this->getSource()) {
  1011. // no configuration file set at all
  1012. return false;
  1013. }
  1014. if (! @file_exists($this->getSource())) {
  1015. $this->source_mtime = 0;
  1016. return false;
  1017. }
  1018. if (! @is_readable($this->getSource())) {
  1019. // manually check if file is readable
  1020. // might be bug #3059806 Supporting running from CIFS/Samba shares
  1021. $contents = false;
  1022. $handle = @fopen($this->getSource(), 'r');
  1023. if ($handle !== false) {
  1024. $contents = @fread($handle, 1); // reading 1 byte is enough to test
  1025. fclose($handle);
  1026. }
  1027. if ($contents === false) {
  1028. $this->source_mtime = 0;
  1029. Core::fatalError(
  1030. sprintf(
  1031. function_exists('__')
  1032. ? __('Existing configuration file (%s) is not readable.')
  1033. : 'Existing configuration file (%s) is not readable.',
  1034. $this->getSource()
  1035. )
  1036. );
  1037. return false;
  1038. }
  1039. }
  1040. return true;
  1041. }
  1042. /**
  1043. * verifies the permissions on config file (if asked by configuration)
  1044. * (must be called after config.inc.php has been merged)
  1045. *
  1046. * @return void
  1047. */
  1048. public function checkPermissions()
  1049. {
  1050. // Check for permissions (on platforms that support it):
  1051. if ($this->get('CheckConfigurationPermissions') && @file_exists($this->getSource())) {
  1052. $perms = @fileperms($this->getSource());
  1053. if (!($perms === false) && ($perms & 2)) {
  1054. // This check is normally done after loading configuration
  1055. $this->checkWebServerOs();
  1056. if ($this->get('PMA_IS_WINDOWS') == 0) {
  1057. $this->source_mtime = 0;
  1058. Core::fatalError(
  1059. __(
  1060. 'Wrong permissions on configuration file, '
  1061. . 'should not be world writable!'
  1062. )
  1063. );
  1064. }
  1065. }
  1066. }
  1067. }
  1068. /**
  1069. * Checks for errors
  1070. * (must be called after config.inc.php has been merged)
  1071. *
  1072. * @return void
  1073. */
  1074. public function checkErrors()
  1075. {
  1076. if ($this->error_config_default_file) {
  1077. Core::fatalError(
  1078. sprintf(
  1079. __('Could not load default configuration from: %1$s'),
  1080. $this->default_source
  1081. )
  1082. );
  1083. }
  1084. if ($this->error_config_file) {
  1085. $error = '[strong]' . __('Failed to read configuration file!') . '[/strong]'
  1086. . '[br][br]'
  1087. . __(
  1088. 'This usually means there is a syntax error in it, '
  1089. . 'please check any errors shown below.'
  1090. )
  1091. . '[br][br]'
  1092. . '[conferr]';
  1093. trigger_error($error, E_USER_ERROR);
  1094. }
  1095. }
  1096. /**
  1097. * returns specific config setting
  1098. *
  1099. * @param string $setting config setting
  1100. *
  1101. * @return mixed value
  1102. */
  1103. public function get($setting)
  1104. {
  1105. if (isset($this->settings[$setting])) {
  1106. return $this->settings[$setting];
  1107. }
  1108. return null;
  1109. }
  1110. /**
  1111. * sets configuration variable
  1112. *
  1113. * @param string $setting configuration option
  1114. * @param mixed $value new value for configuration option
  1115. *
  1116. * @return void
  1117. */
  1118. public function set($setting, $value)
  1119. {
  1120. if (! isset($this->settings[$setting])
  1121. || $this->settings[$setting] !== $value
  1122. ) {
  1123. $this->settings[$setting] = $value;
  1124. $this->set_mtime = time();
  1125. }
  1126. }
  1127. /**
  1128. * returns source for current config
  1129. *
  1130. * @return string config source
  1131. */
  1132. public function getSource()
  1133. {
  1134. return $this->source;
  1135. }
  1136. /**
  1137. * returns a unique value to force a CSS reload if either the config
  1138. * or the theme changes
  1139. *
  1140. * @return int Summary of unix timestamps and fontsize,
  1141. * to be unique on theme parameters change
  1142. */
  1143. public function getThemeUniqueValue()
  1144. {
  1145. if (null !== $this->get('FontSize')) {
  1146. $fontsize = intval($this->get('FontSize'));
  1147. } else {
  1148. $fontsize = 0;
  1149. }
  1150. return (
  1151. $fontsize +
  1152. $this->source_mtime +
  1153. $this->default_source_mtime +
  1154. $this->get('user_preferences_mtime') +
  1155. $GLOBALS['PMA_Theme']->mtime_info +
  1156. $GLOBALS['PMA_Theme']->filesize_info);
  1157. }
  1158. /**
  1159. * checks if upload is enabled
  1160. *
  1161. * @return void
  1162. */
  1163. public function checkUpload()
  1164. {
  1165. if (!ini_get('file_uploads')) {
  1166. $this->set('enable_upload', false);
  1167. return;
  1168. }
  1169. $this->set('enable_upload', true);
  1170. // if set "php_admin_value file_uploads Off" in httpd.conf
  1171. // ini_get() also returns the string "Off" in this case:
  1172. if ('off' == strtolower(ini_get('file_uploads'))) {
  1173. $this->set('enable_upload', false);
  1174. }
  1175. }
  1176. /**
  1177. * Maximum upload size as limited by PHP
  1178. * Used with permission from Moodle (https://moodle.org/) by Martin Dougiamas
  1179. *
  1180. * this section generates $max_upload_size in bytes
  1181. *
  1182. * @return void
  1183. */
  1184. public function checkUploadSize()
  1185. {
  1186. if (! $filesize = ini_get('upload_max_filesize')) {
  1187. $filesize = "5M";
  1188. }
  1189. if ($postsize = ini_get('post_max_size')) {
  1190. $this->set(
  1191. 'max_upload_size',
  1192. min(Core::getRealSize($filesize), Core::getRealSize($postsize))
  1193. );
  1194. } else {
  1195. $this->set('max_upload_size', Core::getRealSize($filesize));
  1196. }
  1197. }
  1198. /**
  1199. * Checks if protocol is https
  1200. *
  1201. * This function checks if the https protocol on the active connection.
  1202. *
  1203. * @return bool
  1204. */
  1205. public function isHttps()
  1206. {
  1207. if (null !== $this->get('is_https')) {
  1208. return $this->get('is_https');
  1209. }
  1210. $url = $this->get('PmaAbsoluteUri');
  1211. $is_https = false;
  1212. if (! empty($url) && parse_url($url, PHP_URL_SCHEME) === 'https') {
  1213. $is_https = true;
  1214. } elseif (strtolower(Core::getenv('HTTP_SCHEME')) == 'https') {
  1215. $is_https = true;
  1216. } elseif (strtolower(Core::getenv('HTTPS')) == 'on') {
  1217. $is_https = true;
  1218. } elseif (substr(strtolower(Core::getenv('REQUEST_URI')), 0, 6) == 'https:') {
  1219. $is_https = true;
  1220. } elseif (strtolower(Core::getenv('HTTP_HTTPS_FROM_LB')) == 'on') {
  1221. // A10 Networks load balancer
  1222. $is_https = true;
  1223. } elseif (strtolower(Core::getenv('HTTP_FRONT_END_HTTPS')) == 'on') {
  1224. $is_https = true;
  1225. } elseif (strtolower(Core::getenv('HTTP_X_FORWARDED_PROTO')) == 'https') {
  1226. $is_https = true;
  1227. } elseif (Core::getenv('SERVER_PORT') == 443) {
  1228. $is_https = true;
  1229. }
  1230. $this->set('is_https', $is_https);
  1231. return $is_https;
  1232. }
  1233. /**
  1234. * Get phpMyAdmin root path
  1235. *
  1236. * @return string
  1237. */
  1238. public function getRootPath()
  1239. {
  1240. static $cookie_path = null;
  1241. if (null !== $cookie_path && !defined('TESTSUITE')) {
  1242. return $cookie_path;
  1243. }
  1244. $url = $this->get('PmaAbsoluteUri');
  1245. if (! empty($url)) {
  1246. $path = parse_url($url, PHP_URL_PATH);
  1247. if (! empty($path)) {
  1248. if (substr($path, -1) != '/') {
  1249. return $path . '/';
  1250. }
  1251. return $path;
  1252. }
  1253. }
  1254. $parsed_url = parse_url($GLOBALS['PMA_PHP_SELF']);
  1255. $parts = explode(
  1256. '/',
  1257. rtrim(str_replace('\\', '/', $parsed_url['path']), '/')
  1258. );
  1259. /* Remove filename */
  1260. if (substr($parts[count($parts) - 1], -4) == '.php') {
  1261. $parts = array_slice($parts, 0, count($parts) - 1);
  1262. }
  1263. /* Remove extra path from javascript calls */
  1264. if (defined('PMA_PATH_TO_BASEDIR')) {
  1265. $parts = array_slice($parts, 0, count($parts) - 1);
  1266. }
  1267. $parts[] = '';
  1268. return implode('/', $parts);
  1269. }
  1270. /**
  1271. * enables backward compatibility
  1272. *
  1273. * @return void
  1274. */
  1275. public function enableBc()
  1276. {
  1277. $GLOBALS['cfg'] = $this->settings;
  1278. $GLOBALS['default_server'] = $this->default_server;
  1279. unset($this->default_server);
  1280. $GLOBALS['is_upload'] = $this->get('enable_upload');
  1281. $GLOBALS['max_upload_size'] = $this->get('max_upload_size');
  1282. $GLOBALS['is_https'] = $this->get('is_https');
  1283. $defines = array(
  1284. 'PMA_VERSION',
  1285. 'PMA_MAJOR_VERSION',
  1286. 'PMA_THEME_VERSION',
  1287. 'PMA_THEME_GENERATION',
  1288. 'PMA_IS_WINDOWS',
  1289. 'PMA_IS_GD2',
  1290. 'PMA_USR_OS',
  1291. 'PMA_USR_BROWSER_VER',
  1292. 'PMA_USR_BROWSER_AGENT'
  1293. );
  1294. foreach ($defines as $define) {
  1295. if (! defined($define)) {
  1296. define($define, $this->get($define));
  1297. }
  1298. }
  1299. }
  1300. /**
  1301. * returns options for font size selection
  1302. *
  1303. * @param string $current_size current selected font size with unit
  1304. *
  1305. * @return array selectable font sizes
  1306. */
  1307. protected static function getFontsizeOptions($current_size = '82%')
  1308. {
  1309. $unit = preg_replace('/[0-9.]*/', '', $current_size);
  1310. $value = preg_replace('/[^0-9.]*/', '', $current_size);
  1311. $factors = array();
  1312. $options = array();
  1313. $options["$value"] = $value . $unit;
  1314. if ($unit === '%') {
  1315. $factors[] = 1;
  1316. $factors[] = 5;
  1317. $factors[] = 10;
  1318. $options['100'] = '100%';
  1319. } elseif ($unit === 'em') {
  1320. $factors[] = 0.05;
  1321. $factors[] = 0.2;
  1322. $factors[] = 1;
  1323. } elseif ($unit === 'pt') {
  1324. $factors[] = 0.5;
  1325. $factors[] = 2;
  1326. } elseif ($unit === 'px') {
  1327. $factors[] = 1;
  1328. $factors[] = 5;
  1329. $factors[] = 10;
  1330. } else {
  1331. //unknown font size unit
  1332. $factors[] = 0.05;
  1333. $factors[] = 0.2;
  1334. $factors[] = 1;
  1335. $factors[] = 5;
  1336. $factors[] = 10;
  1337. }
  1338. foreach ($factors as $key => $factor) {
  1339. $option_inc = $value + $factor;
  1340. $option_dec = $value - $factor;
  1341. while (count($options) < 21) {
  1342. $options["$option_inc"] = $option_inc . $unit;
  1343. if ($option_dec > $factors[0]) {
  1344. $options["$option_dec"] = $option_dec . $unit;
  1345. }
  1346. $option_inc += $factor;
  1347. $option_dec -= $factor;
  1348. if (isset($factors[$key + 1])
  1349. && $option_inc >= $value + $factors[$key + 1]
  1350. ) {
  1351. break;
  1352. }
  1353. }
  1354. }
  1355. ksort($options);
  1356. return $options;
  1357. }
  1358. /**
  1359. * returns html selectbox for font sizes
  1360. *
  1361. * @return string html selectbox
  1362. */
  1363. protected static function getFontsizeSelection()
  1364. {
  1365. $current_size = $GLOBALS['PMA_Config']->get('FontSize');
  1366. // for the case when there is no config file (this is supported)
  1367. if (empty($current_size)) {
  1368. $current_size = '82%';
  1369. }
  1370. $options = Config::getFontsizeOptions($current_size);
  1371. $return = '<label for="select_fontsize">' . __('Font size')
  1372. . ':</label>' . "\n"
  1373. . '<select name="set_fontsize" id="select_fontsize"'
  1374. . ' class="autosubmit">' . "\n";
  1375. foreach ($options as $option) {
  1376. $return .= '<option value="' . $option . '"';
  1377. if ($option == $current_size) {
  1378. $return .= ' selected="selected"';
  1379. }
  1380. $return .= '>' . $option . '</option>' . "\n";
  1381. }
  1382. $return .= '</select>';
  1383. return $return;
  1384. }
  1385. /**
  1386. * return complete font size selection form
  1387. *
  1388. * @return string html selectbox
  1389. */
  1390. public static function getFontsizeForm()
  1391. {
  1392. return '<form name="form_fontsize_selection" id="form_fontsize_selection"'
  1393. . ' method="post" action="index.php" class="disableAjax">' . "\n"
  1394. . Url::getHiddenInputs() . "\n"
  1395. . Config::getFontsizeSelection() . "\n"
  1396. . '</form>';
  1397. }
  1398. /**
  1399. * removes cookie
  1400. *
  1401. * @param string $cookie name of cookie to remove
  1402. *
  1403. * @return boolean result of setcookie()
  1404. */
  1405. public function removeCookie($cookie)
  1406. {
  1407. if (defined('TESTSUITE')) {
  1408. if (isset($_COOKIE[$cookie])) {
  1409. unset($_COOKIE[$cookie]);
  1410. }
  1411. return true;
  1412. }
  1413. return setcookie(
  1414. $cookie,
  1415. '',
  1416. time() - 3600,
  1417. $this->getRootPath(),
  1418. '',
  1419. $this->isHttps()
  1420. );
  1421. }
  1422. /**
  1423. * sets cookie if value is different from current cookie value,
  1424. * or removes if value is equal to default
  1425. *
  1426. * @param string $cookie name of cookie to remove
  1427. * @param mixed $value new cookie value
  1428. * @param string $default default value
  1429. * @param int $validity validity of cookie in seconds (default is one month)
  1430. * @param bool $httponly whether cookie is only for HTTP (and not for scripts)
  1431. *
  1432. * @return boolean result of setcookie()
  1433. */
  1434. public function setCookie($cookie, $value, $default = null,
  1435. $validity = null, $httponly = true
  1436. ) {
  1437. if (strlen($value) > 0 && null !== $default && $value === $default
  1438. ) {
  1439. // default value is used
  1440. if (isset($_COOKIE[$cookie])) {
  1441. // remove cookie
  1442. return $this->removeCookie($cookie);
  1443. }
  1444. return false;
  1445. }
  1446. if (strlen($value) === 0 && isset($_COOKIE[$cookie])) {
  1447. // remove cookie, value is empty
  1448. return $this->removeCookie($cookie);
  1449. }
  1450. if (! isset($_COOKIE[$cookie]) || $_COOKIE[$cookie] !== $value) {
  1451. // set cookie with new value
  1452. /* Calculate cookie validity */
  1453. if ($validity === null) {
  1454. /* Valid for one month */
  1455. $validity = time() + 2592000;
  1456. } elseif ($validity == 0) {
  1457. /* Valid for session */
  1458. $validity = 0;
  1459. } else {
  1460. $validity = time() + $validity;
  1461. }
  1462. if (defined('TESTSUITE')) {
  1463. $_COOKIE[$cookie] = $value;
  1464. return true;
  1465. }
  1466. return setcookie(
  1467. $cookie,
  1468. $value,
  1469. $validity,
  1470. $this->getRootPath(),
  1471. '',
  1472. $this->isHttps(),
  1473. $httponly
  1474. );
  1475. }
  1476. // cookie has already $value as value
  1477. return true;
  1478. }
  1479. /**
  1480. * Error handler to catch fatal errors when loading configuration
  1481. * file
  1482. *
  1483. *
  1484. * PMA_Config_fatalErrorHandler
  1485. * @return void
  1486. */
  1487. public static function fatalErrorHandler()
  1488. {
  1489. if (!isset($GLOBALS['pma_config_loading'])
  1490. || !$GLOBALS['pma_config_loading']
  1491. ) {
  1492. return;
  1493. }
  1494. $error = error_get_last();
  1495. if ($error === null) {
  1496. return;
  1497. }
  1498. Core::fatalError(
  1499. sprintf(
  1500. 'Failed to load phpMyAdmin configuration (%s:%s): %s',
  1501. Error::relPath($error['file']),
  1502. $error['line'],
  1503. $error['message']
  1504. )
  1505. );
  1506. }
  1507. /**
  1508. * Wrapper for footer/header rendering
  1509. *
  1510. * @param string $filename File to check and render
  1511. * @param string $id Div ID
  1512. *
  1513. * @return string
  1514. */
  1515. private static function _renderCustom($filename, $id)
  1516. {
  1517. $retval = '';
  1518. if (@file_exists($filename)) {
  1519. $retval .= '<div id="' . $id . '">';
  1520. ob_start();
  1521. include $filename;
  1522. $retval .= ob_get_contents();
  1523. ob_end_clean();
  1524. $retval .= '</div>';
  1525. }
  1526. return $retval;
  1527. }
  1528. /**
  1529. * Renders user configured footer
  1530. *
  1531. * @return string
  1532. */
  1533. public static function renderFooter()
  1534. {
  1535. return self::_renderCustom(CUSTOM_FOOTER_FILE, 'pma_footer');
  1536. }
  1537. /**
  1538. * Renders user configured footer
  1539. *
  1540. * @return string
  1541. */
  1542. public static function renderHeader()
  1543. {
  1544. return self::_renderCustom(CUSTOM_HEADER_FILE, 'pma_header');
  1545. }
  1546. /**
  1547. * Returns temporary dir path
  1548. *
  1549. * @param string $name Directory name
  1550. *
  1551. * @return string|null
  1552. */
  1553. public function getTempDir($name)
  1554. {
  1555. static $temp_dir = array();
  1556. if (isset($temp_dir[$name]) && !defined('TESTSUITE')) {
  1557. return $temp_dir[$name];
  1558. }
  1559. $path = $this->get('TempDir');
  1560. if (empty($path)) {
  1561. $path = null;
  1562. } else {
  1563. $path .= '/' . $name;
  1564. if (! @is_dir($path)) {
  1565. @mkdir($path, 0770, true);
  1566. }
  1567. if (! @is_dir($path) || ! @is_writable($path)) {
  1568. $path = null;
  1569. }
  1570. }
  1571. $temp_dir[$name] = $path;
  1572. return $path;
  1573. }
  1574. /**
  1575. * Returns temporary directory
  1576. *
  1577. * @return string
  1578. */
  1579. public function getUploadTempDir()
  1580. {
  1581. // First try configured temp dir
  1582. // Fallback to PHP upload_tmp_dir
  1583. $dirs = array(
  1584. $this->getTempDir('upload'),
  1585. ini_get('upload_tmp_dir'),
  1586. sys_get_temp_dir(),
  1587. );
  1588. foreach ($dirs as $dir) {
  1589. if (! empty($dir) && @is_writable($dir)) {
  1590. return realpath($dir);
  1591. }
  1592. }
  1593. return null;
  1594. }
  1595. /**
  1596. * Selects server based on request parameters.
  1597. *
  1598. * @return integer
  1599. */
  1600. public function selectServer() {
  1601. $server = 0;
  1602. $request = empty($_REQUEST['server']) ? 0 : $_REQUEST['server'];
  1603. /**
  1604. * Lookup server by name
  1605. * (see FAQ 4.8)
  1606. */
  1607. if (! is_numeric($request)) {
  1608. foreach ($this->settings['Servers'] as $i => $server) {
  1609. $verboseToLower = mb_strtolower($server['verbose']);
  1610. $serverToLower = mb_strtolower($request);
  1611. if ($server['host'] == $request
  1612. || $server['verbose'] == $request
  1613. || $verboseToLower == $serverToLower
  1614. || md5($verboseToLower) === $serverToLower
  1615. ) {
  1616. $request = $i;
  1617. break;
  1618. }
  1619. }
  1620. if (is_string($request)) {
  1621. $request = 0;
  1622. }
  1623. }
  1624. /**
  1625. * If no server is selected, make sure that $this->settings['Server'] is empty (so
  1626. * that nothing will work), and skip server authentication.
  1627. * We do NOT exit here, but continue on without logging into any server.
  1628. * This way, the welcome page will still come up (with no server info) and
  1629. * present a choice of servers in the case that there are multiple servers
  1630. * and '$this->settings['ServerDefault'] = 0' is set.
  1631. */
  1632. if (is_numeric($request) && ! empty($request) && ! empty($this->settings['Servers'][$request])) {
  1633. $server = $request;
  1634. $this->settings['Server'] = $this->settings['Servers'][$server];
  1635. } else {
  1636. if (!empty($this->settings['Servers'][$this->settings['ServerDefault']])) {
  1637. $server = $this->settings['ServerDefault'];
  1638. $this->settings['Server'] = $this->settings['Servers'][$server];
  1639. } else {
  1640. $server = 0;
  1641. $this->settings['Server'] = array();
  1642. }
  1643. }
  1644. return $server;
  1645. }
  1646. /**
  1647. * Checks whether Servers configuration is valid and possibly apply fixups.
  1648. *
  1649. * @return void
  1650. */
  1651. public function checkServers() {
  1652. // Do we have some server?
  1653. if (! isset($this->settings['Servers']) || count($this->settings['Servers']) == 0) {
  1654. // No server => create one with defaults
  1655. $this->settings['Servers'] = array(1 => $this->default_server);
  1656. } else {
  1657. // We have server(s) => apply default configuration
  1658. $new_servers = array();
  1659. foreach ($this->settings['Servers'] as $server_index => $each_server) {
  1660. // Detect wrong configuration
  1661. if (!is_int($server_index) || $server_index < 1) {
  1662. trigger_error(
  1663. sprintf(__('Invalid server index: %s'), $server_index),
  1664. E_USER_ERROR
  1665. );
  1666. }
  1667. $each_server = array_merge($this->default_server, $each_server);
  1668. // Final solution to bug #582890
  1669. // If we are using a socket connection
  1670. // and there is nothing in the verbose server name
  1671. // or the host field, then generate a name for the server
  1672. // in the form of "Server 2", localized of course!
  1673. if (empty($each_server['host']) && empty($each_server['verbose'])) {
  1674. $each_server['verbose'] = sprintf(__('Server %d'), $server_index);
  1675. }
  1676. $new_servers[$server_index] = $each_server;
  1677. }
  1678. $this->settings['Servers'] = $new_servers;
  1679. }
  1680. }
  1681. }
  1682. if (!defined('TESTSUITE')) {
  1683. register_shutdown_function(array('PhpMyAdmin\Config', 'fatalErrorHandler'));
  1684. }