Config.php 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896
  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.9.10');
  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. $canUseErrorReporting = function_exists('error_reporting');
  713. if ($canUseErrorReporting) {
  714. $old_error_reporting = error_reporting(0);
  715. }
  716. ob_start();
  717. $GLOBALS['pma_config_loading'] = true;
  718. $eval_result = include $this->default_source;
  719. $GLOBALS['pma_config_loading'] = false;
  720. ob_end_clean();
  721. if ($canUseErrorReporting) {
  722. error_reporting($old_error_reporting);
  723. }
  724. if ($eval_result === false) {
  725. $this->error_config_default_file = true;
  726. return false;
  727. }
  728. $this->default_source_mtime = filemtime($this->default_source);
  729. $this->default_server = $cfg['Servers'][1];
  730. unset($cfg['Servers']);
  731. $this->default = $cfg;
  732. $this->settings = array_replace_recursive($this->settings, $cfg);
  733. $this->error_config_default_file = false;
  734. return true;
  735. }
  736. /**
  737. * loads configuration from $source, usually the config file
  738. * should be called on object creation
  739. *
  740. * @param string $source config file
  741. *
  742. * @return bool
  743. */
  744. public function load($source = null)
  745. {
  746. $this->loadDefaults();
  747. if (null !== $source) {
  748. $this->setSource($source);
  749. }
  750. if (! $this->checkConfigSource()) {
  751. return false;
  752. }
  753. $cfg = array();
  754. /**
  755. * Parses the configuration file, we throw away any errors or
  756. * output.
  757. */
  758. $canUseErrorReporting = function_exists('error_reporting');
  759. if ($canUseErrorReporting) {
  760. $old_error_reporting = error_reporting(0);
  761. }
  762. ob_start();
  763. $GLOBALS['pma_config_loading'] = true;
  764. $eval_result = include $this->getSource();
  765. $GLOBALS['pma_config_loading'] = false;
  766. ob_end_clean();
  767. if ($canUseErrorReporting) {
  768. error_reporting($old_error_reporting);
  769. }
  770. if ($eval_result === false) {
  771. $this->error_config_file = true;
  772. } else {
  773. $this->error_config_file = false;
  774. $this->source_mtime = filemtime($this->getSource());
  775. }
  776. /**
  777. * Ignore keys with / as we do not use these
  778. *
  779. * These can be confusing for user configuration layer as it
  780. * flatten array using / and thus don't see difference between
  781. * $cfg['Export/method'] and $cfg['Export']['method'], while rest
  782. * of thre code uses the setting only in latter form.
  783. *
  784. * This could be removed once we consistently handle both values
  785. * in the functional code as well.
  786. *
  787. * It could use array_filter(...ARRAY_FILTER_USE_KEY), but it's not
  788. * supported on PHP 5.5 and HHVM.
  789. */
  790. $matched_keys = array_filter(
  791. array_keys($cfg),
  792. function ($key) {return strpos($key, '/') === false;}
  793. );
  794. $cfg = array_intersect_key($cfg, array_flip($matched_keys));
  795. /**
  796. * Backward compatibility code
  797. */
  798. if (!empty($cfg['DefaultTabTable'])) {
  799. $cfg['DefaultTabTable'] = str_replace(
  800. '_properties',
  801. '',
  802. str_replace(
  803. 'tbl_properties.php',
  804. 'tbl_sql.php',
  805. $cfg['DefaultTabTable']
  806. )
  807. );
  808. }
  809. if (!empty($cfg['DefaultTabDatabase'])) {
  810. $cfg['DefaultTabDatabase'] = str_replace(
  811. '_details',
  812. '',
  813. str_replace(
  814. 'db_details.php',
  815. 'db_sql.php',
  816. $cfg['DefaultTabDatabase']
  817. )
  818. );
  819. }
  820. $this->settings = array_replace_recursive($this->settings, $cfg);
  821. return true;
  822. }
  823. /**
  824. * Sets the connection collation
  825. *
  826. * @return void
  827. */
  828. private function _setConnectionCollation()
  829. {
  830. $collation_connection = $this->get('DefaultConnectionCollation');
  831. if (! empty($collation_connection)
  832. && $collation_connection != $GLOBALS['collation_connection']
  833. ) {
  834. $GLOBALS['dbi']->setCollation($collation_connection);
  835. }
  836. }
  837. /**
  838. * Loads user preferences and merges them with current config
  839. * must be called after control connection has been established
  840. *
  841. * @return void
  842. */
  843. public function loadUserPreferences()
  844. {
  845. // index.php should load these settings, so that phpmyadmin.css.php
  846. // will have everything available in session cache
  847. $server = isset($GLOBALS['server'])
  848. ? $GLOBALS['server']
  849. : (!empty($GLOBALS['cfg']['ServerDefault'])
  850. ? $GLOBALS['cfg']['ServerDefault']
  851. : 0);
  852. $cache_key = 'server_' . $server;
  853. if ($server > 0 && !defined('PMA_MINIMUM_COMMON')) {
  854. $config_mtime = max($this->default_source_mtime, $this->source_mtime);
  855. // cache user preferences, use database only when needed
  856. if (! isset($_SESSION['cache'][$cache_key]['userprefs'])
  857. || $_SESSION['cache'][$cache_key]['config_mtime'] < $config_mtime
  858. ) {
  859. $prefs = $this->userPreferences->load();
  860. $_SESSION['cache'][$cache_key]['userprefs']
  861. = $this->userPreferences->apply($prefs['config_data']);
  862. $_SESSION['cache'][$cache_key]['userprefs_mtime'] = $prefs['mtime'];
  863. $_SESSION['cache'][$cache_key]['userprefs_type'] = $prefs['type'];
  864. $_SESSION['cache'][$cache_key]['config_mtime'] = $config_mtime;
  865. }
  866. } elseif ($server == 0
  867. || ! isset($_SESSION['cache'][$cache_key]['userprefs'])
  868. ) {
  869. $this->set('user_preferences', false);
  870. return;
  871. }
  872. $config_data = $_SESSION['cache'][$cache_key]['userprefs'];
  873. // type is 'db' or 'session'
  874. $this->set(
  875. 'user_preferences',
  876. $_SESSION['cache'][$cache_key]['userprefs_type']
  877. );
  878. $this->set(
  879. 'user_preferences_mtime',
  880. $_SESSION['cache'][$cache_key]['userprefs_mtime']
  881. );
  882. // load config array
  883. $this->settings = array_replace_recursive($this->settings, $config_data);
  884. $GLOBALS['cfg'] = array_replace_recursive($GLOBALS['cfg'], $config_data);
  885. if (defined('PMA_MINIMUM_COMMON')) {
  886. return;
  887. }
  888. // settings below start really working on next page load, but
  889. // changes are made only in index.php so everything is set when
  890. // in frames
  891. // save theme
  892. /** @var ThemeManager $tmanager */
  893. $tmanager = ThemeManager::getInstance();
  894. if ($tmanager->getThemeCookie() || isset($_REQUEST['set_theme'])) {
  895. if ((! isset($config_data['ThemeDefault'])
  896. && $tmanager->theme->getId() != 'original')
  897. || isset($config_data['ThemeDefault'])
  898. && $config_data['ThemeDefault'] != $tmanager->theme->getId()
  899. ) {
  900. // new theme was set in common.inc.php
  901. $this->setUserValue(
  902. null,
  903. 'ThemeDefault',
  904. $tmanager->theme->getId(),
  905. 'original'
  906. );
  907. }
  908. } else {
  909. // no cookie - read default from settings
  910. if ($this->settings['ThemeDefault'] != $tmanager->theme->getId()
  911. && $tmanager->checkTheme($this->settings['ThemeDefault'])
  912. ) {
  913. $tmanager->setActiveTheme($this->settings['ThemeDefault']);
  914. $tmanager->setThemeCookie();
  915. }
  916. }
  917. // save language
  918. if ($this->issetCookie('pma_lang') || isset($_POST['lang'])) {
  919. if ((! isset($config_data['lang'])
  920. && $GLOBALS['lang'] != 'en')
  921. || isset($config_data['lang'])
  922. && $GLOBALS['lang'] != $config_data['lang']
  923. ) {
  924. $this->setUserValue(null, 'lang', $GLOBALS['lang'], 'en');
  925. }
  926. } else {
  927. // read language from settings
  928. if (isset($config_data['lang'])) {
  929. $language = LanguageManager::getInstance()->getLanguage(
  930. $config_data['lang']
  931. );
  932. if ($language !== false) {
  933. $language->activate();
  934. $this->setCookie('pma_lang', $language->getCode());
  935. }
  936. }
  937. }
  938. // set connection collation
  939. $this->_setConnectionCollation();
  940. }
  941. /**
  942. * Sets config value which is stored in user preferences (if available)
  943. * or in a cookie.
  944. *
  945. * If user preferences are not yet initialized, option is applied to
  946. * global config and added to a update queue, which is processed
  947. * by {@link loadUserPreferences()}
  948. *
  949. * @param string $cookie_name can be null
  950. * @param string $cfg_path configuration path
  951. * @param mixed $new_cfg_value new value
  952. * @param mixed $default_value default value
  953. *
  954. * @return true|PhpMyAdmin\Message
  955. */
  956. public function setUserValue($cookie_name, $cfg_path, $new_cfg_value,
  957. $default_value = null
  958. ) {
  959. $result = true;
  960. // use permanent user preferences if possible
  961. $prefs_type = $this->get('user_preferences');
  962. if ($prefs_type) {
  963. if ($default_value === null) {
  964. $default_value = Core::arrayRead($cfg_path, $this->default);
  965. }
  966. $result = $this->userPreferences->persistOption($cfg_path, $new_cfg_value, $default_value);
  967. }
  968. if ($prefs_type != 'db' && $cookie_name) {
  969. // fall back to cookies
  970. if ($default_value === null) {
  971. $default_value = Core::arrayRead($cfg_path, $this->settings);
  972. }
  973. $this->setCookie($cookie_name, $new_cfg_value, $default_value);
  974. }
  975. Core::arrayWrite($cfg_path, $GLOBALS['cfg'], $new_cfg_value);
  976. Core::arrayWrite($cfg_path, $this->settings, $new_cfg_value);
  977. return $result;
  978. }
  979. /**
  980. * Reads value stored by {@link setUserValue()}
  981. *
  982. * @param string $cookie_name cookie name
  983. * @param mixed $cfg_value config value
  984. *
  985. * @return mixed
  986. */
  987. public function getUserValue($cookie_name, $cfg_value)
  988. {
  989. $cookie_exists = isset($_COOKIE) && !empty($this->getCookie($cookie_name));
  990. $prefs_type = $this->get('user_preferences');
  991. if ($prefs_type == 'db') {
  992. // permanent user preferences value exists, remove cookie
  993. if ($cookie_exists) {
  994. $this->removeCookie($cookie_name);
  995. }
  996. } elseif ($cookie_exists) {
  997. return $this->getCookie($cookie_name);
  998. }
  999. // return value from $cfg array
  1000. return $cfg_value;
  1001. }
  1002. /**
  1003. * set source
  1004. *
  1005. * @param string $source source
  1006. *
  1007. * @return void
  1008. */
  1009. public function setSource($source)
  1010. {
  1011. $this->source = trim($source);
  1012. }
  1013. /**
  1014. * check config source
  1015. *
  1016. * @return boolean whether source is valid or not
  1017. */
  1018. public function checkConfigSource()
  1019. {
  1020. if (! $this->getSource()) {
  1021. // no configuration file set at all
  1022. return false;
  1023. }
  1024. if (! @file_exists($this->getSource())) {
  1025. $this->source_mtime = 0;
  1026. return false;
  1027. }
  1028. if (! @is_readable($this->getSource())) {
  1029. // manually check if file is readable
  1030. // might be bug #3059806 Supporting running from CIFS/Samba shares
  1031. $contents = false;
  1032. $handle = @fopen($this->getSource(), 'r');
  1033. if ($handle !== false) {
  1034. $contents = @fread($handle, 1); // reading 1 byte is enough to test
  1035. fclose($handle);
  1036. }
  1037. if ($contents === false) {
  1038. $this->source_mtime = 0;
  1039. Core::fatalError(
  1040. sprintf(
  1041. function_exists('__')
  1042. ? __('Existing configuration file (%s) is not readable.')
  1043. : 'Existing configuration file (%s) is not readable.',
  1044. $this->getSource()
  1045. )
  1046. );
  1047. return false;
  1048. }
  1049. }
  1050. return true;
  1051. }
  1052. /**
  1053. * verifies the permissions on config file (if asked by configuration)
  1054. * (must be called after config.inc.php has been merged)
  1055. *
  1056. * @return void
  1057. */
  1058. public function checkPermissions()
  1059. {
  1060. // Check for permissions (on platforms that support it):
  1061. if ($this->get('CheckConfigurationPermissions') && @file_exists($this->getSource())) {
  1062. $perms = @fileperms($this->getSource());
  1063. if (!($perms === false) && ($perms & 2)) {
  1064. // This check is normally done after loading configuration
  1065. $this->checkWebServerOs();
  1066. if ($this->get('PMA_IS_WINDOWS') == 0) {
  1067. $this->source_mtime = 0;
  1068. Core::fatalError(
  1069. __(
  1070. 'Wrong permissions on configuration file, '
  1071. . 'should not be world writable!'
  1072. )
  1073. );
  1074. }
  1075. }
  1076. }
  1077. }
  1078. /**
  1079. * Checks for errors
  1080. * (must be called after config.inc.php has been merged)
  1081. *
  1082. * @return void
  1083. */
  1084. public function checkErrors()
  1085. {
  1086. if ($this->error_config_default_file) {
  1087. Core::fatalError(
  1088. sprintf(
  1089. __('Could not load default configuration from: %1$s'),
  1090. $this->default_source
  1091. )
  1092. );
  1093. }
  1094. if ($this->error_config_file) {
  1095. $error = '[strong]' . __('Failed to read configuration file!') . '[/strong]'
  1096. . '[br][br]'
  1097. . __(
  1098. 'This usually means there is a syntax error in it, '
  1099. . 'please check any errors shown below.'
  1100. )
  1101. . '[br][br]'
  1102. . '[conferr]';
  1103. trigger_error($error, E_USER_ERROR);
  1104. }
  1105. }
  1106. /**
  1107. * returns specific config setting
  1108. *
  1109. * @param string $setting config setting
  1110. *
  1111. * @return mixed value
  1112. */
  1113. public function get($setting)
  1114. {
  1115. if (isset($this->settings[$setting])) {
  1116. return $this->settings[$setting];
  1117. }
  1118. return null;
  1119. }
  1120. /**
  1121. * sets configuration variable
  1122. *
  1123. * @param string $setting configuration option
  1124. * @param mixed $value new value for configuration option
  1125. *
  1126. * @return void
  1127. */
  1128. public function set($setting, $value)
  1129. {
  1130. if (! isset($this->settings[$setting])
  1131. || $this->settings[$setting] !== $value
  1132. ) {
  1133. $this->settings[$setting] = $value;
  1134. $this->set_mtime = time();
  1135. }
  1136. }
  1137. /**
  1138. * returns source for current config
  1139. *
  1140. * @return string config source
  1141. */
  1142. public function getSource()
  1143. {
  1144. return $this->source;
  1145. }
  1146. /**
  1147. * returns a unique value to force a CSS reload if either the config
  1148. * or the theme changes
  1149. *
  1150. * @return int Summary of unix timestamps and fontsize,
  1151. * to be unique on theme parameters change
  1152. */
  1153. public function getThemeUniqueValue()
  1154. {
  1155. if (null !== $this->get('FontSize')) {
  1156. $fontsize = intval($this->get('FontSize'));
  1157. } else {
  1158. $fontsize = 0;
  1159. }
  1160. return (
  1161. $fontsize +
  1162. $this->source_mtime +
  1163. $this->default_source_mtime +
  1164. $this->get('user_preferences_mtime') +
  1165. $GLOBALS['PMA_Theme']->mtime_info +
  1166. $GLOBALS['PMA_Theme']->filesize_info);
  1167. }
  1168. /**
  1169. * checks if upload is enabled
  1170. *
  1171. * @return void
  1172. */
  1173. public function checkUpload()
  1174. {
  1175. if (!ini_get('file_uploads')) {
  1176. $this->set('enable_upload', false);
  1177. return;
  1178. }
  1179. $this->set('enable_upload', true);
  1180. // if set "php_admin_value file_uploads Off" in httpd.conf
  1181. // ini_get() also returns the string "Off" in this case:
  1182. if ('off' == strtolower(ini_get('file_uploads'))) {
  1183. $this->set('enable_upload', false);
  1184. }
  1185. }
  1186. /**
  1187. * Maximum upload size as limited by PHP
  1188. * Used with permission from Moodle (https://moodle.org/) by Martin Dougiamas
  1189. *
  1190. * this section generates $max_upload_size in bytes
  1191. *
  1192. * @return void
  1193. */
  1194. public function checkUploadSize()
  1195. {
  1196. if (! $filesize = ini_get('upload_max_filesize')) {
  1197. $filesize = "5M";
  1198. }
  1199. if ($postsize = ini_get('post_max_size')) {
  1200. $this->set(
  1201. 'max_upload_size',
  1202. min(Core::getRealSize($filesize), Core::getRealSize($postsize))
  1203. );
  1204. } else {
  1205. $this->set('max_upload_size', Core::getRealSize($filesize));
  1206. }
  1207. }
  1208. /**
  1209. * Checks if protocol is https
  1210. *
  1211. * This function checks if the https protocol on the active connection.
  1212. *
  1213. * @return bool
  1214. */
  1215. public function isHttps()
  1216. {
  1217. if (null !== $this->get('is_https')) {
  1218. return $this->get('is_https');
  1219. }
  1220. $url = $this->get('PmaAbsoluteUri');
  1221. $is_https = false;
  1222. if (! empty($url) && parse_url($url, PHP_URL_SCHEME) === 'https') {
  1223. $is_https = true;
  1224. } elseif (strtolower(Core::getenv('HTTP_SCHEME')) == 'https') {
  1225. $is_https = true;
  1226. } elseif (strtolower(Core::getenv('HTTPS')) == 'on') {
  1227. $is_https = true;
  1228. } elseif (substr(strtolower(Core::getenv('REQUEST_URI')), 0, 6) == 'https:') {
  1229. $is_https = true;
  1230. } elseif (strtolower(Core::getenv('HTTP_HTTPS_FROM_LB')) == 'on') {
  1231. // A10 Networks load balancer
  1232. $is_https = true;
  1233. } elseif (strtolower(Core::getenv('HTTP_FRONT_END_HTTPS')) == 'on') {
  1234. $is_https = true;
  1235. } elseif (strtolower(Core::getenv('HTTP_X_FORWARDED_PROTO')) == 'https') {
  1236. $is_https = true;
  1237. } elseif (strtolower(Core::getenv('HTTP_CLOUDFRONT_FORWARDED_PROTO')) === 'https') {
  1238. // Amazon CloudFront, issue #15621
  1239. $is_https = true;
  1240. } elseif (Core::getenv('SERVER_PORT') == 443) {
  1241. $is_https = true;
  1242. }
  1243. $this->set('is_https', $is_https);
  1244. return $is_https;
  1245. }
  1246. /**
  1247. * Get phpMyAdmin root path
  1248. *
  1249. * @return string
  1250. */
  1251. public function getRootPath()
  1252. {
  1253. static $cookie_path = null;
  1254. if (null !== $cookie_path && !defined('TESTSUITE')) {
  1255. return $cookie_path;
  1256. }
  1257. $url = $this->get('PmaAbsoluteUri');
  1258. if (! empty($url)) {
  1259. $path = parse_url($url, PHP_URL_PATH);
  1260. if (! empty($path)) {
  1261. if (substr($path, -1) != '/') {
  1262. return $path . '/';
  1263. }
  1264. return $path;
  1265. }
  1266. }
  1267. $parsed_url = parse_url($GLOBALS['PMA_PHP_SELF']);
  1268. $parts = explode(
  1269. '/',
  1270. rtrim(str_replace('\\', '/', $parsed_url['path']), '/')
  1271. );
  1272. /* Remove filename */
  1273. if (substr($parts[count($parts) - 1], -4) == '.php') {
  1274. $parts = array_slice($parts, 0, count($parts) - 1);
  1275. }
  1276. /* Remove extra path from javascript calls */
  1277. if (defined('PMA_PATH_TO_BASEDIR')) {
  1278. $parts = array_slice($parts, 0, count($parts) - 1);
  1279. }
  1280. $parts[] = '';
  1281. return implode('/', $parts);
  1282. }
  1283. /**
  1284. * enables backward compatibility
  1285. *
  1286. * @return void
  1287. */
  1288. public function enableBc()
  1289. {
  1290. $GLOBALS['cfg'] = $this->settings;
  1291. $GLOBALS['default_server'] = $this->default_server;
  1292. unset($this->default_server);
  1293. $GLOBALS['is_upload'] = $this->get('enable_upload');
  1294. $GLOBALS['max_upload_size'] = $this->get('max_upload_size');
  1295. $GLOBALS['is_https'] = $this->get('is_https');
  1296. $defines = array(
  1297. 'PMA_VERSION',
  1298. 'PMA_MAJOR_VERSION',
  1299. 'PMA_THEME_VERSION',
  1300. 'PMA_THEME_GENERATION',
  1301. 'PMA_IS_WINDOWS',
  1302. 'PMA_IS_GD2',
  1303. 'PMA_USR_OS',
  1304. 'PMA_USR_BROWSER_VER',
  1305. 'PMA_USR_BROWSER_AGENT'
  1306. );
  1307. foreach ($defines as $define) {
  1308. if (! defined($define)) {
  1309. define($define, $this->get($define));
  1310. }
  1311. }
  1312. }
  1313. /**
  1314. * returns options for font size selection
  1315. *
  1316. * @param string $current_size current selected font size with unit
  1317. *
  1318. * @return array selectable font sizes
  1319. */
  1320. protected static function getFontsizeOptions($current_size = '82%')
  1321. {
  1322. $unit = preg_replace('/[0-9.]*/', '', $current_size);
  1323. $value = preg_replace('/[^0-9.]*/', '', $current_size);
  1324. $factors = array();
  1325. $options = array();
  1326. $options["$value"] = $value . $unit;
  1327. if ($unit === '%') {
  1328. $factors[] = 1;
  1329. $factors[] = 5;
  1330. $factors[] = 10;
  1331. $options['100'] = '100%';
  1332. } elseif ($unit === 'em') {
  1333. $factors[] = 0.05;
  1334. $factors[] = 0.2;
  1335. $factors[] = 1;
  1336. } elseif ($unit === 'pt') {
  1337. $factors[] = 0.5;
  1338. $factors[] = 2;
  1339. } elseif ($unit === 'px') {
  1340. $factors[] = 1;
  1341. $factors[] = 5;
  1342. $factors[] = 10;
  1343. } else {
  1344. //unknown font size unit
  1345. $factors[] = 0.05;
  1346. $factors[] = 0.2;
  1347. $factors[] = 1;
  1348. $factors[] = 5;
  1349. $factors[] = 10;
  1350. }
  1351. foreach ($factors as $key => $factor) {
  1352. $option_inc = $value + $factor;
  1353. $option_dec = $value - $factor;
  1354. while (count($options) < 21) {
  1355. $options["$option_inc"] = $option_inc . $unit;
  1356. if ($option_dec > $factors[0]) {
  1357. $options["$option_dec"] = $option_dec . $unit;
  1358. }
  1359. $option_inc += $factor;
  1360. $option_dec -= $factor;
  1361. if (isset($factors[$key + 1])
  1362. && $option_inc >= $value + $factors[$key + 1]
  1363. ) {
  1364. break;
  1365. }
  1366. }
  1367. }
  1368. ksort($options);
  1369. return $options;
  1370. }
  1371. /**
  1372. * returns html selectbox for font sizes
  1373. *
  1374. * @return string html selectbox
  1375. */
  1376. protected static function getFontsizeSelection()
  1377. {
  1378. $current_size = $GLOBALS['PMA_Config']->get('FontSize');
  1379. // for the case when there is no config file (this is supported)
  1380. if (empty($current_size)) {
  1381. $current_size = '82%';
  1382. }
  1383. $options = Config::getFontsizeOptions($current_size);
  1384. $return = '<label for="select_fontsize">' . __('Font size')
  1385. . ':</label>' . "\n"
  1386. . '<select name="set_fontsize" id="select_fontsize"'
  1387. . ' class="autosubmit">' . "\n";
  1388. foreach ($options as $option) {
  1389. $return .= '<option value="' . $option . '"';
  1390. if ($option == $current_size) {
  1391. $return .= ' selected="selected"';
  1392. }
  1393. $return .= '>' . $option . '</option>' . "\n";
  1394. }
  1395. $return .= '</select>';
  1396. return $return;
  1397. }
  1398. /**
  1399. * return complete font size selection form
  1400. *
  1401. * @return string html selectbox
  1402. */
  1403. public static function getFontsizeForm()
  1404. {
  1405. return '<form name="form_fontsize_selection" id="form_fontsize_selection"'
  1406. . ' method="post" action="index.php" class="disableAjax">' . "\n"
  1407. . Url::getHiddenInputs() . "\n"
  1408. . Config::getFontsizeSelection() . "\n"
  1409. . '</form>';
  1410. }
  1411. /**
  1412. * removes cookie
  1413. *
  1414. * @param string $cookieName name of cookie to remove
  1415. *
  1416. * @return boolean result of setcookie()
  1417. */
  1418. public function removeCookie($cookieName)
  1419. {
  1420. $httpCookieName = $this->getCookieName($cookieName);
  1421. if ($this->issetCookie($cookieName)) {
  1422. unset($_COOKIE[$httpCookieName]);
  1423. }
  1424. if (defined('TESTSUITE')) {
  1425. return true;
  1426. }
  1427. return setcookie(
  1428. $httpCookieName,
  1429. '',
  1430. time() - 3600,
  1431. $this->getRootPath(),
  1432. '',
  1433. $this->isHttps()
  1434. );
  1435. }
  1436. /**
  1437. * sets cookie if value is different from current cookie value,
  1438. * or removes if value is equal to default
  1439. *
  1440. * @param string $cookie name of cookie to remove
  1441. * @param mixed $value new cookie value
  1442. * @param string $default default value
  1443. * @param int $validity validity of cookie in seconds (default is one month)
  1444. * @param bool $httponly whether cookie is only for HTTP (and not for scripts)
  1445. *
  1446. * @return boolean result of setcookie()
  1447. */
  1448. public function setCookie($cookie, $value, $default = null,
  1449. $validity = null, $httponly = true
  1450. ) {
  1451. if (strlen($value) > 0 && null !== $default && $value === $default
  1452. ) {
  1453. // default value is used
  1454. if ($this->issetCookie($cookie)) {
  1455. // remove cookie
  1456. return $this->removeCookie($cookie);
  1457. }
  1458. return false;
  1459. }
  1460. if (strlen($value) === 0 && $this->issetCookie($cookie)) {
  1461. // remove cookie, value is empty
  1462. return $this->removeCookie($cookie);
  1463. }
  1464. $httpCookieName = $this->getCookieName($cookie);
  1465. if (! $this->issetCookie($cookie) || $this->getCookie($cookie) !== $value) {
  1466. // set cookie with new value
  1467. /* Calculate cookie validity */
  1468. if ($validity === null) {
  1469. /* Valid for one month */
  1470. $validity = time() + 2592000;
  1471. } elseif ($validity == 0) {
  1472. /* Valid for session */
  1473. $validity = 0;
  1474. } else {
  1475. $validity = time() + $validity;
  1476. }
  1477. if (defined('TESTSUITE')) {
  1478. $_COOKIE[$httpCookieName] = $value;
  1479. return true;
  1480. }
  1481. return setcookie(
  1482. $httpCookieName,
  1483. $value,
  1484. $validity,
  1485. $this->getRootPath(),
  1486. '',
  1487. $this->isHttps(),
  1488. $httponly
  1489. );
  1490. }
  1491. // cookie has already $value as value
  1492. return true;
  1493. }
  1494. /**
  1495. * get cookie
  1496. *
  1497. * @param string $cookieName The name of the cookie to get
  1498. *
  1499. * @return mixed result of getCookie()
  1500. */
  1501. public function getCookie($cookieName) {
  1502. if (isset($_COOKIE[$this->getCookieName($cookieName)])) {
  1503. return $_COOKIE[$this->getCookieName($cookieName)];
  1504. } else {
  1505. return null;
  1506. }
  1507. }
  1508. /**
  1509. * Get the real cookie name
  1510. *
  1511. * @param string $cookieName The name of the cookie
  1512. * @return string
  1513. */
  1514. public function getCookieName($cookieName) {
  1515. return $cookieName. ( ($this->isHttps()) ? '_https' : '' );
  1516. }
  1517. /**
  1518. * isset cookie
  1519. *
  1520. * @param string $cookieName The name of the cookie to check
  1521. *
  1522. * @return bool result of issetCookie()
  1523. */
  1524. public function issetCookie($cookieName) {
  1525. return isset($_COOKIE[$this->getCookieName($cookieName)]);
  1526. }
  1527. /**
  1528. * Error handler to catch fatal errors when loading configuration
  1529. * file
  1530. *
  1531. *
  1532. * PMA_Config_fatalErrorHandler
  1533. * @return void
  1534. */
  1535. public static function fatalErrorHandler()
  1536. {
  1537. if (!isset($GLOBALS['pma_config_loading'])
  1538. || !$GLOBALS['pma_config_loading']
  1539. ) {
  1540. return;
  1541. }
  1542. $error = error_get_last();
  1543. if ($error === null) {
  1544. return;
  1545. }
  1546. Core::fatalError(
  1547. sprintf(
  1548. 'Failed to load phpMyAdmin configuration (%s:%s): %s',
  1549. Error::relPath($error['file']),
  1550. $error['line'],
  1551. $error['message']
  1552. )
  1553. );
  1554. }
  1555. /**
  1556. * Wrapper for footer/header rendering
  1557. *
  1558. * @param string $filename File to check and render
  1559. * @param string $id Div ID
  1560. *
  1561. * @return string
  1562. */
  1563. private static function _renderCustom($filename, $id)
  1564. {
  1565. $retval = '';
  1566. if (@file_exists($filename)) {
  1567. $retval .= '<div id="' . $id . '">';
  1568. ob_start();
  1569. include $filename;
  1570. $retval .= ob_get_contents();
  1571. ob_end_clean();
  1572. $retval .= '</div>';
  1573. }
  1574. return $retval;
  1575. }
  1576. /**
  1577. * Renders user configured footer
  1578. *
  1579. * @return string
  1580. */
  1581. public static function renderFooter()
  1582. {
  1583. return self::_renderCustom(CUSTOM_FOOTER_FILE, 'pma_footer');
  1584. }
  1585. /**
  1586. * Renders user configured footer
  1587. *
  1588. * @return string
  1589. */
  1590. public static function renderHeader()
  1591. {
  1592. return self::_renderCustom(CUSTOM_HEADER_FILE, 'pma_header');
  1593. }
  1594. /**
  1595. * Returns temporary dir path
  1596. *
  1597. * @param string $name Directory name
  1598. *
  1599. * @return string|null
  1600. */
  1601. public function getTempDir($name)
  1602. {
  1603. static $temp_dir = array();
  1604. if (isset($temp_dir[$name]) && !defined('TESTSUITE')) {
  1605. return $temp_dir[$name];
  1606. }
  1607. $path = $this->get('TempDir');
  1608. if (empty($path)) {
  1609. $path = null;
  1610. } else {
  1611. $path .= '/' . $name;
  1612. if (! @is_dir($path)) {
  1613. @mkdir($path, 0770, true);
  1614. }
  1615. if (! @is_dir($path) || ! @is_writable($path)) {
  1616. $path = null;
  1617. }
  1618. }
  1619. $temp_dir[$name] = $path;
  1620. return $path;
  1621. }
  1622. /**
  1623. * Returns temporary directory
  1624. *
  1625. * @return string
  1626. */
  1627. public function getUploadTempDir()
  1628. {
  1629. // First try configured temp dir
  1630. // Fallback to PHP upload_tmp_dir
  1631. $dirs = array(
  1632. $this->getTempDir('upload'),
  1633. ini_get('upload_tmp_dir'),
  1634. sys_get_temp_dir(),
  1635. );
  1636. foreach ($dirs as $dir) {
  1637. if (! empty($dir) && @is_writable($dir)) {
  1638. return realpath($dir);
  1639. }
  1640. }
  1641. return null;
  1642. }
  1643. /**
  1644. * Selects server based on request parameters.
  1645. *
  1646. * @return integer
  1647. */
  1648. public function selectServer() {
  1649. $server = 0;
  1650. $request = empty($_REQUEST['server']) ? 0 : $_REQUEST['server'];
  1651. /**
  1652. * Lookup server by name
  1653. * (see FAQ 4.8)
  1654. */
  1655. if (! is_numeric($request)) {
  1656. foreach ($this->settings['Servers'] as $i => $server) {
  1657. $verboseToLower = mb_strtolower($server['verbose']);
  1658. $serverToLower = mb_strtolower($request);
  1659. if ($server['host'] == $request
  1660. || $server['verbose'] == $request
  1661. || $verboseToLower == $serverToLower
  1662. || md5($verboseToLower) === $serverToLower
  1663. ) {
  1664. $request = $i;
  1665. break;
  1666. }
  1667. }
  1668. if (is_string($request)) {
  1669. $request = 0;
  1670. }
  1671. }
  1672. /**
  1673. * If no server is selected, make sure that $this->settings['Server'] is empty (so
  1674. * that nothing will work), and skip server authentication.
  1675. * We do NOT exit here, but continue on without logging into any server.
  1676. * This way, the welcome page will still come up (with no server info) and
  1677. * present a choice of servers in the case that there are multiple servers
  1678. * and '$this->settings['ServerDefault'] = 0' is set.
  1679. */
  1680. if (is_numeric($request) && ! empty($request) && ! empty($this->settings['Servers'][$request])) {
  1681. $server = $request;
  1682. $this->settings['Server'] = $this->settings['Servers'][$server];
  1683. } else {
  1684. if (!empty($this->settings['Servers'][$this->settings['ServerDefault']])) {
  1685. $server = $this->settings['ServerDefault'];
  1686. $this->settings['Server'] = $this->settings['Servers'][$server];
  1687. } else {
  1688. $server = 0;
  1689. $this->settings['Server'] = array();
  1690. }
  1691. }
  1692. return $server;
  1693. }
  1694. /**
  1695. * Checks whether Servers configuration is valid and possibly apply fixups.
  1696. *
  1697. * @return void
  1698. */
  1699. public function checkServers() {
  1700. // Do we have some server?
  1701. if (! isset($this->settings['Servers']) || count($this->settings['Servers']) == 0) {
  1702. // No server => create one with defaults
  1703. $this->settings['Servers'] = array(1 => $this->default_server);
  1704. } else {
  1705. // We have server(s) => apply default configuration
  1706. $new_servers = array();
  1707. foreach ($this->settings['Servers'] as $server_index => $each_server) {
  1708. // Detect wrong configuration
  1709. if (!is_int($server_index) || $server_index < 1) {
  1710. trigger_error(
  1711. sprintf(__('Invalid server index: %s'), $server_index),
  1712. E_USER_ERROR
  1713. );
  1714. }
  1715. $each_server = array_merge($this->default_server, $each_server);
  1716. // Final solution to bug #582890
  1717. // If we are using a socket connection
  1718. // and there is nothing in the verbose server name
  1719. // or the host field, then generate a name for the server
  1720. // in the form of "Server 2", localized of course!
  1721. if (empty($each_server['host']) && empty($each_server['verbose'])) {
  1722. $each_server['verbose'] = sprintf(__('Server %d'), $server_index);
  1723. }
  1724. $new_servers[$server_index] = $each_server;
  1725. }
  1726. $this->settings['Servers'] = $new_servers;
  1727. }
  1728. }
  1729. }
  1730. if (!defined('TESTSUITE')) {
  1731. register_shutdown_function(array('PhpMyAdmin\Config', 'fatalErrorHandler'));
  1732. }