make sure pt payments show on statement as pt paid (#4008)
[openemr.git] / sql_upgrade.php
blob46b7089f475695dac71341591ec8a4aa3ab0ad3a
1 <?php
3 // Copyright (C) 2008-2010 Rod Roark <rod@sunsetsystems.com>
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License
7 // as published by the Free Software Foundation; either version 2
8 // of the License, or (at your option) any later version.
9 //
10 // This may be run after an upgraded OpenEMR has been installed.
11 // Its purpose is to upgrade the MySQL OpenEMR database as needed
12 // for the new release.
14 /* @TODO add language selection. needs RTL testing */
16 if (php_sapi_name() === 'cli') {
17 // setting for when running as command line script
18 // need this for output to be readable when running as command line
19 $GLOBALS['force_simple_sql_upgrade'] = true;
22 // Checks if the server's PHP version is compatible with OpenEMR:
23 require_once(__DIR__ . "/src/Common/Compatibility/Checker.php");
24 $response = OpenEMR\Common\Compatibility\Checker::checkPhpVersion();
25 if ($response !== true) {
26 die(htmlspecialchars($response));
29 @ini_set('zlib.output_compression', 0);
30 @ini_set('implicit_flush', 1);
31 @ob_end_clean();
32 // Disable PHP timeout. This will not work in safe mode.
33 @ini_set('max_execution_time', '0');
34 if (ob_get_level() === 0) {
35 ob_start();
38 $ignoreAuth = true; // no login required
39 $sessionAllowWrite = true;
40 $GLOBALS['connection_pooling_off'] = true; // force off database connection pooling
42 require_once('interface/globals.php');
43 require_once('library/sql_upgrade_fx.php');
45 use OpenEMR\Common\Csrf\CsrfUtils;
46 use OpenEMR\Core\Header;
47 use OpenEMR\Services\VersionService;
49 // Force logging off
50 $GLOBALS["enable_auditlog"] = 0;
52 $versions = array();
53 $sqldir = "$webserver_root/sql";
54 $dh = opendir($sqldir);
55 if (!$dh) {
56 die("Cannot read $sqldir");
59 while (false !== ($sfname = readdir($dh))) {
60 if ($sfname[0] === '.') {
61 continue;
64 if (preg_match('/^(\d+)_(\d+)_(\d+)-to-\d+_\d+_\d+_upgrade.sql$/', $sfname, $matches)) {
65 $version = $matches[1] . '.' . $matches[2] . '.' . $matches[3];
66 $versions[$version] = $sfname;
70 closedir($dh);
71 ksort($versions);
73 $res2 = sqlStatement("select * from lang_languages where lang_description = ?", array($GLOBALS['language_default']));
74 for ($iter = 0; $row = sqlFetchArray($res2); $iter++) {
75 $result2[$iter] = $row;
78 if (count($result2) == 1) {
79 $defaultLangID = $result2[0]["lang_id"];
80 $defaultLangName = $result2[0]["lang_description"];
81 $direction = (int)$result2[0]["lang_is_rtl"] === 1 ? 'rtl' : 'ltr';
82 } else {
83 //default to english if any problems
84 $defaultLangID = 1;
85 $defaultLangName = "English";
88 $_SESSION['language_choice'] = $defaultLangID;
89 $_SESSION['language_direction'] = $direction;
90 CsrfUtils::setupCsrfKey();
91 session_write_close();
93 header('Content-type: text/html; charset=utf-8');
96 <!-- @todo Adding DOCTYPE html breaks BS width/height percentages. Why? -->
97 <html>
98 <head>
99 <title>OpenEMR Database Upgrade</title>
100 <?php Header::setupHeader(); ?>
101 <link rel="shortcut icon" href="public/images/favicon.ico" />
102 <script>
103 let currentVersion;
104 let processProgress = 0;
105 let doPoll = 0;
106 let serverPaused = 0;
107 // recursive long polling where ending is based
108 // on global doPoll true or false.
109 // added a forcePollOff parameter to avoid polling from staying on indefinitely when updating from patch.sql
110 async function serverStatus(version = '', start = 0, forcePollOff = 0) {
111 let updateMsg = "";
112 let endMsg = "<li class='text-success bg-light'>" +
113 <?php echo xlj("End watching server processes for upgrade version"); ?> + " " + currentVersion + "</li>";
114 if (version) {
115 currentVersion = version;
116 updateMsg = "<li class='text-light bg-success'>" +
117 <?php echo xlj("Start watching server processes for upgrade version"); ?> + " " + version + "</li>";
120 // start polling
121 let url = "library/ajax/sql_server_status.php?poll=" + encodeURIComponent(currentVersion);
122 let data = new FormData;
123 data.append("csrf_token_form", <?php echo js_escape(CsrfUtils::collectCsrfToken('sqlupgrade')); ?>);
124 data.append("poll", currentVersion);
126 let response = await fetch(url, {
127 method: 'post',
128 body: data
131 if (response.status === 502) {
132 progressStatus("<li class='text-light bg-danger'> ERROR: Restarting. " + response.statusText) + "</li>";
133 // connection timeout, just reconnect
134 if (doPoll) {
135 await serverStatus();
137 } else if (response.status !== 200) {
138 // show error
139 progressStatus("<li class='text-light bg-danger'> ERROR: " + response.statusText) + "</li>";
140 // reconnect in one second
141 if (doPoll) {
142 await serverStatus();
144 } else {
145 // await status
146 let status = await response.text();
147 if (status === 'Internal Server Error') {
148 let errorMsg = "<li class='text-light bg-danger'>" +
149 <?php echo xlj("Stopping activity status checks. Internal Server Error"); ?> +"</li>";
150 progressStatus(errorMsg);
151 // end polling
152 doPoll = 0;
154 if (status === 'Authentication Error') {
155 let errorMsg = "<li class='text-light bg-danger'>" +
156 <?php echo xlj("Stopping status checks. Csrf Error. No harm to upgrade and will continue."); ?> +"</li>";
157 progressStatus(errorMsg);
158 // end polling
159 doPoll = 0;
161 if (version) {
162 progressStatus(updateMsg);
164 if (start === 1) {
165 doPoll = 1;
167 if (forcePollOff === 1) {
168 doPoll = 0;
170 // display to screen div
171 if (status > "") {
172 progressStatus(status);
175 // and so forth.
176 if (doPoll) {
177 await serverStatus();
178 } else {
179 progressStatus(endMsg);
184 * Focus scrolls to bottom of view
185 * */
186 function doScrolls() {
187 let serverStatus = document.getElementById("serverStatus");
188 let isServerBottom = serverStatus.scrollHeight - serverStatus.clientHeight <= serverStatus.scrollTop + 1;
189 let processDetails = document.getElementById("processDetails");
190 let isDetailsBottom = processDetails.scrollHeight - processDetails.clientHeight <= processDetails.scrollTop + 1;
192 if(!isServerBottom) {
193 serverStatus.scrollTop = serverStatus.scrollHeight - serverStatus.clientHeight;
194 }if(!isDetailsBottom) {
195 processDetails.scrollTop = processDetails.scrollHeight - processDetails.clientHeight;
199 function progressStatus(msg = '') {
200 let eventList = document.getElementById('status-message');
201 let progressEl = document.getElementById('progress');
203 progressEl.style.width = processProgress + "%";
204 progressEl.innerHTML = processProgress + "%" + " v" + currentVersion;
205 if (msg) {
206 eventList.innerHTML += msg;
207 doScrolls();
211 function setWarnings(othis) {
212 if (othis.value < '5.0.0') {
213 document.querySelector('.version-warning').classList.remove("d-none");
214 } else {
215 document.querySelector('.version-warning').classList.add("d-none");
219 function pausePoll(othis) {
220 if (serverPaused === 0 && doPoll === 1) {
221 let alertMsg = "<li class='text-dark bg-warning'>" +
222 <?php echo xlj("Paused status checks."); ?> +"</li>";
223 progressStatus(alertMsg);
224 serverPaused = 1;
225 doPoll = 0;
226 document.querySelector('.pause-server').classList.remove("btn-success");
227 document.querySelector('.pause-server').classList.add("btn-warning");
228 } else if (serverPaused === 1) {
229 let alertMsg = "<li class='text-dark bg-success'>" +
230 <?php echo xlj("Resuming status checks."); ?> +"</li>";
231 progressStatus(alertMsg);
232 serverPaused = 0;
233 doPoll = 1;
234 serverStatus('', 1);
235 document.querySelector('.pause-server').classList.remove("btn-warning");
236 document.querySelector('.pause-server').classList.add("btn-success");
239 </script>
240 </head>
241 <body>
242 <div class="container my-3">
243 <div class="row">
244 <div class="col-12">
245 <h2><?php echo xlt("OpenEMR Database Upgrade"); ?></h2>
246 </div>
247 </div>
248 <div>
249 <form class="form-inline" method='post' action='sql_upgrade.php'>
250 <div class="form-group mb-1">
251 <label><?php echo xlt("Please select the prior release you are converting from"); ?>:</label>
252 <select class='mx-3 form-control' name='form_old_version' onchange="setWarnings(this)">
253 <?php
254 $cnt_versions = count($versions);
255 foreach ($versions as $version => $filename) {
256 --$cnt_versions;
257 echo " <option value='$version'";
258 // Defaulting to most recent version or last version in list.
259 if ($cnt_versions === 0) {
260 echo " selected";
262 echo ">$version</option>\n";
265 </select>
266 <span><?php echo xlt("If you are unsure or were using a development version between two releases, then choose the older of possible releases"); ?>.</span>
267 </div>
268 <span class="alert alert-warning text-danger version-warning d-none">
269 <?php echo xlt("If you are upgrading from a version below 5.0.0 to version 5.0.0 or greater, do note that this upgrade can take anywhere from several minutes to several hours (you will only see a whitescreen until it is complete; do not stop the script before it is complete or you risk corrupting your data)"); ?>.
270 </span>
271 <button type='submit' class='btn btn-primary btn-transmit' name='form_submit' value='Upgrade Database'>
272 <?php echo xlt("Upgrade Database"); ?>
273 </button>
274 <div class="btn-group">
275 </div>
276 </form>
277 <!-- server status card -->
278 <div class="card card-header">
279 <span class="btn-group">
280 <a class="btn btn-success pause-server fa fa-pause float-left" onclick="pausePoll(this)" title="<?php echo xla("Click to start or end sql server activity checks."); ?>"></a>
281 <a class="btn btn-primary w-100" data-toggle="collapse" href="#serverStatus">
282 <?php echo xlt("Server Status"); ?><i class="fa fa-angle-down rotate-icon float-right"></i>
283 </a>
284 </span>
285 </div>
286 <div id="serverStatus" class="card card-body pb-2 h-25 overflow-auto collapse show">
287 <div class="bg-light text-dark">
288 <ul id="status-message"></ul>
289 </div>
290 </div>
291 </div>
292 <!-- collapse place holder for upgrade processing on submit. -->
293 <div class="card card-header">
294 <a class="btn btn-primary" data-toggle="collapse" href="#processDetails">
295 <?php echo xlt("Processing Details"); ?><i class="fas fa-angle-down rotate-icon float-right"></i>
296 </a>
297 <div id="progress-div" class="bg-secondary float-left">
298 <div id="progress" class="mt-1 progress-bar bg-success" style="height:1.125rem;width:0;"></div>
299 </div>
300 </div>
301 <div id='processDetails' class='card card-body pb-2 h-50 overflow-auto collapse show'>
302 <div class='bg-light text-dark'>
303 <?php if (!empty($_POST['form_submit'])) {
304 $form_old_version = $_POST['form_old_version'];
306 foreach ($versions as $version => $filename) {
307 if (strcmp($version, $form_old_version) < 0) {
308 continue;
310 // set polling version and start
311 flush_echo("<script>serverStatus(" . js_escape($version) . ", 1);</script>");
312 upgradeFromSqlFile($filename);
313 // end polling
314 sleep(2); // fixes odd bug, where if the sql upgrade goes to fast, then the polling does not stop
315 flush_echo("<script>processProgress = 100;doPoll = 0;</script>");
318 if (!empty($GLOBALS['ippf_specific'])) {
319 // Upgrade custom stuff for IPPF.
320 upgradeFromSqlFile('ippf_upgrade.sql');
323 if ((!empty($v_realpatch)) && ($v_realpatch != "") && ($v_realpatch > 0)) {
324 // This release contains a patch file, so process it.
325 echo "<script>serverStatus('Patch', 0, 1);</script>";
326 upgradeFromSqlFile('patch.sql');
328 flush();
330 echo "<p class='text-success'>" . xlt("Updating global configuration defaults") . "..." . "</p><br />\n";
331 $skipGlobalEvent = true; //use in globals.inc.php script to skip event stuff
332 require_once("library/globals.inc.php");
333 foreach ($GLOBALS_METADATA as $grpname => $grparr) {
334 foreach ($grparr as $fldid => $fldarr) {
335 list($fldname, $fldtype, $flddef, $flddesc) = $fldarr;
336 if (is_array($fldtype) || (substr($fldtype, 0, 2) !== 'm_')) {
337 $row = sqlQuery("SELECT count(*) AS count FROM globals WHERE gl_name = '$fldid'");
338 if (empty($row['count'])) {
339 sqlStatement("INSERT INTO globals ( gl_name, gl_index, gl_value ) " .
340 "VALUES ( '$fldid', '0', '$flddef' )");
346 echo "<p class='text-success'>" . xlt("Updating Access Controls") . "..." . "</p><br />\n";
347 require("acl_upgrade.php");
348 echo "<br />\n";
350 $versionService = new VersionService();
351 $currentVersion = $versionService->fetch();
352 $desiredVersion = $currentVersion;
353 $desiredVersion['v_database'] = $v_database;
354 $desiredVersion['v_tag'] = $v_tag;
355 $desiredVersion['v_realpatch'] = $v_realpatch;
356 $desiredVersion['v_patch'] = $v_patch;
357 $desiredVersion['v_minor'] = $v_minor;
358 $desiredVersion['v_major'] = $v_major;
360 $canRealPatchBeApplied = $versionService->canRealPatchBeApplied($desiredVersion);
361 $line = "Updating version indicators";
363 if ($canRealPatchBeApplied) {
364 $line = $line . ". " . xlt("Patch was also installed, updating version patch indicator");
367 echo "<p class='text-success'>" . $line . "...</p><br />\n";
368 $versionService->update($desiredVersion);
370 echo "<p><p class='text-success'>" . xlt("Database and Access Control upgrade finished.") . "</p></p>\n";
371 echo "</div></body></html>\n";
372 exit();
375 </div>
376 </div>
377 </div>
378 </body>
379 </html>