/** * Replace one or more value pairs in a configuration file. * * @param string $file Path to the file containing the string to replace. * @param array $valuePairs Containing 'old' => 'new' values. * @param bool $root True to write new file as root * @return boolean True if the file was updated successfully */ public static function updateConfigFile($file, $valuePairs, $root = false) { Log::debug("* Updating config file {$file}"); if (!file_exists($file)) { Log::error("* Cannot replace values in non-existent file {$file}"); return false; } $content = file_get_contents($file); # replace and count so we can log meaningfully foreach ($valuePairs as $old => $new) { $content = str_replace($old, $new, $content, $count); if ($count == 0) { Log::warning("* Skipping: nothing to replace, `{$old}` could not be found"); return true; } else { Log::debug("* Replaced {$count} occurences of `{$old}`"); } } # Update file if (!$root) { $result = file_put_contents($file, $content); if (!$result) { Log::error("* Error writing to config file: " . error_get_last()); return false; } } else { $Execute = new CakeboxExecute(); if (!$Execute->shell("echo '{$content}' | sudo tee {$file}", 'root')) { return false; } } Log::info("* Successfully updated config file"); return true; }