$dates = array();
if (!$selection) {
    $selection = CConstantesMedicales::getConstantsByRank('form', true, $host);
} else {
    $selection = CConstantesMedicales::selectConstants($selection, 'form');
}
foreach (CConstantesMedicales::$list_constantes as $key => $cst) {
    $dates["{$key}"] = CMbDT::format(null, '%d/%m/%y');
}
$patient_id = $constantes->patient_id ? $constantes->patient_id : $patient_id;
$patient = CPatient::loadFromGuid("CPatient-{$patient_id}");
$patient->loadRefLatestConstantes(null, array("poids", "taille"), null, false);
$constantes = new CConstantesMedicales();
$constantes->load($const_id);
$constantes->loadRefContext();
$constantes->loadRefPatient();
$constantes->updateFormFields();
// Pour forcer le chargement des unités lors de la saisie d'une nouvelle constante
if ($context) {
    $constantes->patient_id = $patient_id;
    $constantes->context_class = $context->_class;
    $constantes->context_id = $context->_id;
}
$modif_timeout = intval(CAppUI::conf("dPpatients CConstantesMedicales constants_modif_timeout", $host->_guid));
$can_create = $perms->edit;
if ($perms->edit && $constantes->_id && $modif_timeout > 0 && time() - strtotime($constantes->datetime) > $modif_timeout * 3600) {
    $can_edit = 0;
} else {
    $modif_timeout = 0;
}
/* Gestion des droits d'edition sur les constantes */
 /**
  * Get the latest constantes values
  *
  * @param int|CPatient $patient   The patient to load the constantes for
  * @param string       $datetime  The reference datetime
  * @param array        $selection A selection of constantes to load
  * @param CMbObject    $context   The context
  * @param boolean      $use_cache Force the function to return the latest_values is already set
  *
  * @return array The constantes values and dates
  */
 static function getLatestFor($patient, $datetime = null, $selection = array(), $context = null, $use_cache = true)
 {
     $patient_id = $patient instanceof CPatient ? $patient->_id : $patient;
     if (isset(self::$_latest_values[$patient_id][$datetime]) && $use_cache === true) {
         return self::$_latest_values[$patient_id][$datetime];
     }
     if (empty($selection)) {
         $list_constantes = CConstantesMedicales::$list_constantes;
     } else {
         $list_constantes = array_intersect_key(CConstantesMedicales::$list_constantes, array_flip($selection));
     }
     // Constante que l'on va construire
     $constante = new CConstantesMedicales();
     if (!$patient_id) {
         return array($constante, array());
     }
     $constante->patient_id = $patient_id;
     $constante->datetime = CMbDT::dateTime();
     $constante->loadRefPatient();
     $where = array("patient_id" => "= '{$patient_id}'");
     if ($context) {
         $where["context_class"] = " = '{$context->_class}'";
         $where["context_id"] = " = '{$context->_id}'";
     }
     if ($datetime) {
         $where["datetime"] = "<= '{$datetime}'";
     }
     if (count($selection)) {
         $ors = array();
         foreach ($selection as $_item) {
             $ors[] = "{$_item} IS NOT NULL";
         }
         $where[] = implode(" OR ", $ors);
     }
     $count = $constante->countList($where);
     // Load all constants instead of checking every type to reduce number of SQL queries
     /** @var self[] $all_list */
     $all_list = array();
     if ($count <= 30) {
         $all_list = $constante->loadList($where, "datetime DESC");
     }
     $list_datetimes = array();
     foreach ($list_constantes as $type => $params) {
         $list_datetimes[$type] = null;
         if ($type[0] == "_") {
             continue;
         }
         // Load them, if any ...
         if ($count > 0) {
             // Load them all and dispatch
             if ($count <= 30) {
                 foreach ($all_list as $_const) {
                     $_value = $_const->{$type};
                     if ($_value != null) {
                         $constante->{$type} = $_value;
                         $list_datetimes[$type] = $_const->datetime;
                         break;
                     }
                 }
             } else {
                 $_where = $where;
                 $_where[$type] = "IS NOT NULL";
                 $_list = $constante->loadList($_where, "datetime DESC", 1);
                 if (count($_list)) {
                     $_const = reset($_list);
                     $constante->{$type} = $_const->{$type};
                     $list_datetimes[$type] = $_const->datetime;
                 }
             }
         }
     }
     // Cumul de la diurese
     if ($datetime) {
         foreach ($list_constantes as $_name => $_params) {
             if (isset($_params["cumul_reset_config"]) || isset($_params["formula"])) {
                 $day_defore = CMbDT::dateTime("-24 hours", $datetime);
                 if (isset($_params["cumul_reset_config"]) && !isset($_params['formula'])) {
                     $cumul_field = '_' . $_name . '_cumul';
                     $reset_hour = str_pad(self::getHostConfig($_params["cumul_reset_config"], $context), 2, '0', STR_PAD_LEFT);
                     $cumul_begin = '';
                     $cumul_end = '';
                     if ($datetime >= CMbDT::format($datetime, "%Y-%m-%d {$reset_hour}:00:00")) {
                         $cumul_begin = CMbDT::format($datetime, "%Y-%m-%d {$reset_hour}:00:00");
                         $cumul_end = CMbDT::format(CMbDT::date('+1 DAY', $datetime), "%Y-%m-%d {$reset_hour}:00:00");
                     } else {
                         $cumul_begin = CMbDT::format(CMbDT::date('-1 DAY', $datetime), "%Y-%m-%d {$reset_hour}:00:00");
                         $cumul_end = CMbDT::format($datetime, "%Y-%m-%d {$reset_hour}:00:00");
                     }
                     $query = new CRequest();
                     $query->addSelect("SUM(`{$_name}`)");
                     $query->addTable('constantes_medicales');
                     $query->addWhere(array("`datetime` >= '{$cumul_begin}'", "`datetime` <= '{$cumul_end}'", "`{$_name}` IS NOT NULL", "`patient_id` = {$patient_id}"));
                     $ds = CSQLDataSource::get('std');
                     $constante->{$cumul_field} = $ds->loadResult($query->makeSelect());
                 } else {
                     // cumul de plusieurs champs (avec formule)
                     $formula = $_params["formula"];
                     foreach ($formula as $_field => $_sign) {
                         $_where = $where;
                         $_where[$_field] = "IS NOT NULL";
                         $_where[] = "datetime >= '{$day_defore}'";
                         $_list = $constante->loadList($_where);
                         foreach ($_list as $_const) {
                             if ($_sign === "+") {
                                 $constante->{$_name} += $_const->{$_field};
                             } else {
                                 $constante->{$_name} -= $_const->{$_field};
                             }
                         }
                     }
                 }
             }
         }
     }
     $constante->updateFormFields();
     // Don't cache partial loadings
     if (empty($selection)) {
         self::$_latest_values[$patient_id][$datetime] = array($constante, $list_datetimes);
     }
     return array($constante, $list_datetimes);
 }