示例#1
0
 public function edit($id)
 {
     global $userRoles;
     try {
         $this->result['data']['form'] = $_POST;
         if (filter_var($id, FILTER_VALIDATE_INT) === false) {
             throw new Exception('Идентификатор должен быть целым числом');
         }
         $action = filter_input(INPUT_POST, 'action', FILTER_VALIDATE_INT);
         if ($action === 1) {
             $fio = filter_input(INPUT_POST, 'fio');
             $username = filter_input(INPUT_POST, 'username');
             $password = filter_input(INPUT_POST, 'password');
             $role = filter_input(INPUT_POST, 'role');
             /* username */
             if (!empty($username)) {
                 if ($id === 0) {
                     $result = DB::select("SELECT COUNT(*) as count FROM users WHERE username = '******';", 1);
                 } else {
                     $result = DB::select("SELECT COUNT(*) as count FROM users WHERE username = '******' AND id != {$id};", 1);
                 }
                 if ($result['count'] !== '0') {
                     throw new Exception('Пользователь с таким логином уже существует');
                 }
             } else {
                 throw new Exception('Поле "Имя пользователя" обязательно для заполнения');
             }
             /* password */
             if (!empty($password)) {
                 $passwordHash = Helpers::getPasswordHash($username, $password);
             } else {
                 if ($id === 0) {
                     throw new Exception('Укажите пароль');
                 }
             }
             /* role */
             if (!isset($userRoles[$role])) {
                 throw new exception('Не верная роль');
             }
             if ($id === 0) {
                 DB::query("INSERT INTO users SET\r\n                                  fio = '" . Helpers::escapeString($fio) . "',\r\n                                  role = '" . Helpers::escapeString($role) . "',\r\n                                  password = '******',\r\n                                  username = '******';");
                 $this->result['message'][] = 'Пользователь успешно добавлен.';
             } else {
                 DB::query("UPDATE users SET\r\n                                  fio = '" . Helpers::escapeString($fio) . "',\r\n                                  role = '" . Helpers::escapeString($role) . "',\r\n                                  " . (!empty($passwordHash) ? "password = '******', " : "") . "\r\n                                  username = '******',\r\n                                  date_update = NOW()\r\n                              WHERE id = {$id};");
                 $this->result['message'][] = 'Пользователь успешно изменен.';
             }
             $this->result['data']['form'] = array();
         }
         if ($id > 0) {
             $res = DB::select("SELECT fio, username, role FROM users WHERE id = {$id};", 1);
             $this->result['data']['form'] = $res;
         }
     } catch (Exception $ex) {
         $this->result['success'] = false;
         $this->result['message'][] = $ex->getMessage();
     }
 }
 public function edit($id)
 {
     try {
         $this->result['data']['form'] = $_POST;
         if (filter_var($id, FILTER_VALIDATE_INT) === false) {
             throw new Exception('Идентификатор должен быть целым числом');
         }
         $action = filter_input(INPUT_POST, 'action', FILTER_VALIDATE_INT);
         if ($action === 1) {
             $fio = filter_input(INPUT_POST, 'fio');
             /* fio */
             if (!empty($fio)) {
                 if ($id === 0) {
                     $result = DB::select("SELECT COUNT(*) as count FROM surgeons WHERE fio = '" . Helpers::escapeString($fio) . "';", 1);
                 } else {
                     $result = DB::select("SELECT COUNT(*) as count FROM surgeons WHERE fio = '" . Helpers::escapeString($fio) . "' AND id != {$id};", 1);
                 }
                 if ($result['count'] !== '0') {
                     throw new Exception('Хирург с таким ФИО уже существует');
                 }
             } else {
                 throw new Exception('Поле "ФИО" обязательно для заполнения');
             }
             if ($id === 0) {
                 DB::query("INSERT INTO surgeons SET fio = '" . Helpers::escapeString($fio) . "';");
                 $this->result['message'][] = 'Хирург добавлен.';
             } else {
                 DB::query("UPDATE surgeons SET fio = '" . Helpers::escapeString($fio) . "' WHERE id = {$id};");
                 $this->result['message'][] = 'Данные хирурга изменены.';
             }
             $this->result['data']['form'] = array();
         }
         if ($id > 0) {
             $res = DB::select("SELECT * FROM surgeons WHERE id = {$id};", 1);
             $this->result['data']['form'] = $res;
         }
     } catch (Exception $ex) {
         $this->result['success'] = false;
         $this->result['message'][] = $ex->getMessage();
     }
 }
 public function login()
 {
     try {
         $this->result['data']['form'] = $_POST;
         $login = filter_input(INPUT_POST, 'login');
         $password = filter_input(INPUT_POST, 'password');
         $password = Helpers::getPasswordHash($login, $password);
         $result = DB::select("SELECT * FROM users WHERE username = '******' AND password = '******';");
         if (count($result) !== 1) {
             $_SESSION = array();
             sleep(AUTH_SLEEPTIME_WHEN_ERROR);
             throw new Exception('Не верное сочетание логин/пароль.');
         }
         $_SESSION['failTryAuth'] = 0;
         $_SESSION['user'] = $result[0];
         $_SESSION['isAuth'] = true;
     } catch (Exception $ex) {
         $this->result['success'] = false;
         $this->result['message'][] = $ex->getMessage();
     }
 }
 public function edit($id)
 {
     $this->result['views']['mainContent'] = 'patients/form.php';
     try {
         if ($id === 0 || filter_var($id, FILTER_VALIDATE_INT)) {
             if ($id !== 0) {
                 $res = DB::select("SELECT id, fio, age FROM patients WHERE id = {$id} AND is_delete = 0;", 1);
                 if (!empty($res)) {
                     $this->result['data']['form'] = $res;
                 } else {
                     throw new Exception('Записи с индентификатором «' . $id . '» не существует.');
                 }
             }
         } else {
             throw new Exception('Идентификатор должен быть целым числом');
         }
         $action = (int) filter_input(INPUT_POST, 'action');
         if (!empty($action) && $action === 1) {
             $fio = filter_input(INPUT_POST, 'fio');
             $age = filter_input(INPUT_POST, 'age');
             $this->result['data']['form']['fio'] = $fio;
             $this->result['data']['form']['age'] = $age;
             try {
                 if (empty($fio)) {
                     throw new Exception('Поле "ФИО" не может быть пустым.');
                 }
             } catch (Exception $ex) {
                 $this->result['success'] = false;
                 $this->result['message'][] = $ex->getMessage();
             }
             try {
                 if (empty($age)) {
                     throw new Exception('Поле "Возраст" не может быть пустым.');
                 } elseif (!is_numeric($age)) {
                     throw new Exception('Поле "Возраст" должно состоять только из цифр.');
                 } elseif ($age > 150) {
                     throw new Exception('Не может быть пациентов старше 150 лет.');
                 }
             } catch (Exception $ex) {
                 $this->result['success'] = false;
                 $this->result['message'][] = $ex->getMessage();
             }
             if ($this->result['success'] === true) {
                 if ($id === 0) {
                     $sqlResult = DB::select("SELECT COUNT(*) as count FROM patients WHERE fio = '" . Helpers::escapeString($fio) . "' AND age = {$age} AND is_delete = 0", 1);
                 } else {
                     $sqlResult = DB::select("SELECT COUNT(*) as count FROM patients WHERE fio = '" . Helpers::escapeString($fio) . "' AND age = {$age} AND is_delete = 0 AND id != {$id}", 1);
                 }
                 if ($sqlResult['count'] > 0) {
                     throw new Exception('Пациент с таким ФИО и возрастом уже существует. <a href="/patients/?filter=' . $fio . ' ' . $age . '">Перейти к нему</a>');
                 }
                 if ($this->result['success'] === true) {
                     if ($id === 0) {
                         DB::query("INSERT INTO patients SET\r\n                                          fio = '" . Helpers::escapeString($fio) . "',\r\n                                          age = {$age};");
                         $this->result['message'][] = 'Запись добавлена.';
                         $this->result['fio'] = $fio;
                         $this->result['age'] = $age;
                     } else {
                         DB::query("UPDATE patients SET\r\n                                          fio = '" . Helpers::escapeString($fio) . "',\r\n                                          age = {$age}\r\n                                      WHERE `id` = {$id};");
                         $this->result['message'][] = 'Запись изменена.';
                     }
                 }
             }
         }
     } catch (Exception $ex) {
         $this->result['success'] = false;
         $this->result['message'][] = $ex->getMessage();
     }
 }
示例#5
0
 public function edit($id, $patId)
 {
     $this->result['views']['mainContent'] = 'hosps/form.php';
     try {
         if (filter_var($id, FILTER_VALIDATE_INT) === false) {
             throw new Exception('Идентификатор должен быть целым числом');
         } else {
             if ($id === 0) {
                 if (empty($patId)) {
                     throw new Exception('Отсутствует идентификатор пациента');
                 } else {
                     $res = DB::select("SELECT id FROM patients WHERE id = {$patId} AND is_delete = 0;", 1);
                     if (empty($res)) {
                         throw new Exception('Пациента с индентификатором &laquo;' . $patId . '&raquo; не существует.');
                     }
                 }
             } else {
                 $res = DB::select("SELECT *, DATE_FORMAT(date_begin, '%d.%m.%Y')as date_begin, DATE_FORMAT(date_end, '%d.%m.%Y')as date_end FROM hosps WHERE id = {$id} AND is_delete = 0;", 1);
                 if (!empty($res)) {
                     $this->result['patientId'] = $res['pat_id'];
                     $this->result['data']['form'] = $res;
                 } else {
                     throw new Exception('Госпитализации с индентификатором &laquo;' . $id . '&raquo; не существует.');
                 }
             }
         }
         $action = (int) filter_input(INPUT_POST, 'action');
         if (!empty($action) && $action === 1) {
             $channel = filter_input(INPUT_POST, 'channel', FILTER_VALIDATE_INT);
             $number = filter_input(INPUT_POST, 'number');
             $diagnosis = filter_input(INPUT_POST, 'diagnosis');
             $dateBegin = filter_input(INPUT_POST, 'date_begin');
             $dateEnd = filter_input(INPUT_POST, 'date_end');
             $this->result['data']['form'] = $_POST;
             try {
                 if (!in_array($channel, array(0, 1))) {
                     throw new Exception('Поле "Канал госпитализации" должно быть заполнено');
                 }
                 if (is_numeric($number) && (int) $number > 0) {
                     $res = DB::select("SELECT id FROM hosps WHERE `number` = {$number} AND id != {$id} AND is_delete = 0;", 1);
                     if (!empty($res)) {
                         throw new Exception('Госпитализация с номером "' . $number . '" уже существует в базе');
                     }
                 } else {
                     throw new Exception('Поле "Номер" должно состоять только из цифр больше нуля');
                 }
                 if (empty($diagnosis)) {
                     throw new Exception('Поле "Диагноз" не может быть пустым.');
                 }
                 if (!empty($dateBegin)) {
                     if (preg_match('/^(\\d{2})\\.{1}(\\d{2})\\.{1}(\\d{4})$/', $dateBegin, $dateBegin)) {
                         $dateBegin = $dateBegin[3] . '-' . $dateBegin[2] . '-' . $dateBegin[1];
                     } else {
                         throw new Exception('Поле "Дата госпитализации" должно быть в формате ДД.ММ.ГГГГ');
                     }
                 } else {
                     throw new Exception('Поле "Дата госпитализации" должно быть заполнено');
                 }
                 if (!empty($dateEnd)) {
                     if (preg_match('/^(\\d{2})\\.{1}(\\d{2})\\.{1}(\\d{4})$/', $dateEnd, $dateEnd)) {
                         $dateEnd = $dateEnd[3] . '-' . $dateEnd[2] . '-' . $dateEnd[1];
                     } else {
                         throw new Exception('Поле "Дата выписки" должно быть в формате ДД.ММ.ГГГГ');
                     }
                 } else {
                     throw new Exception('Поле "Дата выписки" должно быть заполнено');
                 }
                 if ($dateBegin > $dateEnd) {
                     throw new exception('Дата госпитализации не может быть позднее чем дата выписки');
                 }
             } catch (Exception $ex) {
                 $this->result['success'] = false;
                 $this->result['message'][] = $ex->getMessage();
             }
             if ($this->result['success'] === true) {
                 if ($id === 0) {
                     DB::query("INSERT INTO hosps SET pat_id = '{$patId}', channel = {$channel}, number = {$number}, diagnosis = '" . Helpers::escapeString($diagnosis) . "', date_begin = '{$dateBegin}', date_end = '{$dateEnd}';");
                     $this->result['message'][] = 'Запись добавлена.';
                 } else {
                     DB::query("UPDATE hosps SET channel = {$channel}, number = {$number}, diagnosis = '" . Helpers::escapeString($diagnosis) . "', date_begin = '{$dateBegin}', date_end = '{$dateEnd}' WHERE id = {$id};");
                     $this->result['message'][] = 'Запись изменена.';
                 }
             }
         }
     } catch (Exception $ex) {
         $this->result['success'] = false;
         $this->result['message'][] = $ex->getMessage();
     }
 }
 public function edit($id, $hospId)
 {
     global $operationFileTypes;
     $this->result['views']['mainContent'] = 'operations/form.php';
     try {
         if (filter_var($id, FILTER_VALIDATE_INT) === false) {
             throw new Exception('Идентификатор должен быть целым числом');
         }
         $action = (int) filter_input(INPUT_POST, 'action');
         if (!empty($action) && $action === 1) {
             $surgeonId = filter_input(INPUT_POST, 'surgeonId');
             $number = filter_input(INPUT_POST, 'number');
             $title = filter_input(INPUT_POST, 'title');
             $date = filter_input(INPUT_POST, 'date');
             $complication = filter_input(INPUT_POST, 'complication');
             $payments = filter_input(INPUT_POST, 'payments');
             $emergency = filter_input(INPUT_POST, 'emergency');
             $dead = filter_input(INPUT_POST, 'dead');
             $reportDetails = filter_input(INPUT_POST, 'reportDetails');
             $this->result['data']['form'] = $_POST;
             try {
                 // Validation
                 /* хирург */
                 if (is_numeric($surgeonId) && (int) $surgeonId > 0) {
                     $res = DB::select("SELECT id FROM surgeons WHERE id = {$surgeonId};", 1);
                     if (empty($res)) {
                         throw new Exception('Хирурга с id="' . $surgeonId . '" не существует');
                     }
                 } else {
                     throw new Exception('Поле "хирург" заполнено не верно');
                 }
                 /* номер */
                 if (!is_numeric($number) || (int) $number < 0) {
                     throw new Exception('Поле "Номер" должно состоять только из цифр больше нуля');
                 }
                 /* дата */
                 if (!empty($date)) {
                     if (preg_match('/^(\\d{2})\\.{1}(\\d{2})\\.{1}(\\d{4})$/', $date, $date)) {
                         $date = $date[3] . '-' . $date[2] . '-' . $date[1];
                     } else {
                         throw new Exception('Поле "Дата" должно быть в формате ДД.ММ.ГГГГ');
                     }
                 } else {
                     throw new Exception('Поле "Дата" должно быть заполнено');
                 }
                 /* плательщик */
                 if (!is_null($payments)) {
                     if (!in_array($payments, array('0', '1', '2'), true)) {
                         throw new Exception('Неверное значение в поле "Плательщик".');
                     }
                 } else {
                     throw new Exception('Укажите, пожалуйста, кто плательщик');
                 }
                 /* срочность */
                 if (empty($emergency) || $emergency !== '1') {
                     $emergency = '0';
                 }
                 /* исход */
                 if (!is_null($dead)) {
                     if (!in_array($dead, array('0', '1'), true)) {
                         throw new Exception('Неверное значение в поле "Исход".');
                     }
                 } else {
                     throw new Exception('Укажите, пожалуйста, исход операции');
                 }
                 /* детализация для отчета */
                 if (!empty($reportDetails)) {
                     if (!is_numeric($reportDetails) || mb_strlen($reportDetails) !== 2) {
                         throw new Exception('Не верный формат детализации для отчета');
                     }
                 } else {
                     throw new Exception('Заполните, пожалуйста, детализацию для отчета');
                 }
             } catch (Exception $ex) {
                 $this->result['success'] = false;
                 $this->result['message'][] = $ex->getMessage();
             }
             if ($this->result['success'] === true) {
                 if ($id === 0) {
                     $operationId = DB::query("INSERT INTO operations SET\r\n                                      hosp_id = {$hospId},\r\n                                      surgeon_id = {$surgeonId},\r\n                                      `number` = {$number},\r\n                                      title = '" . Helpers::escapeString($title) . "',\r\n                                      date = '{$date}',\r\n                                      complication = '" . Helpers::escapeString($complication) . "',\r\n                                      payments = {$payments},\r\n                                      emergency = {$emergency},\r\n                                      dead = {$dead},\r\n                                      report_details = {$reportDetails};", 'lastInsertId');
                     $this->result['message'][] = 'Операция успешно добавлена.';
                 } else {
                     DB::query("UPDATE operations SET\r\n                                      surgeon_id = {$surgeonId},\r\n                                      `number` = {$number},\r\n                                      title = '" . Helpers::escapeString($title) . "',\r\n                                      date = '{$date}',\r\n                                      complication = '" . Helpers::escapeString($complication) . "',\r\n                                      payments = {$payments},\r\n                                      emergency = {$emergency},\r\n                                      dead = {$dead},\r\n                                      report_details = {$reportDetails}\r\n                                  WHERE id = {$id};");
                     $this->result['message'][] = 'Операция успешно изменена.';
                     $operationId = $id;
                     $hospId = DB::select("SELECT hosp_id FROM operations WHERE id = {$operationId};", 1);
                     if (count($hospId) === 1) {
                         $this->result['hospId'] = $hospId['hosp_id'];
                     }
                 }
                 /* Загрузка изображения */
                 if (!empty($_FILES['operationImage']['name'])) {
                     $operationImageTitle = filter_input(INPUT_POST, 'operationImageTitle');
                     if (empty($operationImageTitle)) {
                         $operationImageTitle = $_FILES['operationImage']['name'];
                     }
                     if ($_FILES['operationImage']['error'] > 0) {
                         throw new Exception('При загрузке файла возникла ошибка №.' . $_FILES['operationImage']['error']);
                     }
                     $max_fileSize = min(array((int) ini_get('upload_max_filesize'), (int) ini_get('post_max_size'), 20));
                     if ($_FILES['operationImage']['size'] > $max_fileSize * 1024 * 1024) {
                         throw new Exception('Файл слишком большой. Максимальный размер = ' . $max_fileSize . ' Мб');
                     }
                     preg_match('/\\.([^\\.]{3,})$/i', $_FILES['operationImage']['name'], $extension);
                     if (empty($extension[1])) {
                         throw new Exception('Не удалось определить разширение файла. Проверьте правильность имени файла.');
                     }
                     if (!empty($operationFileTypes[$_FILES['operationImage']['type']])) {
                         $fileType = $operationFileTypes[$_FILES['operationImage']['type']];
                     } else {
                         throw new Exception('Не верный тип файла (' . $_FILES['operationImage']['type'] . ').');
                     }
                     $fileName = md5(md5_file($_FILES['operationImage']['tmp_name']) . time()) . '.' . $extension[1];
                     $fileFolder = DOCUMENT_ROOT . '/operationFiles/' . $fileType . '/';
                     if (file_exists($fileFolder . $fileName)) {
                         throw new Exception('Коллизия. Попробуйте еще раз.');
                     }
                     if (!move_uploaded_file($_FILES['operationImage']['tmp_name'], $fileFolder . $fileName)) {
                         throw new Exception('При перемещении файла возникла ошибка.');
                     }
                     $result = DB::query("INSERT INTO operation_files SET operation_id = {$operationId}, title = '{$operationImageTitle}', file_name = '{$fileName}', `type` = '{$fileType}';");
                     if ($result !== true) {
                         throw new Exception('При добавлении файла возникла sql-ошибка.');
                     }
                 }
                 $res = DB::select("SELECT hosp_id FROM operations WHERE id = {$operationId}", 1);
                 $hospId = (int) $res['hosp_id'];
             }
         } else {
             if ($id === 0) {
                 // Добавление
                 if (empty($hospId)) {
                     throw new Exception('Отсутствует идентификатор госпитализации');
                 } else {
                     $res = DB::select("SELECT id FROM hosps WHERE id = {$hospId} AND is_delete = 0;", 1);
                     if (empty($res)) {
                         throw new Exception('Госпитализации с индентификатором &laquo;' . $hospId . '&raquo; не существует.');
                     }
                 }
             } else {
                 // Редактирование
                 $res = DB::select("SELECT surgeon_id as surgeonId,\r\n                                         report_details as reportDetails,\r\n                                         `number`,\r\n                                         title,\r\n                                         DATE_FORMAT(date, '%d.%m.%Y')as date,\r\n                                         complication,\r\n                                         payments,\r\n                                         emergency,\r\n                                         dead,\r\n                                         report_details as reportDetails\r\n                                     FROM operations WHERE id = {$id} AND is_delete = 0;", 1);
                 if (!empty($res)) {
                     $this->result['data']['form'] = $res;
                 } else {
                     throw new Exception('Госпитализации с индентификатором &laquo;' . $id . '&raquo; не существует.');
                 }
             }
         }
     } catch (Exception $ex) {
         $this->result['success'] = false;
         $this->result['message'][] = $ex->getMessage();
     }
 }
示例#7
0
                break;
            }
        }
        if (!isset($patients[$i]['hosp']['operation']['report_details'])) {
            $validateMessage[] = 'Строка №' . ($i + 1) . '. Не найдена соответсвующая детализация &laquo;' . $row[1] . '&raquo;. Допустимые значения: (' . implode(', ', array_keys($operationDetails)) . ').';
        }
    } else {
        $validateMessage[] = 'Строка №' . ($i + 1) . '. Не указана детализация.';
    }
}
if (!empty($validateMessage)) {
    echo '<div style="color: #FF0000">' . implode('<br/>', $validateMessage) . '</div>';
} else {
    if (!empty($patients)) {
        $count = array('patients' => 0, 'hosps' => 0, 'operations' => 0);
        foreach ($patients as $patient) {
            $sql = "INSERT INTO patients SET\r\n                        fio = '" . Helpers::escapeString($patient['fio']) . "',\r\n                        age = " . $patient['age'] . ";";
            $patient['id'] = DB::query($sql, 'lastInsertId');
            ++$count['patients'];
            if (!empty($patient['hosp'])) {
                $patient['hosp']['id'] = DB::query("INSERT INTO hosps SET pat_id = " . $patient['id'] . ", number = " . $patient['hosp']['number'] . ", diagnosis = '" . Helpers::escapeString($patient['diagnosis']) . "';", 'lastInsertId');
                ++$count['hosps'];
                if (!empty($patient['hosp']['operation'])) {
                    DB::query("INSERT INTO operations SET\r\n                                hosp_id = " . $patient['hosp']['id'] . ",\r\n                                surgeon_id = " . $patient['hosp']['operation']['surgeon_id'] . ",\r\n                                number = " . $patient['hosp']['operation']['number'] . ",\r\n                                title = '" . Helpers::escapeString($patient['hosp']['operation']['title']) . "',\r\n                                date = '" . $patient['hosp']['operation']['date'] . "',\r\n                                complication = '" . Helpers::escapeString($patient['hosp']['operation']['complication']) . "',\r\n                                payments = " . $patient['hosp']['operation']['payments'] . ",\r\n                                dead = " . $patient['hosp']['operation']['dead'] . ",\r\n                                report_details = " . $patient['hosp']['operation']['report_details'] . "\r\n                    ;");
                    ++$count['operations'];
                }
            }
        }
        echo 'Добавление успешно завершено. Добавлено:<br/>' . $count['patients'] . ' пациентов,<br/>' . $count['hosps'] . ' госпитализаций,<br/>' . $count['operations'] . ' операций';
    }
}