PageRenderTime 49ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/install/helpers/config_file_helper.php

https://github.com/carlosezeta/Bonfire
PHP | 430 lines | 234 code | 58 blank | 138 comment | 57 complexity | 554c6ba89b202096f09a5cb2f98a3afb MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
  2. /*
  3. Copyright (c) 2011 Lonnie Ezell
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. /*
  21. File: Config File Helper
  22. Functions to aid in reading and saving config items to and from
  23. configuration files.
  24. The config files are expected to be found in the APPPATH .'/config' folder.
  25. It does not currently work within modules.
  26. Author:
  27. Lonnie Ezell
  28. */
  29. //--------------------------------------------------------------------
  30. /*
  31. Function: read_config()
  32. Returns an array of configuration settings from a single
  33. config file.
  34. Parameters:
  35. $file - The config file to read.
  36. $fail_gracefully - true/false. Whether to show errors or simply return false.
  37. $module - Name of the module where the config file exists
  38. Return:
  39. An array of settings, or false on failure (when $fail_gracefully = true).
  40. */
  41. function read_config($file, $fail_gracefully = TRUE, $module = '')
  42. {
  43. $file = ($file == '') ? 'config' : str_replace(EXT, '', $file);
  44. $file = 'config/'.$file;
  45. $file_details = '';
  46. if (!empty($module))
  47. {
  48. $file_details = Modules::find($file, $module, '');
  49. }
  50. if (is_array($file_details) && !empty($file_details[0]))
  51. {
  52. $file = implode("", $file_details);
  53. }
  54. else
  55. {
  56. $file = APPPATH.$file;
  57. }
  58. if ( ! file_exists($file.EXT))
  59. {
  60. if ($fail_gracefully === TRUE)
  61. {
  62. return FALSE;
  63. }
  64. show_error('The configuration file '.$file.EXT.' does not exist.');
  65. }
  66. include($file.EXT);
  67. if ( ! isset($config) OR ! is_array($config))
  68. {
  69. if ($fail_gracefully === TRUE)
  70. {
  71. return FALSE;
  72. }
  73. show_error('Your '.$file.EXT.' file does not appear to contain a valid configuration array.');
  74. }
  75. return $config;
  76. }
  77. //---------------------------------------------------------------
  78. /*
  79. Function: write_config()
  80. Saves the passed array settings into a single config file located
  81. in the /config directory.
  82. Parameters:
  83. $file - The config file to write to.
  84. $settigns - An array of key/value pairs to be written to the file.
  85. $module - Name of the module where the config file exists
  86. Return:
  87. true/false
  88. */
  89. function write_config($file='', $settings=null, $module='')
  90. {
  91. if (empty($file) || !is_array($settings ))
  92. {
  93. return false;
  94. }
  95. $config_file = APPPATH.'../bonfire/application/config/'.$file;
  96. // Load the file so we can loop through the lines
  97. if (is_file($config_file . EXT))
  98. {
  99. $contents = file_get_contents($config_file.EXT);
  100. $empty = false;
  101. }
  102. else
  103. {
  104. $contents = '';
  105. $empty = true;
  106. }
  107. foreach ($settings as $name => $val)
  108. {
  109. // Is the config setting in the file?
  110. $start = strpos($contents, '$config[\''.$name.'\']');
  111. $end = strpos($contents, ';', $start);
  112. $search = substr($contents, $start, $end-$start+1);
  113. //var_dump($search); die();
  114. if (is_array($val))
  115. {
  116. // get the array output
  117. $val = config_array_output($val);
  118. }
  119. elseif (is_numeric($val))
  120. {
  121. $val = $val;
  122. }
  123. else
  124. {
  125. $val ="\"$val\"";
  126. }
  127. if (!$empty)
  128. {
  129. $contents = str_replace($search, '$config[\''.$name.'\'] = '. $val .';', $contents);
  130. }
  131. else
  132. {
  133. $contents .= '$config[\''.$name.'\'] = '. $val .";\n";
  134. }
  135. }
  136. // Make sure the file still has the php opening header in it...
  137. if (strpos($contents, '<?php') === FALSE)
  138. {
  139. $contents = '<?php if ( ! defined(\'BASEPATH\')) exit(\'No direct script access allowed\');' . "\n\n" . $contents;
  140. }
  141. // Write the changes out...
  142. if (!function_exists('write_file'))
  143. {
  144. $CI = get_instance();
  145. $CI->load->helper('file');
  146. }
  147. $result = write_file($config_file.EXT, $contents);
  148. if ($result === FALSE)
  149. {
  150. return false;
  151. } else {
  152. return true;
  153. }
  154. }
  155. //---------------------------------------------------------------
  156. /*
  157. Function: config_array_output()
  158. Outputs the array string which is then used in the config file.
  159. Parameters:
  160. $array - Array of values to store in the config
  161. $num_tabs - (Optional) The number of tabs to use in front of the array elements - makes it all nice !
  162. Return:
  163. A string of text which will make up the array values in the config file
  164. */
  165. function config_array_output($array, $num_tabs=1)
  166. {
  167. if (!is_array($array))
  168. {
  169. return false;
  170. }
  171. $tval = 'array(';
  172. // allow for two-dimensional arrays
  173. $array_keys = array_keys($array);
  174. // check if they are basic numeric keys
  175. if (is_numeric($array_keys[0]) && $array_keys[0] == 0)
  176. {
  177. $tval .= "'".implode("','", $array)."'";
  178. }
  179. else
  180. {
  181. $tabs = "";
  182. for ($num=0;$num<$num_tabs;$num++)
  183. {
  184. $tabs .= "\t";
  185. }
  186. // non-numeric keys
  187. foreach ($array as $key => $value)
  188. {
  189. if(is_array($value))
  190. {
  191. $num_tabs++;
  192. $tval .= "\n".$tabs."'".$key."' => ". config_array_output($value, $num_tabs). ",";
  193. }
  194. else
  195. {
  196. $tval .= "\n".$tabs."'".$key."' => '". $value. "',";
  197. }
  198. }//end foreach
  199. $tval .= "\n".$tabs;
  200. }//end if
  201. $tval .= ')';
  202. return $tval;
  203. }//end config_array_output()
  204. //---------------------------------------------------------------
  205. /*
  206. Function: read_db_config()
  207. Retrieves the config/database.php file settings. Plays nice with CodeIgniter 2.0's
  208. multiple environment support.
  209. Parameters:
  210. $environment - (Optional) The envinroment to get. If empty, will return all environments.
  211. $new_db (str) - (Optional) Returns an new db config array with parameter as $db active_group name
  212. $fail_gracefully - true/false. Whether to halt on errors or simply return false.
  213. Return:
  214. An array of database settings or abrupt failure (when $fail_gracefully == FALSE)
  215. */
  216. function read_db_config($environment=null, $new_db = NULL, $fail_gracefully = TRUE)
  217. {
  218. $files = array();
  219. $settings = array();
  220. // Determine what environment to read.
  221. if (empty($environment))
  222. {
  223. $files['main'] = 'database';
  224. $files['development'] = 'development/database';
  225. $files['testing'] = 'testing/database';
  226. $files['production'] = 'production/database';
  227. } else
  228. {
  229. $files[$environment] = "$environment/database";
  230. }
  231. // Grab our required settings
  232. foreach ($files as $env => $file)
  233. {
  234. if ( file_exists(APPPATH.'config/'.$file.EXT))
  235. {
  236. include(APPPATH.'config/'.$file.EXT);
  237. }
  238. else if ($fail_gracefully === FALSE)
  239. {
  240. show_error('The configuration file '.$file.EXT.' does not exist.');
  241. }
  242. //Acts as a reseter for given environment and active_group
  243. if (empty($db) && ($new_db !== NULL))
  244. //Do I wanna make sure we won't overwrite existing $db?
  245. //If not, removing empty($db) will always return a new db array for given ENV
  246. {
  247. $db[$new_db]['hostname'] = '';
  248. $db[$new_db]['username'] = '';
  249. $db[$new_db]['password'] = '';
  250. $db[$new_db]['database'] = '';
  251. $db[$new_db]['dbdriver'] = 'mysql';
  252. $db[$new_db]['dbprefix'] = '';
  253. $db[$new_db]['pconnect'] = TRUE;
  254. $db[$new_db]['db_debug'] = TRUE;
  255. $db[$new_db]['cache_on'] = FALSE;
  256. $db[$new_db]['cachedir'] = '';
  257. $db[$new_db]['char_set'] = 'utf8';
  258. $db[$new_db]['dbcollat'] = 'utf8_general_ci';
  259. $db[$new_db]['swap_pre'] = '';
  260. $db[$new_db]['autoinit'] = TRUE;
  261. $db[$new_db]['stricton'] = TRUE;
  262. $db[$new_db]['stricton'] = TRUE;
  263. }
  264. //found file but is empty or clearly malformed
  265. if (empty($db) OR ! is_array($db))
  266. {
  267. //logit('[Config_File_Helper] Corrupt DB ENV file: '.$env,'debug');
  268. continue;
  269. }
  270. $settings[$env] = $db;
  271. unset($db);
  272. }
  273. unset($files);
  274. return $settings;
  275. }
  276. //---------------------------------------------------------------
  277. /*
  278. Function: write_db_config()
  279. Saves the settings to the config/database.php file.
  280. Parameters:
  281. $settings - The array of database settings. Should be in the format:
  282. array(
  283. 'main' => array(
  284. 'setting1' => value,
  285. ...
  286. ),
  287. 'development' => array(
  288. ...
  289. )
  290. );
  291. Return:
  292. true/false
  293. */
  294. function write_db_config($settings=null)
  295. {
  296. if (!is_array($settings ))
  297. {
  298. logit('[Config_File_Helper] Invalid write_db_config PARAMETER!');
  299. return false;
  300. }
  301. foreach ($settings as $env => $values)
  302. {
  303. if (strpos($env, '/') === false)
  304. {
  305. $env .= '/';
  306. }
  307. // Is it the main file?
  308. if ($env == 'main' || $env == 'main/')
  309. {
  310. $env = '';
  311. }
  312. // Load the file so we can loop through the lines
  313. $contents = file_get_contents(APPPATH.'config/'. $env .'database'.EXT);
  314. if (empty($contents) OR ! is_array($contents))
  315. {
  316. //logit('[Config_File_Helper] Error getting db file contents. Loading default database_format.php');
  317. $contents = file_get_contents(APPPATH.'config/database'.EXT);
  318. }
  319. if ($env != 'submit')
  320. {
  321. foreach ($values as $name => $value)
  322. {
  323. // Convert on/off to TRUE/FALSE values
  324. //$value = strtolower($value);
  325. if (strtolower($value) == 'on' || strtolower($value) == 'yes' || strtolower($value) == 'true') $value = 'TRUE';
  326. if (strtolower($value) == 'on' || strtolower($value) == 'no' || strtolower($value) == 'false') $value = 'FALSE';
  327. if ($value != 'TRUE' && $value != 'FALSE')
  328. {
  329. $value = "'$value'";
  330. }
  331. // Is the config setting in the file?
  332. $start = strpos($contents, '$db[\'default\'][\''. $name .'\']');
  333. $end = strpos($contents, ';', $start);
  334. $search = substr($contents, $start, $end-$start+1);
  335. $contents = str_replace($search, '$db[\'default\'][\''. $name .'\'] = '. $value .';', $contents);
  336. }
  337. // Make sure the file still has the php opening header in it...
  338. if (!strpos($contents, '<?php') === FALSE)
  339. {
  340. $contents = '<?php' . "\n" . $contents;
  341. }
  342. $CI = get_instance();
  343. $CI->load->helper('file');;
  344. // Write the changes out...
  345. $result = write_file(APPPATH.'../bonfire/application/config/'.$env .'database'.EXT, $contents);
  346. }
  347. }
  348. return $result;
  349. }
  350. //---------------------------------------------------------------
  351. // End Config helper