3 // Copyright (C) 2008-2010 Rod Roark <rod@sunsetsystems.com>
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.
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 $GLOBALS['ongoing_sql_upgrade'] = true;
18 if (php_sapi_name() === 'cli') {
19 // setting for when running as command line script
20 // need this for output to be readable when running as command line
21 $GLOBALS['force_simple_sql_upgrade'] = true;
24 // Checks if the server's PHP version is compatible with OpenEMR:
25 require_once(__DIR__
. "/src/Common/Compatibility/Checker.php");
26 $response = OpenEMR\Common\Compatibility\Checker
::checkPhpVersion();
27 if ($response !== true) {
28 die(htmlspecialchars($response));
31 @ini_set
('zlib.output_compression', 0);
32 @ini_set
('implicit_flush', 1);
34 // Disable PHP timeout. This will not work in safe mode.
35 @ini_set
('max_execution_time', '0');
36 if (ob_get_level() === 0) {
40 $ignoreAuth = true; // no login required
41 $sessionAllowWrite = true;
42 $GLOBALS['connection_pooling_off'] = true; // force off database connection pooling
44 require_once('interface/globals.php');
45 require_once('library/sql_upgrade_fx.php');
47 use OpenEMR\Common\Csrf\CsrfUtils
;
48 use OpenEMR\Common\Uuid\UuidRegistry
;
49 use OpenEMR\Core\Header
;
50 use OpenEMR\Services\VersionService
;
53 $GLOBALS["enable_auditlog"] = 0;
56 $sqldir = "$webserver_root/sql";
57 $dh = opendir($sqldir);
59 die("Cannot read $sqldir");
62 while (false !== ($sfname = readdir($dh))) {
63 if ($sfname[0] === '.') {
67 if (preg_match('/^(\d+)_(\d+)_(\d+)-to-\d+_\d+_\d+_upgrade.sql$/', $sfname, $matches)) {
68 $version = $matches[1] . '.' . $matches[2] . '.' . $matches[3];
69 $versions[$version] = $sfname;
76 $res2 = sqlStatement("select * from lang_languages where lang_description = ?", array($GLOBALS['language_default']));
77 for ($iter = 0; $row = sqlFetchArray($res2); $iter++
) {
78 $result2[$iter] = $row;
81 if (count($result2) == 1) {
82 $defaultLangID = $result2[0]["lang_id"];
83 $defaultLangName = $result2[0]["lang_description"];
84 $direction = (int)$result2[0]["lang_is_rtl"] === 1 ?
'rtl' : 'ltr';
86 //default to english if any problems
88 $defaultLangName = "English";
91 $_SESSION['language_choice'] = $defaultLangID;
92 $_SESSION['language_direction'] = $direction;
93 CsrfUtils
::setupCsrfKey();
94 session_write_close();
96 header('Content-type: text/html; charset=utf-8');
99 <!-- @todo Adding DOCTYPE html breaks BS width
/height percentages
. Why?
-->
102 <title
>OpenEMR Database Upgrade
</title
>
103 <?php Header
::setupHeader(); ?
>
104 <link rel
="shortcut icon" href
="public/images/favicon.ico" />
107 let processProgress
= 0;
109 let serverPaused
= 0;
110 // recursive long polling where ending is based
111 // on global doPoll true or false.
112 // added a forcePollOff parameter to avoid polling from staying on indefinitely when updating from patch.sql
113 async
function serverStatus(version
= '', start
= 0, forcePollOff
= 0) {
115 let endMsg
= "<li class='text-success bg-light'>" +
116 <?php
echo xlj("End watching server processes for upgrade version"); ?
> +
" " + currentVersion +
"</li>";
118 currentVersion
= version
;
119 updateMsg
= "<li class='text-light bg-success'>" +
120 <?php
echo xlj("Start watching server processes for upgrade version"); ?
> +
" " + version +
"</li>";
124 let url
= "library/ajax/sql_server_status.php?poll=" +
encodeURIComponent(currentVersion
);
125 let data
= new FormData
;
126 data
.append("csrf_token_form", <?php
echo js_escape(CsrfUtils
::collectCsrfToken('sqlupgrade')); ?
>);
127 data
.append("poll", currentVersion
);
129 let response
= await
fetch(url
, {
134 if (response
.status
=== 502) {
135 progressStatus("<li class='text-light bg-danger'> ERROR: Restarting. " + response
.statusText
) +
"</li>";
136 // connection timeout, just reconnect
138 await
serverStatus();
140 } else if (response
.status
!== 200) {
142 progressStatus("<li class='text-light bg-danger'> ERROR: " + response
.statusText
) +
"</li>";
143 // reconnect in one second
145 await
serverStatus();
149 let status
= await response
.text();
150 if (status
=== 'Internal Server Error') {
151 let errorMsg
= "<li class='text-light bg-danger'>" +
152 <?php
echo xlj("Stopping activity status checks. Internal Server Error"); ?
> +
"</li>";
153 progressStatus(errorMsg
);
157 if (status
=== 'Authentication Error') {
158 let errorMsg
= "<li class='text-light bg-danger'>" +
159 <?php
echo xlj("Stopping status checks. Csrf Error. No harm to upgrade and will continue."); ?
> +
"</li>";
160 progressStatus(errorMsg
);
165 progressStatus(updateMsg
);
170 if (forcePollOff
=== 1) {
173 // display to screen div
175 progressStatus(status
);
180 await
serverStatus();
182 progressStatus(endMsg
);
187 * Focus scrolls to bottom of view
189 function doScrolls() {
190 let serverStatus
= document
.getElementById("serverStatus");
191 let isServerBottom
= serverStatus
.scrollHeight
- serverStatus
.clientHeight
<= serverStatus
.scrollTop +
1;
192 let processDetails
= document
.getElementById("processDetails");
193 let isDetailsBottom
= processDetails
.scrollHeight
- processDetails
.clientHeight
<= processDetails
.scrollTop +
1;
195 if(!isServerBottom
) {
196 serverStatus
.scrollTop
= serverStatus
.scrollHeight
- serverStatus
.clientHeight
;
197 }if(!isDetailsBottom
) {
198 processDetails
.scrollTop
= processDetails
.scrollHeight
- processDetails
.clientHeight
;
202 function progressStatus(msg
= '') {
203 let eventList
= document
.getElementById('status-message');
204 let progressEl
= document
.getElementById('progress');
206 if (currentVersion
== "UUID") {
207 if (processProgress
< 30) {
209 } else if (processProgress
< 40) {
210 if (Math
.random() > 0.9) {
213 } else if (processProgress
< 50) {
214 if (Math
.random() > 0.95) {
217 } else if (processProgress
< 60) {
218 if (Math
.random() > 0.97) {
221 } else if (processProgress
< 70) {
222 if (Math
.random() > 0.98) {
225 } else if (processProgress
< 80) {
226 if (Math
.random() > 0.99) {
229 } else if (processProgress
< 96) {
230 if (Math
.random() > 0.999) {
233 } else if (processProgress
< 99) {
234 if (Math
.random() > 0.9999) {
238 progressEl
.style
.width
= processProgress +
"%";
239 progressEl
.innerHTML
= processProgress +
"%" +
" UUID Update";
241 progressEl
.style
.width
= processProgress +
"%";
242 progressEl
.innerHTML
= processProgress +
"%" +
" v" + currentVersion
;
245 eventList
.innerHTML +
= msg
;
250 function setWarnings(othis
) {
251 if (othis
.value
< '5.0.0') {
252 document
.querySelector('.version-warning').classList
.remove("d-none");
254 document
.querySelector('.version-warning').classList
.add("d-none");
258 function pausePoll(othis
) {
259 if (serverPaused
=== 0 && doPoll
=== 1) {
260 let alertMsg
= "<li class='text-dark bg-warning'>" +
261 <?php
echo xlj("Paused status checks."); ?
> +
"</li>";
262 progressStatus(alertMsg
);
265 document
.querySelector('.pause-server').classList
.remove("btn-success");
266 document
.querySelector('.pause-server').classList
.add("btn-warning");
267 } else if (serverPaused
=== 1) {
268 let alertMsg
= "<li class='text-dark bg-success'>" +
269 <?php
echo xlj("Resuming status checks."); ?
> +
"</li>";
270 progressStatus(alertMsg
);
274 document
.querySelector('.pause-server').classList
.remove("btn-warning");
275 document
.querySelector('.pause-server').classList
.add("btn-success");
281 <div
class="container my-3">
284 <h2
><?php
echo xlt("OpenEMR Database Upgrade"); ?
></h2
>
288 <form
class="form-inline" method
='post' action
='sql_upgrade.php'>
289 <div
class="form-group mb-1">
290 <label
><?php
echo xlt("Please select the prior release you are converting from"); ?
>:</label
>
291 <select
class='mx-3 form-control' name
='form_old_version' onchange
="setWarnings(this)">
293 $cnt_versions = count($versions);
294 foreach ($versions as $version => $filename) {
296 echo " <option value='$version'";
297 // Defaulting to most recent version or last version in list.
298 if ($cnt_versions === 0) {
301 echo ">$version</option>\n";
305 <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
>
307 <span
class="alert alert-warning text-danger version-warning d-none">
308 <?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)"); ?
>.
310 <button type
='submit' class='btn btn-primary btn-transmit' name
='form_submit' value
='Upgrade Database'>
311 <?php
echo xlt("Upgrade Database"); ?
>
313 <div
class="btn-group">
316 <!-- server status card
-->
317 <div
class="card card-header">
318 <span
class="btn-group">
319 <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
>
320 <a
class="btn btn-primary w-100" data
-toggle
="collapse" href
="#serverStatus">
321 <?php
echo xlt("Server Status"); ?
><i
class="fa fa-angle-down rotate-icon float-right"></i
>
325 <div id
="serverStatus" class="card card-body pb-2 h-25 overflow-auto collapse show">
326 <div
class="bg-light text-dark">
327 <ul id
="status-message"></ul
>
331 <!-- collapse place holder
for upgrade processing on submit
. -->
332 <div
class="card card-header">
333 <a
class="btn btn-primary" data
-toggle
="collapse" href
="#processDetails">
334 <?php
echo xlt("Processing Details"); ?
><i
class="fas fa-angle-down rotate-icon float-right"></i
>
336 <div id
="progress-div" class="bg-secondary float-left">
337 <div id
="progress" class="mt-1 progress-bar bg-success" style
="height:1.125rem;width:0;"></div
>
340 <div id
='processDetails' class='card card-body pb-2 h-50 overflow-auto collapse show'>
341 <div
class='bg-light text-dark'>
342 <?php
if (!empty($_POST['form_submit'])) {
343 $form_old_version = $_POST['form_old_version'];
345 foreach ($versions as $version => $filename) {
346 if (strcmp($version, $form_old_version) < 0) {
349 // set polling version and start
350 flush_echo("<script>serverStatus(" . js_escape($version) . ", 1);</script>");
351 upgradeFromSqlFile($filename);
353 sleep(2); // fixes odd bug, where if the sql upgrade goes to fast, then the polling does not stop
354 flush_echo("<script>processProgress = 100;doPoll = 0;</script>");
357 if (!empty($GLOBALS['ippf_specific'])) {
358 // Upgrade custom stuff for IPPF.
359 upgradeFromSqlFile('ippf_upgrade.sql');
362 if ((!empty($v_realpatch)) && ($v_realpatch != "") && ($v_realpatch > 0)) {
363 // This release contains a patch file, so process it.
364 echo "<script>serverStatus('Patch', 0, 1);</script>";
365 upgradeFromSqlFile('patch.sql');
369 echo "<br /><p class='text-success'>Updating UUIDs (this could take some time)<br />\n";
370 flush_echo("<script>processProgress = 10; serverStatus('UUID', 1);</script>");
371 $updateUuidLog = UuidRegistry
::populateAllMissingUuids();
372 if (!empty($updateUuidLog)) {
373 echo "Updated UUIDs: " . text($updateUuidLog) . "</p><br />\n";
375 echo "Did not need to update or add any new UUIDs</p><br />\n";
377 sleep(2); // fixes odd bug, where if process goes to fast, then the polling does not stop
378 flush_echo("<script>processProgress = 100;doPoll = 0;</script>");
380 echo "<p class='text-success'>" . xlt("Updating global configuration defaults") . "..." . "</p><br />\n";
381 $skipGlobalEvent = true; //use in globals.inc.php script to skip event stuff
382 require_once("library/globals.inc.php");
383 foreach ($GLOBALS_METADATA as $grpname => $grparr) {
384 foreach ($grparr as $fldid => $fldarr) {
385 list($fldname, $fldtype, $flddef, $flddesc) = $fldarr;
386 if (is_array($fldtype) ||
(substr($fldtype, 0, 2) !== 'm_')) {
387 $row = sqlQuery("SELECT count(*) AS count FROM globals WHERE gl_name = '$fldid'");
388 if (empty($row['count'])) {
389 sqlStatement("INSERT INTO globals ( gl_name, gl_index, gl_value ) " .
390 "VALUES ( '$fldid', '0', '$flddef' )");
396 echo "<p class='text-success'>" . xlt("Updating Access Controls") . "..." . "</p><br />\n";
397 require("acl_upgrade.php");
400 $versionService = new VersionService();
401 $currentVersion = $versionService->fetch();
402 $desiredVersion = $currentVersion;
403 $desiredVersion['v_database'] = $v_database;
404 $desiredVersion['v_tag'] = $v_tag;
405 $desiredVersion['v_realpatch'] = $v_realpatch;
406 $desiredVersion['v_patch'] = $v_patch;
407 $desiredVersion['v_minor'] = $v_minor;
408 $desiredVersion['v_major'] = $v_major;
410 $canRealPatchBeApplied = $versionService->canRealPatchBeApplied($desiredVersion);
411 $line = "Updating version indicators";
413 if ($canRealPatchBeApplied) {
414 $line = $line . ". " . xlt("Patch was also installed, updating version patch indicator");
417 echo "<p class='text-success'>" . $line . "...</p><br />\n";
418 $versionService->update($desiredVersion);
420 echo "<p><p class='text-success'>" . xlt("Database and Access Control upgrade finished.") . "</p></p>\n";
421 echo "</div></body></html>\n";