diff --git a/seed/galette/dictionaries/40_galette.xml b/seed/galette/dictionaries/40_galette.xml new file mode 100644 index 0000000..55e7a87 --- /dev/null +++ b/seed/galette/dictionaries/40_galette.xml @@ -0,0 +1,9 @@ + + + + + /etc/galette/config.inc.php + /etc/nginx/default.d/galette.conf + + + diff --git a/seed/galette/extras/machine/20_sensmotdire.xml b/seed/galette/extras/machine/20_sensmotdire.xml new file mode 100644 index 0000000..ac4f5b3 --- /dev/null +++ b/seed/galette/extras/machine/20_sensmotdire.xml @@ -0,0 +1,20 @@ + + + + + 256 + + + False + + + False + + + False + + + 512 + + + diff --git a/seed/galette/manual/image/postinstall/galette.sh b/seed/galette/manual/image/postinstall/galette.sh new file mode 100644 index 0000000..8dc7e16 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette.sh @@ -0,0 +1,8 @@ +set -e + +mkdir -p "$IMAGE_NAME_RISOTTO_IMAGE_DIR_TMP/usr/local/share" +cp -a $IMAGE_DIR_RECIPIENT_IMAGE/postinstall/galette "$IMAGE_NAME_RISOTTO_IMAGE_DIR_TMP/usr/local/share" +chown -R root: "$IMAGE_NAME_RISOTTO_IMAGE_DIR_TMP/usr/local/share/galette" +ln -s /etc/galette/config.inc.php "$IMAGE_NAME_RISOTTO_IMAGE_DIR_TMP/usr/local/share/galette/includes/config.inc.php" + +cd $ORIPWD diff --git a/seed/galette/manual/image/postinstall/galette/ajouter_adherent.php b/seed/galette/manual/image/postinstall/galette/ajouter_adherent.php new file mode 100644 index 0000000..9628b29 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/ajouter_adherent.php @@ -0,0 +1,810 @@ + modif ou création + $values = Array(); + $id_adh = ""; + $values['date_crea_adh'] = ""; + if (isset($_GET["id_adh"])) + if (is_numeric($_GET["id_adh"])) + $id_adh = $_GET["id_adh"]; + if (isset($_POST["id_adh"])) + if (is_numeric($_POST["id_adh"])) + $id_adh = $_POST["id_adh"]; + + // Si c'est un user qui est loggé, on va à sa fiche + if ($_SESSION["admin_status"]!=1) + $id_adh = $_SESSION["logged_id_adh"]; + $values['id_adh'] = $id_adh; + // variables d'erreur (pour affichage) + $error_detected = ""; + $warning_detected = ""; + $confirm_detected = ""; + + // + // DEBUT parametrage des champs + // On recupere de la base la longueur et les flags des champs + // et on initialise des valeurs par defaut + + // recuperation de la liste de champs de la table + $fields = $DB->MetaColumns(PREFIX_DB."adherents"); + foreach ($fields as $champ => $proprietes) + { + $proprietes_arr = get_object_vars($proprietes); + // on obtient name, max_length, type, not_null, has_default, primary_key, + // auto_increment et binary + + $fieldname = $proprietes_arr["name"]; + + // on ne met jamais a jour id_adh + if ($fieldname!="id_adh" && $fieldname!="date_echeance") + $$fieldname= ""; + + $fieldlen = $fieldname."_len"; + $fieldreq = $fieldname."_req"; + + // definissons aussi la longueur des input text + $max_tmp = $proprietes_arr["max_length"]; + if ($max_tmp == "-1") + $max_tmp = 10; + $fieldlen = $fieldname."_len"; + $$fieldlen=$max_tmp; + + // et s'ils sont obligatoires (à partir de la base) + if ($proprietes_arr["not_null"]==1) + $$fieldreq = "style=\"color: #FF0000;\""; + else + $$fieldreq = ""; + } + reset($fields); + + // et les valeurs par defaut + $id_statut = "4"; + $values['titre_adh'] = "1"; + + // + // FIN parametrage des champs + // + + // + // Validation du formulaire + // + + if (isset($_POST["valid"])) + { + // verification de champs + $update_string = ""; + $insert_string_fields = ""; + $insert_string_values = ""; + + // recuperation de la liste de champs de la table + foreach ($fields as $champ => $proprietes) + { + $proprietes_arr = get_object_vars($proprietes); + // on obtient name, max_length, type, not_null, has_default, primary_key, + // auto_increment et binary + + $fieldname = $proprietes_arr["name"]; + + // on précise les champs non modifiables + if ( + ($_SESSION["admin_status"]==1 && $fieldname!="id_adh" + && $fieldname!="date_echeance") || + ($_SESSION["admin_status"]==0 && $fieldname!="date_crea_adh" + && $fieldname!="panier_adh" + && $fieldname!="pain_adh" + && $fieldname!="volaille_adh" + && $fieldname!="chevre_adh" + && $fieldname!="boeuf_adh" + && $fieldname!="veau_adh" + && $fieldname!="cochon_adh" + && $fieldname!="farine_adh" + && $fieldname!="id_adh" + && $fieldname!="titre_adh" + && $fieldname!="id_statut" + && $fieldname!="nom_adh" + && $fieldname!="prenom_adh" + && $fieldname!="activite_adh" + && $fieldname!="bool_exempt_adh" + && $fieldname!="bool_admin_adh" + && $fieldname!="date_echeance" + && $fieldname!="info_adh") + ) + { + if (isset($_POST[$fieldname])) + $post_value=trim($_POST[$fieldname]); + else + $post_value=""; + // on declare les variables pour la présaisie en cas d'erreur + $values[$fieldname] = htmlentities(stripslashes($post_value),ENT_QUOTES); + $fieldreq = $fieldname."_req"; + + // vérification de la présence des champs obligatoires + if ($$fieldreq!="" && $post_value=="") + $error_detected .= "
  • "._T("- Champ obligatoire non renseigné.")."
  • "; + else + { + // validation des dates + if($proprietes_arr["type"]=="date" && $post_value!="") + { + if (preg_match("/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/", $post_value, $array_jours) || $post_value=="") + { + if (checkdate($array_jours[2],$array_jours[1],$array_jours[3]) || $post_value=="") +// $value=$DB->DBDate(mktime(0,0,0,$array_jours[2],$array_jours[1],$array_jours[3])); + $value = $DB->DBDate($array_jours[3].'/'.$array_jours[2].'/'.$array_jours[1]); + else + $error_detected .= "
  • "._T("- Date non valide !")."
  • "; + } + else + $error_detected .= "
  • "._T("- Mauvais format de date (jj/mm/aaaa) !")."
  • "; + } + elseif ($fieldname=="email_adh") + { + $post_value=strtolower($post_value); + if (!is_valid_email($post_value) && $post_value!="") + $error_detected .= "
  • "._T("- Adresse E-mail non valide !")."
  • "; + else + $value = $DB->qstr($post_value, true); + + if ($post_value=="" && isset($_POST["mail_confirm"])) + $error_detected .= "
  • "._T("- Vous ne pouvez pas envoyer de confirmation par mail si l'adhérent n'a pas d'adresse !")."
  • "; + } + elseif ($fieldname=="url_adh") + { + if (!is_valid_web_url($post_value) && $post_value!="" && $post_value!="http://") + $error_detected .= "
  • "._T("- Adresse web non valide ! Oubli du http:// ?")."
  • "; + else + { + if ($post_value=="http://") + $post_value=""; + $value = $DB->qstr($post_value, true); + } + } + elseif ($fieldname=="login_adh") + { + if (strlen($post_value)<4) + $error_detected .= "
  • "._T("- L'identifiant doit être composé d'au moins 4 caractères !")."
  • "; + else + { + // on vérifie que le login n'est pas déjà utilisé + $requete = "SELECT id_adh + FROM ".PREFIX_DB."adherents + WHERE login_adh=". $DB->qstr($post_value, true); + if ($id_adh!="") + $requete .= " AND id_adh!=" . $DB->qstr($id_adh, true); +echo $requete; + $result = $DB->Execute($requete); + if (!$result->EOF || $post_value==PREF_ADMIN_LOGIN) + $error_detected .= "
  • "._T("- Cet identifiant est déjà utilisé par un autre adhérent !")."
  • "; + else + $value = $DB->qstr($post_value, true); + } + } + elseif ($fieldname=="mdp_adh") + { + if (strlen($post_value)<4) + $error_detected .= "
  • "._T("- Le mot de passe doit être composé d'au moins 4 caractères !")."
  • "; + else + $value = $DB->qstr($post_value, true); + } + else + { + // on se contente d'escaper le html et les caracteres speciaux + $value = $DB->qstr($post_value, true); + } + + // mise à jour des chaines d'insertion/update + if ($value=="''") + $value="NULL"; + $update_string .= ",".$fieldname."=".$value; + $insert_string_fields .= ",".$fieldname; + $insert_string_values .= ",".$value; + } + } + } + reset($fields); + + // modif ou ajout + if ($error_detected=="") + { + if ($id_adh!="") + { + // modif + + $requete = "UPDATE ".PREFIX_DB."adherents + SET " . substr($update_string,1) . " + WHERE id_adh=" . $id_adh; + $DB->Execute("SET NAMES utf8"); + $DB->Execute($requete); + $DB->Execute("SET NAMES latin1"); + $result = $DB->Execute("SET NAMES latin1"); + dblog(_T("Mise à jour de la fiche adhérent :")." ".strtoupper($_POST["nom_adh"])." ".$_POST["prenom_adh"], $requete); + + $date_fin = get_echeance($DB, $id_adh); + if ($date_fin!="") +// $date_fin_update = $DB->DBDate(mktime(0,0,0,$date_fin[1],$date_fin[0],$date_fin[2])); + $date_fin_update = $DB->DBDate($date_fin[2].'/'.$date_fin[1].'/'.$date_fin[0]); + else + $date_fin_update = "NULL"; + $requete = "UPDATE ".PREFIX_DB."adherents + SET date_echeance=".$date_fin_update." + WHERE id_adh=" . $id_adh; + } + else + { + // ajout + $insert_string_fields = substr($insert_string_fields,1); + $insert_string_values = substr($insert_string_values,1); + $requete = "INSERT INTO ".PREFIX_DB."adherents + (" . $insert_string_fields . ") + VALUES (" . $insert_string_values . ")"; + dblog(_T("Ajout de la fiche adhérent :")." ".strtoupper($_POST["nom_adh"])." ".$_POST["prenom_adh"], $requete); + + } + if ($DB->Execute($requete) === false) { + print 'error inserting: '. $DB->ErrorMsg().'
    '; + return; + }; + // il est temps d'envoyer un mail + if (isset($_POST["mail_confirm"])) + if ($_POST["mail_confirm"]=="1") + if ($email_adh!="") + { + $mail_subject = _T("Vos identifiants Galette"); + $mail_text = _T("Bonjour,")."\n"; + $mail_text .= "\n"; + $mail_text .= _T("Vous venez d'être inscrit sur le système de gestion d'adhérents de l'association.")."\n"; + $mail_text .= _T("Il vous est désormais possible de suivre en temps réel l'état de votre adhésion")."\n"; + $mail_text .= _T("et de mettre à jour vos coordonnées par l'interface web prévue à cet effet.")."\n"; + $mail_text .= "\n"; + $mail_text .= _T("Veuillez vous identifier à cette adresse :")."\n"; + $mail_text .= "http://".$_SERVER["SERVER_NAME"].dirname($_SERVER["REQUEST_URI"])."\n"; + $mail_text .= "\n"; + $mail_text .= _T("Identifiant :")." ".custom_html_entity_decode($values['login_adh'])."\n"; + $mail_text .= _T("Mot de passe :")." ".custom_html_entity_decode($values['mdp_adh'])."\n"; + $mail_text .= "\n"; + $mail_text .= _T("A très bientôt !")."\n"; + $mail_text .= "\n"; + $mail_text .= _T("(ce mail est un envoi automatique)")."\n"; + $mail_headers = "From: ".PREF_EMAIL_NOM." <".PREF_EMAIL.">\n"; + mail ($email_adh,$mail_subject,$mail_text, $mail_headers); + } + + // récupération du max pour insertion photo + // ou passage en mode modif apres insertion + if ($id_adh=="") + { + $requete = "SELECT max(id_adh) + AS max + FROM ".PREFIX_DB."adherents"; + $max = $DB->Execute($requete); + $id_adh_new = $max->fields["max"]; + } + else + $id_adh_new = $id_adh; + + if (isset($_FILES["photo"]["tmp_name"])) + if ($_FILES["photo"]["tmp_name"]!="none" && + $_FILES["photo"]["tmp_name"]!="") + { + + if ($_FILES['photo']['type']=="image/jpeg" || + (function_exists("ImageCreateFromGif") && $_FILES['photo']['type']=="image/gif") || + $_FILES['photo']['type']=="image/png" || + $_FILES['photo']['type']=="image/x-png") + { + $tmp_name = $HTTP_POST_FILES["photo"]["tmp_name"]; + + // extension du fichier (en fonction du type mime) + if ($_FILES['photo']['type']=="image/jpeg") + $ext_image = ".jpg"; + if ($_FILES['photo']['type']=="image/png" || $_FILES['photo']['type']=="image/x-png") + $ext_image = ".png"; + if ($_FILES['photo']['type']=="image/gif") + $ext_image = ".gif"; + + // suppression ancienne photo + // NB : une verification sur le type de $id_adh permet d'eviter une faille + // du style $id_adh = "../../../image" + @unlink(WEB_ROOT . "photos/".$id_adh_new.".jpg"); + @unlink(WEB_ROOT . "photos/".$id_adh_new.".gif"); + @unlink(WEB_ROOT . "photos/".$id_adh_new.".jpg"); + @unlink(WEB_ROOT . "photos/tn_".$id_adh_new.".jpg"); + @unlink(WEB_ROOT . "photos/tn_".$id_adh_new.".gif"); + @unlink(WEB_ROOT . "photos/tn_".$id_adh_new.".jpg"); + + // copie fichier temporaire + if (!@move_uploaded_file($tmp_name,WEB_ROOT . "photos/".$id_adh_new.$ext_image)) + $warning_detected .= "
  • "._T("- La photo semble ne pas avoir été transmise correstement. L'enregistrement a cependant été effectué.")."
  • "; + else + resizeimage(WEB_ROOT . "photos/".$id_adh_new.$ext_image,WEB_ROOT . "photos/tn_".$id_adh_new.$ext_image,130,130); + } + else + { + if (function_exists("imagegif")) + $warning_detected .= "
  • "._T("- Le fichier transmis n'est pas une image valide (GIF, PNG ou JPEG). L'enregistrement a cependant été effectué.")."
  • "; + else + $warning_detected .= "
  • "._T("- Le fichier transmis n'est pas une image valide (PNG ou JPEG). L'enregistrement a cependant été effectué.")."
  • "; + } + } + + // retour à la liste ou passage à la contribution + if ($warning_detected=="" && $id_adh=="") + { + header("location: ajouter_contribution.php?id_adh=".$id_adh_new); + die(); + } + elseif ($warning_detected=="" && !isset($_FILES["photo"])) + { + header("location: gestion_adherents.php"); + die(); + } + elseif ($warning_detected=="" && ($_FILES["photo"]["tmp_name"]=="none" || $_FILES["photo"]["tmp_name"]=="")) + { + header("location: gestion_adherents.php"); + die(); + } + $id_adh=$id_adh_new; + } + } + + // suppression photo + if (isset($_POST["del_photo"])) + { + @unlink(WEB_ROOT . "photos/" . $id_adh . ".jpg"); + @unlink(WEB_ROOT . "photos/" . $id_adh . ".png"); + @unlink(WEB_ROOT . "photos/" . $id_adh . ".gif"); + @unlink(WEB_ROOT . "photos/tn_" . $id_adh . ".jpg"); + @unlink(WEB_ROOT . "photos/tn_" . $id_adh . ".png"); + @unlink(WEB_ROOT . "photos/tn_" . $id_adh . ".gif"); + } + + // + // Pré-remplissage des champs + // avec des valeurs issues de la base + // -> donc uniquement si l'enregistrement existe et que le formulaire + // n'a pas déja été posté avec des erreurs (pour pouvoir corriger) + + if (!isset($_POST["valid"]) || (isset($_POST["valid"]) && $error_detected=="")) + if ($id_adh != "") + + + { + // recup des données + $requete = "SELECT * + FROM ".PREFIX_DB."adherents + WHERE id_adh=$id_adh"; + $result = $DB->Execute($requete); + if ($result->EOF) + { + header("location: index.php"); + die(); + } + + + + // recuperation de la liste de champs de la table + //$fields = &$DB->MetaColumns(PREFIX_DB."cotisations"); + foreach ($fields as $champ => $proprietes) + { + //echo $proprietes_arr["name"]." -- (".$result->fields[$proprietes_arr["name"]].")
    "; + + + $val=""; + $proprietes_arr = get_object_vars($proprietes); + // on obtient name, max_length, type, not_null, has_default, primary_key, + // auto_increment et binary + + // déclaration des variables correspondant aux champs + // et reformatage des dates. + + // on doit faire cette verif pour une enventuelle valeur "NULL" + // non renvoyée -> ex: pas de societe membre + // sinon on obtient un warning + if (isset($result->fields[$proprietes_arr["name"]])) + $val = $result->fields[$proprietes_arr["name"]]; + + if($proprietes_arr["type"]=="date" && $val!="") + { + list($a,$m,$j)=explode("-",$val); + $val="$j/$m/$a"; + } + $values[$proprietes_arr["name"]]=htmlentities(stripslashes(addslashes($val)), ENT_QUOTES); + } + reset($fields); + } + else + { + // initialisation des champs + + } + + // la date de creation de fiche, ici vide si nouvelle fiche + if ($values['date_crea_adh']=="") + $values['date_crea_adh'] = date("d/m/Y"); + if ($url_adh=="") + $url_adh = "http://"; + if ($mdp_adh=="") + $mdp_adh = makeRandomPassword(); + + // variable pour la desactivation de champs + if ($_SESSION["admin_status"]==0) + $disabled_field = "disabled"; + else + $disabled_field = ""; + + + include("header.php"); + +?> + +

    ()

    +
    + + +
    +

    + +
    + +
    +

    + +
    + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    id="libelle"> + >    + >    + >    +
    id="libelle">> + + <?php echo _T(" width="" height=""> + +
    id="libelle">>
    id="libelle">
    id="libelle">
     

    id="libelle">
    > + + "> + +
    + +
    id="libelle"> + + id="libelle"> + +
    id="libelle"> + + id="libelle"> + +
    id="libelle"> + + id="libelle"> + +
    id="libelle"> + +
    id="libelle"> + + +
     
    id="libelle"> + +  
    id="libelle"> + +  
    > 
    > 
     
    > +
    + +
    >>
    >>
    >>
    >>
    >>
     
    >
     

    >
     


     


     

    >
    > + + +
    + +

    ">
    +
    +
    + . +
    + +
    + diff --git a/seed/galette/manual/image/postinstall/galette/ajouter_contribution.php b/seed/galette/manual/image/postinstall/galette/ajouter_contribution.php new file mode 100644 index 0000000..73d413b --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/ajouter_contribution.php @@ -0,0 +1,392 @@ + modif ou création + $id_cotis = ""; + if (isset($_GET["id_cotis"])) + if (is_numeric($_GET["id_cotis"])) + $id_cotis = $_GET["id_cotis"]; + if (isset($_POST["id_cotis"])) + if (is_numeric($_POST["id_cotis"])) + $id_cotis = $_POST["id_cotis"]; + + // variables d'erreur (pour affichage) + $error_detected = ""; + + // + // DEBUT parametrage des champs + // On recupere de la base la longueur et les flags des champs + // et on initialise des valeurs par defaut + + // recuperation de la liste de champs de la table + $fields = $DB->MetaColumns(PREFIX_DB."cotisations"); + foreach ($fields as $champ => $proprietes) + { + $proprietes_arr = get_object_vars($proprietes); + // on obtient name, max_length, type, not_null, has_default, primary_key, + // auto_increment et binary + + $fieldname = $proprietes_arr["name"]; + $fieldreq = $fieldname."_req"; + $fieldlen = $fieldname."_len"; + + // on ne met jamais a jour id_cotis -> on le saute + if ($fieldname!="id_cotis") + $$fieldname = ""; + + // definissons aussi la longueur des input text + $max_tmp = $proprietes_arr["max_length"]; + if ($max_tmp == "-1") + $max_tmp = 10; + $$fieldlen = $max_tmp; + + // et s'ils sont obligatoires (à partir de la base) + if ($proprietes_arr["not_null"]==1) + $$fieldreq = " style=\"color: #FF0000;\""; + else + $$fieldreq = ""; + } + reset($fields); + + // et les valeurs par defaut + $id_type_cotis = "1"; + $duree_mois_cotis = "12"; + + // + // FIN parametrage des champs + // + + $values = Array(); + $values['id_adh'] = ""; + if (isset($_GET["id_adh"])) + $values['id_adh'] = $_GET["id_adh"]; + elseif (isset($_POST["id_adh"])) + $values['id_adh'] = $_POST["id_adh"]; + if ($values['id_adh']!="") + { + $requete = "SELECT nom_adh, prenom_adh FROM ".PREFIX_DB."adherents WHERE id_adh=".$DB->qstr($values['id_adh']); + $resultat = $DB->Execute($requete); + if (!$resultat->EOF) + { + $nom_adh = $resultat->fields[0]; + $prenom_adh = $resultat->fields[1]; + $resultat->Close(); + } + } + + // + // Validation du formulaire + // + + if (isset($_POST["valid"])) + { + // verification de champs + $update_string = ""; + $insert_string_fields = ""; + $insert_string_values = ""; + + // recuperation de la liste de champs de la table + //$fields = &$DB->MetaColumns(PREFIX_DB."cotisations"); + foreach ($fields as $champ => $proprietes) + { + $proprietes_arr = get_object_vars($proprietes); + // on obtient name, max_length, type, not_null, has_default, primary_key, + // auto_increment et binary + + $fieldname = $proprietes_arr["name"]; + $fieldreq = $fieldname."_req"; + + // on ne met jamais a jour id_cotis -> on le saute + if ($fieldname!="id_cotis") + { + if (isset($_POST[$fieldname])) + $post_value=trim($_POST[$fieldname]); + else + $post_value=""; + + // on declare les variables pour la présaisie en cas d'erreur + $$fieldname = htmlentities(stripslashes($post_value),ENT_QUOTES); + + // vérification de la présence des champs obligatoires + if ($$fieldreq!="" && $post_value=="") + $error_detected = "
  • "._T("- Vérifiez que tous les champs obligatoires sont renseignés.")."
  • "; + else + { + $value = ""; + // validation des dates + if($proprietes_arr["type"]=="date") + { + if (preg_match("/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/", $post_value, $array_jours)) + { + if (checkdate($array_jours[2],$array_jours[1],$array_jours[3])) + $value=$DB->DBDate(mktime(0,0,0,$array_jours[2],$array_jours[1],$array_jours[3])); + else + $error_detected .= "
  • "._T("- Date non valide !")."
  • "; + } + else + $error_detected .= "
  • "._T("- Mauvais format de date (jj/mm/aaaa) !")."
  • "; + } + elseif(strstr($proprietes_arr["type"],"int")) + { + if (is_numeric($post_value) || $post_value=="") + $value=$DB->qstr($post_value,ENT_QUOTES); + else + $error_detected .= "
  • "._T("- La durée doit être un entier !")."
  • "; + } + elseif(strstr($proprietes_arr["type"],"float")) + { + $us_value = strtr($post_value, ",", "."); + if (is_numeric($us_value) || $us_value=="") + $value=$DB->qstr($us_value,ENT_QUOTES); + else + $error_detected .= "
  • "._T("- Le montant doit être un chiffre !")."
  • "; + } + else + { + // on se contente d'escaper le html et les caracteres speciaux + $value = $DB->qstr($post_value,ENT_QUOTES); + } + + // mise à jour des chaines d'insertion/update + $update_string .= ",".$fieldname."=".$value; + $insert_string_fields .= ",".$fieldname; + $insert_string_values .= ",".$value; + } + } + } + reset($fields); + + // modif ou ajout + if ($error_detected=="") + { + if ($id_cotis!="") + { + // modif + + $requete = "UPDATE ".PREFIX_DB."cotisations + SET " . substr($update_string,1) . " + WHERE id_cotis=" . $DB->qstr($id_cotis); + dblog(_T("Mise à jour d'une contribution :")." ".strtoupper($nom_adh)." ".$prenom_adh, $requete); + } + else + { + // ajout + + $requete = "INSERT INTO ".PREFIX_DB."cotisations + (" . substr($insert_string_fields,1) . ") + VALUES (" . substr($insert_string_values,1) . ")"; + + dblog(_T("Ajout d'une contribution :")." ".strtoupper($nom_adh)." ".$prenom_adh, $requete); + } + $DB->Execute("SET NAMES utf8"); + $DB->Execute($requete); + $DB->Execute("SET NAMES latin1"); + + // mise a jour de l'échéance + $date_fin = get_echeance($DB, $values['id_adh']); + if ($date_fin!="") + $date_fin_update = $DB->DBDate(mktime(0,0,0,$date_fin[1],$date_fin[0],$date_fin[2])); + else + $date_fin_update = "'NULL'"; + + $requete = "UPDATE ".PREFIX_DB."adherents + SET date_echeance=".$date_fin_update." + WHERE id_adh='".$values['id_adh']."'"; + $DB->Execute($requete); + + // retour à la liste + header("location: gestion_contributions.php?id_adh=".$values['id_adh']); + + // récupération du max pour passage en mode modif apres insertion + if ($id_cotis=="") + { + $requete = "SELECT max(id_cotis) + AS max + FROM ".PREFIX_DB."cotisations"; + $max = $DB->Execute($requete); + $id_cotis = $max->fields["max"]; + } + } + } + + // + // Pré-remplissage des champs + // avec des valeurs issues de la base + // -> donc uniquement si l'enregistrement existe et que le formulaire + // n'a pas déja été posté avec des erreurs (pour pouvoir corriger) + + if (!isset($_POST["valid"]) || (isset($_POST["valid"]) && $error_detected=="")) + if ($id_cotis != "") + { + // recup des données + $requete = "SELECT * + FROM ".PREFIX_DB."cotisations + WHERE id_cotis=$id_cotis"; + $result = $DB->Execute($requete); + if ($result->EOF) + header("location: index.php"); + + + + // recuperation de la liste de champs de la table + //$fields = &$DB->MetaColumns(PREFIX_DB."cotisations"); + foreach ($fields as $champ => $proprietes) + { + $proprietes_arr = get_object_vars($proprietes); + // on obtient name, max_length, type, not_null, has_default, primary_key, + // auto_increment et binary + + // déclaration des variables correspondant aux champs + // et reformatage des dates. + + $val = $result->fields[$proprietes_arr["name"]]; + + if($proprietes_arr["type"]=="date" && $val!="") + { + list($a,$m,$j)=explode("-",$val); + $val="$j/$m/$a"; + } + $values[$proprietes_arr["name"]] = htmlentities(stripslashes(addslashes($val)), ENT_QUOTES); + } + } + else + { + // initialisation des champs + + } + + // la date de creation de fiche, ici vide si nouvelle fiche + if ($date_cotis=="") + $date_cotis = date("d/m/Y"); + + include("header.php"); + +?> + +

    ()

    +
    + + +
    +

    + +
    + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + +
    > + + > + +
    >>
    >
     

    >

    ">
    +
    +
    + . +
    + +
    + diff --git a/seed/galette/manual/image/postinstall/galette/etiquettes_adherents.php b/seed/galette/manual/image/postinstall/galette/etiquettes_adherents.php new file mode 100644 index 0000000..6f96771 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/etiquettes_adherents.php @@ -0,0 +1,208 @@ +qstr($value); + } + $requete .= $where_clause." ORDER by nom_adh, prenom_adh;"; + $resultat = &$DB->Execute($requete); + + $pdf = new pdffile; + $pdf->set_default('margin', 0); + $firstpage = $pdf->new_page("a4-landscape"); + $param["height"] = PREF_ETIQ_CORPS; + $param["fillcolor"] = $pdf->get_color('#000000'); + $param["align"] = "center"; + $param["width"] = 1; + $param["strokecolor"] = $pdf->get_color('#000000'); + if ($resultat->EOF) + die(); + $yorigin=545; + $xorigin=round(PREF_ETIQ_MARGES*2.835); + $row=1; + $nb_etiq=0; + $concatname = ""; + $i=0; + $j=0; + while (date("Ym",strtotime("$j saturday", strtotime($datenow))) <= $annee.$mois) + { + $j++; + if (date("m",strtotime("$j saturday", strtotime($datenow))) == $mois) { + $panier[$i][0]=0; + $panier[$i][1]=0; + $date[$i]=date("d/m/Y",strtotime($j . " saturday", strtotime($datenow))); + $date2[$i]=date("Y-m-d",strtotime($j . " saturday", strtotime($datenow))); + $i++; + } + if ($j > 10) { + print "Problème dans le calcul des mois !"; + die(); + } + } + $col = $i; + $ligne = 18; + $x1 = 70; + $x2 = 300; + $ecart = 480/$col; + $hecart = 490/$ligne; + + + while (!$resultat->EOF) + { + $y1 = $yorigin-(($row-1)*($hecart)); + $y2 = $y1 - $hecart; + if ($row==1) + { + $param["font"] = "Helvetica-Bold"; + $pdf->draw_rectangle($yorigin+20, $x1, $yorigin, $x2, $firstpage, $param); + $pdf->draw_paragraph($yorigin+20, $x1, $yorigin, $x2, "Nom", $firstpage, $param); + $pdf->draw_rectangle($yorigin+20, $x2, $yorigin, $x2+40, $firstpage, $param); + $pdf->draw_paragraph($yorigin+20, $x2, $yorigin, $x2+40, "Prix", $firstpage, $param); + $i=0; + while($i<$col) + { + $xdr1=$x2+40+$i*$ecart; + $xdr2=$x2+40+($i+1)*$ecart; + $pdf->draw_paragraph($yorigin+20, $xdr1, $yorigin, $xdr2, $date[$i], $firstpage, $param); + $pdf->draw_rectangle($yorigin+20, $xdr1, $yorigin, $xdr2, $firstpage, $param); + $i++; + } + } + if ( ($_POST['panier'] == "legume" && $resultat->fields[9] != "-1") || ($_POST['panier'] == "pain" && $resultat->fields[10] != "0") ) { + $nom_adh_ext=""; + switch($resultat->fields[4]) + { + case "1" : + $nom_adh_ext .= _T("M."); + break; + case "2" : + $nom_adh_ext .= _T("Mme."); + break; + default : + $nom_adh_ext .= _T("Mlle."); + } + + $nom_adh_ext .= " ".strtoupper($resultat->fields[1])." ".ucfirst(strtolower($resultat->fields[2])); + $concatname = $concatname . " - " . $nom_adh_ext; + $param["font"] = "Helvetica"; + $pdf->draw_paragraph($y1-5, $x1, $y2, $x2, $nom_adh_ext, $firstpage, $param); + $pdf->draw_rectangle ($y1, $x1, $y2, $x2, $firstpage, $param); + $pdf->draw_rectangle($y1, $x2, $y2, $x2+40, $firstpage, $param); +// $pdf->draw_rectangle($y1, $x2+20, $y2, $x2+40, $firstpage, $param); + if ($_POST['panier'] == "legume") + { + $qpanier=$resultat->fields[9]; + if ($qpanier == "0" ) + $qpanier_result="pp"; + else + $qpanier_result="GP"; + } else if ($_POST['panier'] == "pain") { + $qpanier=$resultat->fields[10]; + if ($qpanier == "1" ) + $qpanier_result="3"; + if ($qpanier == "2" ) + $qpanier_result="5"; + if ($qpanier == "3" ) + $qpanier_result="7"; + if ($qpanier == "4" ) + $qpanier_result="9,50"; + } + $pdf->draw_paragraph($y1, $x2, $y2, $x2+40, $qpanier_result, $firstpage, $param); + $i=0; + while($i<$col) + { + $absence = &$DB->Execute("SELECT * FROM `galette_absences` WHERE `id_adh` = " . $resultat->fields[0] . " AND `date_abs` = '$date2[$i]'"); + if (!$absence->EOF) + $pdf->draw_paragraph($y1, $x2+$i*$ecart+40, $y2, $x2+($i+1)*$ecart+40, "Absent", $firstpage, $param); + else + $panier[$i+1][$qpanier]=$panier[$i+1][$qpanier]+1; + $pdf->draw_rectangle($y1, $x2+$i*$ecart+40, $y2, $x2+($i+1)*$ecart+40, $firstpage, $param); + $i++; + } + + $row++; + if ($row>$ligne) + { + $row=1; + $firstpage = $pdf->new_page("a4-landscape"); + } + $nb_etiq++; + } + $resultat->MoveNext(); + } + $i=0; + while($i<$col) + { + $pdf->draw_rectangle($y2, $x2+$i*$ecart+40, $y2-20, $x2+($i+1)*$ecart+40, $firstpage, $param); + if ($_POST['panier'] == "legume") + $display="pp : " . $panier[$i+1][0] . " | GP : " . $panier[$i+1][1]; + if ($_POST['panier'] == "pain") + $display="3E : " . $panier[$i+1][1] . " | 5E : " . $panier[$i+1][2] . " | 7E : " . $panier[$i+1][3] . " | 9E50 : " . $panier[$i+1][4]; + + $pdf->draw_paragraph($y2, $x2+$i*$ecart+40, $y2-20, $x2+($i+1)*$ecart+40, $display, $firstpage, $param); + $i++; + } + + $resultat->Close(); + dblog(_T("Génération de ")." ".$nb_etiq." "._T("feuille emargement"),$concatname); + header("Content-Disposition: filename=feuille_emargement.pdf"); + header("Content-Type: application/pdf"); + $temp = $pdf->generate(); + header('Content-Length: ' . strlen($temp)); + echo $temp; +?> diff --git a/seed/galette/manual/image/postinstall/galette/etiquettes_adherents_2.php b/seed/galette/manual/image/postinstall/galette/etiquettes_adherents_2.php new file mode 100644 index 0000000..30b9ef7 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/etiquettes_adherents_2.php @@ -0,0 +1,127 @@ +qstr($value); + } + $requete .= $where_clause." ORDER by nom_adh, prenom_adh;"; + // echo $requete; + $resultat = &$DB->Execute($requete); + + $pdf = new pdffile; + $pdf->set_default('margin', 0); + $firstpage = $pdf->new_page("a4"); + $param["height"] = PREF_ETIQ_CORPS; + $param["fillcolor"] = $pdf->get_color('#000000'); + $param["align"] = "center"; + $param["width"] = 1; + $param["strokecolor"] = $pdf->get_color('#DDDDDD'); + + if ($resultat->EOF) + die(); + + $yorigin=842-round(PREF_ETIQ_MARGES*2.835); + $xorigin=round(PREF_ETIQ_MARGES*2.835); + $col=1; + $row=1; + $nb_etiq=0; + $concatname = ""; + while (!$resultat->EOF) + { + $nom_adh_ext=""; + switch($resultat->fields[4]) + { + case "1" : + $nom_adh_ext .= _T("M."); + break; + case "2" : + $nom_adh_ext .= _T("Mme."); + break; + default : + $nom_adh_ext .= _T("Mlle."); + } + + $x1 = $xorigin + ($col-1)*(round(PREF_ETIQ_HSIZE*2.835)+round(PREF_ETIQ_HSPACE*2.835)); + $x2 = $x1 + round(PREF_ETIQ_HSIZE*2.835); + $y1 = $yorigin-($row-1)*(round(PREF_ETIQ_VSIZE*2.835)+round(PREF_ETIQ_VSPACE*2.835)); + $y2 = $y1 - round(PREF_ETIQ_VSIZE*2.835); + + $nom_adh_ext .= " ".strtoupper($resultat->fields[1])." ".ucfirst(strtolower($resultat->fields[2])); + $concatname = $concatname . " - " . $nom_adh_ext; + $param["font"] = "Helvetica-Bold"; + $pdf->draw_paragraph($y1-10, $x1, $y1-10-(round(PREF_ETIQ_VSIZE*2.835)/5)+5, $x2, $nom_adh_ext, $firstpage, $param); + $param["font"] = "Helvetica"; + $pdf->draw_paragraph ($y1-10-(round(PREF_ETIQ_VSIZE*2.835)/5), $x1, $y1-10-(round(PREF_ETIQ_VSIZE*2.835)/5)-(round(PREF_ETIQ_VSIZE*2.835)*4/5), $x2, $resultat->fields[3]."\n".$resultat->fields[8]."\n".$resultat->fields[5]." - ".$resultat->fields[6]."\n".$resultat->fields[7], $firstpage, $param); + $pdf->draw_rectangle ($y1, $x1, $y2, $x2, $firstpage, $param); + $resultat->MoveNext(); + + $col++; + if ($col>PREF_ETIQ_COLS) + { + $col=1; + $row++; + } + if ($row>PREF_ETIQ_ROWS) + { + $col=1; + $row=1; + $firstpage = $pdf->new_page("a4"); + } + $nb_etiq++; + } + $resultat->Close(); + dblog(_T("Génération de ")." ".$nb_etiq." "._T("étiquette(s)"),$concatname); + + header("Content-Disposition: filename=example.pdf"); + header("Content-Type: application/pdf"); + $temp = $pdf->generate(); + header('Content-Length: ' . strlen($temp)); + echo $temp; +?> diff --git a/seed/galette/manual/image/postinstall/galette/footer.php b/seed/galette/manual/image/postinstall/galette/footer.php new file mode 100644 index 0000000..7a5de70 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/footer.php @@ -0,0 +1,168 @@ + + + + + + diff --git a/seed/galette/manual/image/postinstall/galette/galette.css b/seed/galette/manual/image/postinstall/galette/galette.css new file mode 100644 index 0000000..71aaa75 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/galette.css @@ -0,0 +1,414 @@ +body { + margin-top: 0px; + margin-left: 0px; + margin-right: 0px; + margin-bottom: 0px; + font-family: Verdana, Arial, Helvetica, sans-serif; + font-size: 11px +} + +td { + font-size: 11px +} + +input { + font-size: 11px +} + +select { + font-size: 11px +} + +textarea { + font-size: 11px +} + +a { + text-decoration: none; + color: #0000FF; +} + +a:hover { + color: #FF0000; +} + +.left { + text-align: left; +} + +.right { + text-align: right; +} + +.center { + text-align: center; +} + +.cotis-ok { + background-color: #DDFFDD; + vertical-align: top; +} + +.cotis-never { + background-color: #EEEEEE; + vertical-align: top; +} + +.cotis-exempt { + background-color: #DDFFDD; + vertical-align: top; +} + +.cotis-soon { + background-color: #FFE9AB; + vertical-align: top; +} + +.cotis-late { + background-color: #FFDDDD; + vertical-align: top; +} + +.cotis-lastday { + background-color: #FFDDDD; + vertical-align: top; +} + +.cotis-normal { + background-color: #DDFFDD; + vertical-align: top; +} + +.cotis-give { + background-color: #FFDDDD; + vertical-align: top; +} + +.totalcount { + text-align: left; +} + +.pageswitch { + text-align: center; + margin-top: 4px; +} + +.pagelink { + font-weight: bold; +} + +.filtermenus { + text-align: right; +} + +.titre { + font-size: 15px; + text-align: center; + font-weight: bold; + border-style: solid; + border-width: 1px; + background-color: #FBFBFB; + border-color: #BBBBBB; + margin-top: 10px; + margin-bottom: 20px; + color: #000000; + width: 100%; +} + +th.listing { + font-size: 10px; + background-color: #000000; + color: #FFFFFF; +} + +a.listing { + color: #FFFFFF; + font-weight: bold; +} + +a.listing:hover { + color: #FF0000; +} + +.emptylist { + background-color: #EEEEEE; + text-align: center; + font-style: italic; +} + +.actif { +} + +.inactif { + color: #777777; + font-style: italic; +} + +.acronyme { + color: #AAAAAA; + font-style: italic; +} + +#copyright { + color: #CCCCCC; + font-style: italic; + text-align: center; + padding-top: 10px; + margin-bottom: 10px; +} + +#copyright a { + color: #CCCCCC; +} + +#copyright a:hover { + color: #FF0000; +} + +.exemple { + color: #999999; +} + +#logo { + text-align: center; + font-weight: bold; + margin-top: 10px; + width: 150px; + height: 100px; +} + +#nav1 { + width: 150px; + margin-left: 5px; + border-color: #7777FF; + border-width: 2px; + border-style: solid; +} + +#nav1 h1 { + margin: 2px; + font-size: 10px; + background-color: #DDDDFF; + padding-left: 2px; +} + +#nav1 ul { + list-style-type: none; + margin: 2px; + padding: 0px; + border: none; +} + +#nav1 li { + background-color: #EEEEEE; + margin-bottom: 2px; + padding-left: 2px; +} + +#logout { + width: 150px; + margin-left: 5px; + text-align: center; + margin-top: 10px; + margin-bottom: 10px; +} + +#legende { + width: 150px; + margin-left: 5px; + margin-bottom: 5px; + border-color: #7777FF; + border-width: 2px; + border-style: solid; +} + +#legende table { + width: 100%; +} + +#legende h1 { + margin: 2px; + font-size: 10px; + background-color: #DDDDFF; + padding-left: 2px; + text-align: left; +} + +#legende td { + padding-left: 2px; +} + +#legende .back { + background-color: #EEEEEE; +} + +.color-sample { + border-color: #AAAAAA; + border-width: 1px; + border-style: solid; +} + +#content { + position: absolute; + padding-right: 15px; + left: 170px; +} + +#menu { + float: left; + position: absolute; + top: 0px; + left: 0px; +} + +#listfilter { + text-align: right; +} + +#listfilter form { + margin-bottom: 0px; +} + +#infoline { + margin-top: 10px; +} + +#infoline2 { + margin-top: 2px; +} + +#mailing_preview { + margin-top: 10px; + margin-bottom: 10px; + margin-left: 30px;; + margin-right: 30px; + border-color: #DDDDDD; + border-width: 2px; + border-style: solid; +} + +#mailing_preview th { + font-size: 10px; + font-weight: bold; + text-align: left; + background-color: #EEEEEE; +} + +#errorbox { + color: #FF0000; + border-color: #FFDDDD; + border-width: 2px; + border-style: solid; +} + +#errorbox h1 { + background-color: #FFDDDD; + text-align: center; + font-size: 10px; + font-weight: bold; + margin-top: 0px; + margin-bottom: 0px; +} + +#errorbox ul { + list-style-type: none; + margin: 2px; + padding: 0px; + border: none; +} + +#warningbox { + color: #000000; + border-color: #FFE8CC; + border-width: 2px; + border-style: solid; +} + +#warningbox h1 { + background-color: #FFE8CC; + text-align: center; + font-size: 10px; + font-weight: bold; + margin-top: 0px; + margin-bottom: 0px; +} + +#warningbox ul { + list-style-type: none; + margin: 2px; + padding: 0px; + border: none; +} + +#input-table #libelle { + font-size: 11px; + text-align: left; + background-color: #DDDDFF; + font-weight: normal; +} + +#input-table #header { + text-align: left; + font-weight: bold; +} + +#input-table td { + background-color: #EEEEEE; +} + +#installpage { + background-color: #DDDDFF; + padding-left: 20px; +} + +#installpage p { + background-color: #DDDDFF; + padding-left: 20px; + width: 80%; +} + +#installpage h1 { + text-align: left; + margin: 0px; + font-size: 12px; +} + +#installpage #submitbutton2 { + text-align: center; + padding-left: 20px; +} + +#installpage #submitbutton3 { + text-align: right; + padding-right: 20px; +} + +.titreinstall { + font-size: 15px; + text-align: center; + font-weight: bold; + border-style: solid; + border-width: 1px; + background-color: #FBFBFB; + border-color: #BBBBBB; + color: #000000; + left: 0px; + right: 0px; + padding: 10px 0px 10px 0px; + margin: 0px; +} + +.footerinstall { + font-size: 11px; + text-align: right; + padding-right: 20px; + font-weight: normal; + border-style: solid; + border-width: 1px; + background-color: #FBFBFB; + border-color: #BBBBBB; + color: #000000; + left: 0px; + right: 0px; + margin: 0px; +} diff --git a/seed/galette/manual/image/postinstall/galette/gestion_adherents.php b/seed/galette/manual/image/postinstall/galette/gestion_adherents.php new file mode 100644 index 0000000..7221f0c --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/gestion_adherents.php @@ -0,0 +1,449 @@ +qstr($_GET["sup"]); + $resultat = $DB->Execute($requetesup); + if (!$resultat->EOF) + { + // supression record adhérent + $requetesup = "DELETE FROM ".PREFIX_DB."adherents + WHERE id_adh=".$DB->qstr($_GET["sup"]); + $DB->Execute($requetesup); + + // suppression de l'eventuelle photo + @unlink(WEB_ROOT . "photos/".$id_adh.".jpg"); + @unlink(WEB_ROOT . "photos/".$id_adh.".gif"); + @unlink(WEB_ROOT . "photos/".$id_adh.".jpg"); + @unlink(WEB_ROOT . "photos/tn_".$id_adh.".jpg"); + @unlink(WEB_ROOT . "photos/tn_".$id_adh.".gif"); + @unlink(WEB_ROOT . "photos/tn_".$id_adh.".jpg"); + + // suppression records cotisations + $requetesup = "DELETE FROM ".PREFIX_DB."cotisations + WHERE id_adh=" . $DB->qstr($_GET["sup"]); + $DB->Execute($requetesup); + dblog(_T("Suppression de la fiche adhérent (et cotisations) :")." ".strtoupper($resultat->fields[0])." ".$resultat->fields[1], $requetesup); + } + $resultat->Close(); + } + } + +?> +

    +DBDate(time())." "; + $requete[1] .= "AND date_echeance < ".$DB->DBDate(time())." "; + } + + // filtre d'affichage des adherents à jour + if ($_SESSION["filtre_adh"]=="3") + { + $requete[0] .= "AND (date_echeance > ".$DB->DBDate(time())." OR bool_exempt_adh='1') "; + $requete[1] .= "AND (date_echeance > ".$DB->DBDate(time())." OR bool_exempt_adh='1') "; + } + + // filtre d'affichage des adherents bientot a echeance + if ($_SESSION["filtre_adh"]=="1") + { + $requete[0] .= "AND date_echeance > ".$DB->DBDate(time())." + AND date_echeance < ".$DB->OffsetDate(30)." "; + $requete[1] .= "AND date_echeance > ".$DB->DBDate(time())." + AND date_echeance < ".$DB->OffsetDate(30)." "; + } + + // phase de tri + + if ($_SESSION["tri_adh_sens"]=="0") + $tri_adh_sens_txt="ASC"; + else + $tri_adh_sens_txt="DESC"; + + $requete[0] .= "ORDER BY "; + + // tri par pseudo + if ($_SESSION["tri_adh"]=="1") + $requete[0] .= "pseudo_adh ".$tri_adh_sens_txt.","; + + // tri par statut + elseif ($_SESSION["tri_adh"]=="2") + $requete[0] .= "priorite_statut ".$tri_adh_sens_txt.","; + + // tri par echeance + elseif ($_SESSION["tri_adh"]=="3") + $requete[0] .= "bool_exempt_adh ".$tri_adh_sens_txt.", date_echeance ".$tri_adh_sens_txt.","; + + // defaut : tri par nom, prenom + $requete[0] .= "nom_adh ".$tri_adh_sens_txt.", prenom_adh ".$tri_adh_sens_txt; + $resultat = $DB->SelectLimit($requete[0],PREF_NUMROWS,($page-1)*PREF_NUMROWS); + $nbadh = $DB->Execute($requete[1]); + + if ($nbadh->fields[0]%PREF_NUMROWS==0) + $nbpages = intval($nbadh->fields[0]/PREF_NUMROWS); + else + $nbpages = intval($nbadh->fields[0]/PREF_NUMROWS)+1; + $pagestring = ""; + if ($nbpages==0) + $pagestring = "1"; + else for ($i=1;$i<=$nbpages;$i++) + { + if ($i!=$page) + $pagestring .= "".$i." "; + else + $pagestring .= $i." "; + } +?> +
    +
    +   + + + + "> +
    +
    + + + + + +
    fields[0]." "; if ($nbadh->fields[0]!=1) echo _T("adhérents"); else echo _T("adhérent"); ?>
    + + + + + + + + + +EOF) + { +?> + +EOF) + { + // définition CSS pour adherent désactivé + if ($resultat->fields[4]=="1") + $row_class = "actif"; + else + $row_class = "inactif"; + + // temps d'adhésion + if($resultat->fields[6]) + { + $statut_cotis = _T("Exempt de cotisation"); + $row_class .= " cotis-exempt"; + } + else + { + if ($resultat->fields[10]=="") + { + $statut_cotis = _T("N'a jamais cotisé"); + $row_class .= " cotis-never"; + } + else + { + $date_fin = preg_split("~-~",$resultat->fields[10]); + $ts_date_fin = mktime(0,0,0,$date_fin[1],$date_fin[2],$date_fin[0]); + $aujourdhui = time(); + + $difference = intval(($ts_date_fin - $aujourdhui)/(3600*24)); + if ($difference==0) + { + $statut_cotis = _T("Dernier jour !"); + $row_class .= " cotis-lastday"; + } + elseif ($difference<0) + { + $statut_cotis = _T("En retard de ").-$difference." "._T("jours")." ("._T("depuis le")." ".$date_fin[2]."/".$date_fin[1]."/".$date_fin[0].")"; + $row_class .= " cotis-late"; + } + else + { + if ($difference!=1) + $statut_cotis = $difference." "._T("jours restants")." ("._T("fin le")." ".$date_fin[2]."/".$date_fin[1]."/".$date_fin[0].")"; + else + $statut_cotis = $difference." "._T("jour restant")." ("._T("fin le")." ".$date_fin[2]."/".$date_fin[1]."/".$date_fin[0].")"; + if ($difference < 30) + $row_class .= " cotis-soon"; + else + $row_class .= " cotis-ok"; + } + } + } +?> + + + + + + + + +MoveNext(); + } + $resultat->Close(); +?> +
    # + + + + + + + + + + + + + + + +
    +fields[7]=="1") { +?> + <?php echo _T(" align="middle" width="10" height="12"> + + <?php echo _T(" align="middle" width="9" height="12"> +fields[8]!="") { +?> + <?php echo _T(" align="middle" border="0" width="14" height="10"> + + +fields[9]=="1") { +?> + <?php echo _T(" align="middle" width="12" height="13"> + + + + ">fields[1]),ENT_QUOTES)." ".htmlentities($resultat->fields[2], ENT_QUOTES) ?> + fields[3], ENT_QUOTES) ?>fields[5]) ?> + <?php echo _T(" border="0" width="12" height="13"> + <?php echo _T(" border="0" width="13" height="13"> + ')" href="gestion_adherents.php?sup=fields[0] ?>"><?php echo _T(" border="0" width="11" height="13"> +
    +
    + diff --git a/seed/galette/manual/image/postinstall/galette/gestion_contributions.php b/seed/galette/manual/image/postinstall/galette/gestion_contributions.php new file mode 100644 index 0000000..108c7ec --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/gestion_contributions.php @@ -0,0 +1,465 @@ +"._T("- Date non valide !").""; + } + elseif (ereg("^([0-9]{4})$", $_GET["contrib_filter_1"], $array_jours)) + $_SESSION["filtre_date_cotis_1"]="01/01/".$array_jours[1]; + elseif ($_GET["contrib_filter_1"]=="") + $_SESSION["filtre_date_cotis_1"]=""; + else + $error_detected .= "
  • "._T("- Mauvais format de date (jj/mm/aaaa) !")."
  • "; + + if (isset($_GET["contrib_filter_2"])) + if (ereg("^([0-9]{2})/([0-9]{2})/([0-9]{4})$", $_GET["contrib_filter_2"], $array_jours)) + { + if (checkdate($array_jours[2],$array_jours[1],$array_jours[3])) + $_SESSION["filtre_date_cotis_2"]=$_GET["contrib_filter_2"]; + else + $error_detected .= "
  • "._T("- Date non valide !")."
  • "; + } + elseif (ereg("^([0-9]{4})$", $_GET["contrib_filter_2"], $array_jours)) + $_SESSION["filtre_date_cotis_2"]="01/01/".$array_jours[1]; + elseif ($_GET["contrib_filter_2"]=="") + $_SESSION["filtre_date_cotis_2"]=""; + else + $error_detected .= "
  • "._T("- Mauvais format de date (jj/mm/aaaa) !")."
  • "; + + + $page = 1; + if (isset($_GET["page"])) + $page = $_GET["page"]; + + + // Tri + + if (isset($_GET["tri"])) + { + if ($_SESSION["tri_cotis"]==$_GET["tri"]) + $_SESSION["tri_cotis_sens"]=($_SESSION["tri_cotis_sens"]+1)%2; + else + { + $_SESSION["tri_cotis"]=$_GET["tri"]; + $_SESSION["tri_cotis_sens"]=0; + } + } + + include("header.php"); + + if ($_SESSION["admin_status"]==1) + if (isset($_GET["sup"])) + { + // recherche adherent + $requetesel = "SELECT id_adh + FROM ".PREFIX_DB."cotisations + WHERE id_cotis=".$DB->qstr($_GET["sup"]); + $result_adh = $DB->Execute($requetesel); + if (!$result_adh->EOF) + { + $id_adh = $result_adh->fields["id_adh"]; + + $requetesup = "SELECT nom_adh, prenom_adh FROM ".PREFIX_DB."adherents WHERE id_adh=".$DB->qstr($id_adh); + $resultat = $DB->Execute($requetesup); + if (!$resultat->EOF) + { + // supression record cotisation + $requetesup = "DELETE FROM ".PREFIX_DB."cotisations + WHERE id_cotis=".$DB->qstr($_GET["sup"]); + $DB->Execute($requetesup); + + // mise a jour de l'échéance + $date_fin = get_echeance($DB, $id_adh); + if ($date_fin!="") + $date_fin_update = $DB->DBDate(mktime(0,0,0,$date_fin[1],$date_fin[0],$date_fin[2])); + else + $date_fin_update = "NULL"; + $requeteup = "UPDATE ".PREFIX_DB."adherents + SET date_echeance=".$date_fin_update." + WHERE id_adh=".$DB->qstr($id_adh); + $DB->Execute("SET NAMES utf8"); + $DB->Execute($requeteup); + $DB->Execute("SET NAMES latin1"); + dblog(_T("Suppression d'une contribution :")." ".strtoupper($resultat->fields[0])." ".$resultat->fields[1], $requetesup); + } + $resultat->Close(); + } + $result_adh->Close(); + } +?> +

    +DBDate(mktime(0,0,0,$array_jours[2],$array_jours[1],$array_jours[3])); + $requete[0] .= "AND ".PREFIX_DB."cotisations.date_cotis >= " . $datemin . " "; + $requete[1] .= "AND ".PREFIX_DB."cotisations.date_cotis >= " . $datemin . " "; + } + if ($_SESSION["filtre_date_cotis_2"]!="") + { + ereg("^([0-9]{2})/([0-9]{2})/([0-9]{4})$", $_SESSION["filtre_date_cotis_2"], $array_jours); + $datemax = $DB->DBDate(mktime(0,0,0,$array_jours[2],$array_jours[1],$array_jours[3])); + $requete[0] .= "AND ".PREFIX_DB."cotisations.date_cotis <= " . $datemax . " "; + $requete[1] .= "AND ".PREFIX_DB."cotisations.date_cotis <= " . $datemax . " "; + } + + // phase de tri + + if ($_SESSION["tri_cotis_sens"]=="0") + $tri_cotis_sens_txt="ASC"; + else + $tri_cotis_sens_txt="DESC"; + + $requete[0] .= "ORDER BY "; + + // tri par adherent + if ($_SESSION["tri_cotis"]=="1") + $requete[0] .= "nom_adh ".$tri_cotis_sens_txt.", prenom_adh ".$tri_cotis_sens_txt.","; + + // tri par type + elseif ($_SESSION["tri_cotis"]=="2") + $requete[0] .= "libelle_type_cotis ".$tri_cotis_sens_txt.","; + + // tri par montant + elseif ($_SESSION["tri_cotis"]=="3") + $requete[0] .= "montant_cotis ".$tri_cotis_sens_txt.","; + + // tri par duree + elseif ($_SESSION["tri_cotis"]=="4") + $requete[0] .= "duree_mois_cotis ".$tri_cotis_sens_txt.","; + + // defaut : tri par date + $requete[0] .= " ".PREFIX_DB."cotisations.date_cotis ".$tri_cotis_sens_txt; + + // $resultat = &$DB->Execute($requete[0]); + $resultat = $DB->SelectLimit($requete[0],PREF_NUMROWS,($page-1)*PREF_NUMROWS); + $nbcotis = $DB->Execute($requete[1]); + + if ($nbcotis->fields[0]%PREF_NUMROWS==0) + $nbpages = intval($nbcotis->fields[0]/PREF_NUMROWS); + else + $nbpages = intval($nbcotis->fields[0]/PREF_NUMROWS)+1; + $pagestring = ""; + if ($nbpages==0) + $pagestring = "1"; + else for ($i=1;$i<=$nbpages;$i++) + { + if ($i!=$page) + $pagestring .= "".$i." "; + else + $pagestring .= $i." "; + } +?> +
    +
    +   + "> +   + "> + "> +
    +
    + + + + + +
    fields[0]." "; if ($nbcotis->fields[0]!=1) echo _T("contributions"); else echo _T("contribution"); ?>
    + + + + + + + + + + + + + + +EOF) + { + if ($_SESSION["admin_status"]==1) + $colspan = 7; + else + $colspan = 5; +?> + + + +EOF) + { + if ($resultat->fields["duree_mois_cotis"]!="0") + $row_class = "cotis-normal"; + else + $row_class = "cotis-give"; +?> + + + + + + + + + + + +MoveNext(); + } + $resultat->Close(); +?> +
    # + " class="listing"> + "; + else + echo "\"\""; + ?> + + " class="listing"> + "; + else + echo "\"\""; + ?> + + " class="listing"> +"; + else + echo "\"\""; + ?> + + " class="listing"> + "; + else + echo "\"\""; + ?> + + " class="listing"> + "; + else + echo "\"\""; + ?> + + +
    + fields["date_cotis"]); + echo "$j/$m/$a"; + ?> + + ">fields["nom_adh"]), ENT_QUOTES)." "; + if (isset($resultat->fields["prenom_adh"])) + echo htmlentities($resultat->fields["prenom_adh"], ENT_QUOTES); + ?> + fields["libelle_type_cotis"]) ?>fields["montant_cotis"] ?>fields["duree_mois_cotis"] ?> + "><?php echo _T(" border="0" width="12" height="13"> + ')" href="gestion_contributions.php?sup=fields["id_cotis"] ?>"><?php echo _T(" border="0" width="11" height="13"> +
    +
    +Execute($requete); + + // temps d'adhésion + if($resultat->fields[1]) + { + $statut_cotis = _T("Exempt de cotisation"); + $color = "#DDFFDD"; + } + else + { + if ($resultat->fields[0]=="") + { + $statut_cotis = _T("N'a jamais cotisé"); + $color = "#EEEEEE"; + } + else + { + + + $date_fin = explode("-",$resultat->fields[0]); + $ts_date_fin = mktime(0,0,0,$date_fin[1],$date_fin[2],$date_fin[0]); + $aujourdhui = time(); + + $difference = intval(($ts_date_fin - $aujourdhui)/(3600*24)); + if ($difference==0) + { + $statut_cotis = _T("Dernier jour !"); + $color = "#FFDDDD"; + } + elseif ($difference<0) + { + $statut_cotis = _T("En retard de")." ".-$difference." "._T("jours")." ("._T("depuis le")." ".$date_fin[2]."/".$date_fin[1]."/".$date_fin[0].")"; + $color = "#FFDDDD"; + } + else + { + if ($difference!=1) + $statut_cotis = $difference." "._T("jours restants")." ("._T("fin le")." ".$date_fin[2]."/".$date_fin[1]."/".$date_fin[0].")"; + else + $statut_cotis = $difference." "._T("jour restant")." ("._T("fin le")." ".$date_fin[2]."/".$date_fin[1]."/".$date_fin[0].")"; + if ($difference < 30) + $color = "#FFE9AB"; + else + $color = "#DDFFDD"; + } + + } + } + + + /*$days_left = get_days_left($DB, $_SESSION["filtre_cotis_adh"]); + $cumul = $days_left["cumul"]; + $statut_cotis = $days_left["text"]; + $color = $days_left["color"];*/ +?> +
    +
    + + + + +
    + +
    + "> +     + "> + +
    + + + diff --git a/seed/galette/manual/image/postinstall/galette/header.php b/seed/galette/manual/image/postinstall/galette/header.php new file mode 100644 index 0000000..2e8dc96 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/header.php @@ -0,0 +1,46 @@ + + + + + Galette <?php echo GALETTE_VERSION ?> + + + + + +
    diff --git a/seed/galette/manual/image/postinstall/galette/icon-mini.png b/seed/galette/manual/image/postinstall/galette/icon-mini.png new file mode 100644 index 0000000..e190252 Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/icon-mini.png differ diff --git a/seed/galette/manual/image/postinstall/galette/images/asc.png b/seed/galette/manual/image/postinstall/galette/images/asc.png new file mode 100644 index 0000000..0c9a2fa Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/images/asc.png differ diff --git a/seed/galette/manual/image/postinstall/galette/images/desc.png b/seed/galette/manual/image/postinstall/galette/images/desc.png new file mode 100644 index 0000000..cd87534 Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/images/desc.png differ diff --git a/seed/galette/manual/image/postinstall/galette/images/galette.jpg b/seed/galette/manual/image/postinstall/galette/images/galette.jpg new file mode 100644 index 0000000..c7a8a14 Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/images/galette.jpg differ diff --git a/seed/galette/manual/image/postinstall/galette/images/icon-edit.png b/seed/galette/manual/image/postinstall/galette/images/icon-edit.png new file mode 100644 index 0000000..97b48ef Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/images/icon-edit.png differ diff --git a/seed/galette/manual/image/postinstall/galette/images/icon-empty.png b/seed/galette/manual/image/postinstall/galette/images/icon-empty.png new file mode 100644 index 0000000..dcad4c7 Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/images/icon-empty.png differ diff --git a/seed/galette/manual/image/postinstall/galette/images/icon-female.png b/seed/galette/manual/image/postinstall/galette/images/icon-female.png new file mode 100644 index 0000000..91d8843 Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/images/icon-female.png differ diff --git a/seed/galette/manual/image/postinstall/galette/images/icon-mail.png b/seed/galette/manual/image/postinstall/galette/images/icon-mail.png new file mode 100644 index 0000000..55a8761 Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/images/icon-mail.png differ diff --git a/seed/galette/manual/image/postinstall/galette/images/icon-male.png b/seed/galette/manual/image/postinstall/galette/images/icon-male.png new file mode 100644 index 0000000..70a6bbe Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/images/icon-male.png differ diff --git a/seed/galette/manual/image/postinstall/galette/images/icon-money.png b/seed/galette/manual/image/postinstall/galette/images/icon-money.png new file mode 100644 index 0000000..a93a303 Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/images/icon-money.png differ diff --git a/seed/galette/manual/image/postinstall/galette/images/icon-star.png b/seed/galette/manual/image/postinstall/galette/images/icon-star.png new file mode 100644 index 0000000..b64e023 Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/images/icon-star.png differ diff --git a/seed/galette/manual/image/postinstall/galette/images/icon-trash.png b/seed/galette/manual/image/postinstall/galette/images/icon-trash.png new file mode 100644 index 0000000..31d2d7c Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/images/icon-trash.png differ diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-error.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-error.inc.php new file mode 100644 index 0000000..5e03c67 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-error.inc.php @@ -0,0 +1,258 @@ + DB_ERROR_NOSUCHTABLE, + '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/' => DB_ERROR_ALREADY_EXISTS, + '/divide by zero$/' => DB_ERROR_DIVZERO, + '/pg_atoi: error in .*: can\'t parse /' => DB_ERROR_INVALID_NUMBER, + '/ttribute [\"\'].*[\"\'] not found|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => DB_ERROR_NOSUCHFIELD, + '/parser: parse error at or near \"/' => DB_ERROR_SYNTAX, + '/referential integrity violation/' => DB_ERROR_CONSTRAINT, + '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*|duplicate key violates unique constraint/' + => DB_ERROR_ALREADY_EXISTS + ); + reset($error_regexps); + while (list($regexp,$code) = each($error_regexps)) { + if (preg_match($regexp, $errormsg)) { + return $code; + } + } + // Fall back to DB_ERROR if there was no mapping. + return DB_ERROR; +} + +function adodb_error_odbc() +{ +static $MAP = array( + '01004' => DB_ERROR_TRUNCATED, + '07001' => DB_ERROR_MISMATCH, + '21S01' => DB_ERROR_MISMATCH, + '21S02' => DB_ERROR_MISMATCH, + '22003' => DB_ERROR_INVALID_NUMBER, + '22008' => DB_ERROR_INVALID_DATE, + '22012' => DB_ERROR_DIVZERO, + '23000' => DB_ERROR_CONSTRAINT, + '24000' => DB_ERROR_INVALID, + '34000' => DB_ERROR_INVALID, + '37000' => DB_ERROR_SYNTAX, + '42000' => DB_ERROR_SYNTAX, + 'IM001' => DB_ERROR_UNSUPPORTED, + 'S0000' => DB_ERROR_NOSUCHTABLE, + 'S0001' => DB_ERROR_NOT_FOUND, + 'S0002' => DB_ERROR_NOSUCHTABLE, + 'S0011' => DB_ERROR_ALREADY_EXISTS, + 'S0012' => DB_ERROR_NOT_FOUND, + 'S0021' => DB_ERROR_ALREADY_EXISTS, + 'S0022' => DB_ERROR_NOT_FOUND, + 'S1000' => DB_ERROR_NOSUCHTABLE, + 'S1009' => DB_ERROR_INVALID, + 'S1090' => DB_ERROR_INVALID, + 'S1C00' => DB_ERROR_NOT_CAPABLE + ); + return $MAP; +} + +function adodb_error_ibase() +{ +static $MAP = array( + -104 => DB_ERROR_SYNTAX, + -150 => DB_ERROR_ACCESS_VIOLATION, + -151 => DB_ERROR_ACCESS_VIOLATION, + -155 => DB_ERROR_NOSUCHTABLE, + -157 => DB_ERROR_NOSUCHFIELD, + -158 => DB_ERROR_VALUE_COUNT_ON_ROW, + -170 => DB_ERROR_MISMATCH, + -171 => DB_ERROR_MISMATCH, + -172 => DB_ERROR_INVALID, + -204 => DB_ERROR_INVALID, + -205 => DB_ERROR_NOSUCHFIELD, + -206 => DB_ERROR_NOSUCHFIELD, + -208 => DB_ERROR_INVALID, + -219 => DB_ERROR_NOSUCHTABLE, + -297 => DB_ERROR_CONSTRAINT, + -530 => DB_ERROR_CONSTRAINT, + -803 => DB_ERROR_CONSTRAINT, + -551 => DB_ERROR_ACCESS_VIOLATION, + -552 => DB_ERROR_ACCESS_VIOLATION, + -922 => DB_ERROR_NOSUCHDB, + -923 => DB_ERROR_CONNECT_FAILED, + -924 => DB_ERROR_CONNECT_FAILED + ); + + return $MAP; +} + +function adodb_error_ifx() +{ +static $MAP = array( + '-201' => DB_ERROR_SYNTAX, + '-206' => DB_ERROR_NOSUCHTABLE, + '-217' => DB_ERROR_NOSUCHFIELD, + '-329' => DB_ERROR_NODBSELECTED, + '-1204' => DB_ERROR_INVALID_DATE, + '-1205' => DB_ERROR_INVALID_DATE, + '-1206' => DB_ERROR_INVALID_DATE, + '-1209' => DB_ERROR_INVALID_DATE, + '-1210' => DB_ERROR_INVALID_DATE, + '-1212' => DB_ERROR_INVALID_DATE + ); + + return $MAP; +} + +function adodb_error_oci8() +{ +static $MAP = array( + 1 => DB_ERROR_ALREADY_EXISTS, + 900 => DB_ERROR_SYNTAX, + 904 => DB_ERROR_NOSUCHFIELD, + 923 => DB_ERROR_SYNTAX, + 942 => DB_ERROR_NOSUCHTABLE, + 955 => DB_ERROR_ALREADY_EXISTS, + 1476 => DB_ERROR_DIVZERO, + 1722 => DB_ERROR_INVALID_NUMBER, + 2289 => DB_ERROR_NOSUCHTABLE, + 2291 => DB_ERROR_CONSTRAINT, + 2449 => DB_ERROR_CONSTRAINT + ); + + return $MAP; +} + +function adodb_error_mssql() +{ +static $MAP = array( + 208 => DB_ERROR_NOSUCHTABLE, + 2601 => DB_ERROR_ALREADY_EXISTS + ); + + return $MAP; +} + +function adodb_error_sqlite() +{ +static $MAP = array( + 1 => DB_ERROR_SYNTAX + ); + + return $MAP; +} + +function adodb_error_mysql() +{ +static $MAP = array( + 1004 => DB_ERROR_CANNOT_CREATE, + 1005 => DB_ERROR_CANNOT_CREATE, + 1006 => DB_ERROR_CANNOT_CREATE, + 1007 => DB_ERROR_ALREADY_EXISTS, + 1008 => DB_ERROR_CANNOT_DROP, + 1045 => DB_ERROR_ACCESS_VIOLATION, + 1046 => DB_ERROR_NODBSELECTED, + 1049 => DB_ERROR_NOSUCHDB, + 1050 => DB_ERROR_ALREADY_EXISTS, + 1051 => DB_ERROR_NOSUCHTABLE, + 1054 => DB_ERROR_NOSUCHFIELD, + 1062 => DB_ERROR_ALREADY_EXISTS, + 1064 => DB_ERROR_SYNTAX, + 1100 => DB_ERROR_NOT_LOCKED, + 1136 => DB_ERROR_VALUE_COUNT_ON_ROW, + 1146 => DB_ERROR_NOSUCHTABLE, + 1048 => DB_ERROR_CONSTRAINT, + 2002 => DB_ERROR_CONNECT_FAILED, + 2005 => DB_ERROR_CONNECT_FAILED + ); + + return $MAP; +} +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-errorhandler.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-errorhandler.inc.php new file mode 100644 index 0000000..f98a85c --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-errorhandler.inc.php @@ -0,0 +1,79 @@ +$s

    "; + trigger_error($s,ADODB_ERROR_HANDLER_TYPE); +} +?> diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-errorpear.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-errorpear.inc.php new file mode 100644 index 0000000..a2061a4 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-errorpear.inc.php @@ -0,0 +1,88 @@ +!$s

    "; +} + +/** +* Returns last PEAR_Error object. This error might be for an error that +* occured several sql statements ago. +*/ +function ADODB_PEAR_Error() +{ +global $ADODB_Last_PEAR_Error; + + return $ADODB_Last_PEAR_Error; +} + +?> diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-exceptions.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-exceptions.inc.php new file mode 100644 index 0000000..cc38fcd --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-exceptions.inc.php @@ -0,0 +1,80 @@ +sql = $p1; + $this->params = $p2; + $s = "$dbms error: [$errno: $errmsg] in $fn(\"$p1\")\n"; + break; + + case 'PCONNECT': + case 'CONNECT': + $user = $thisConnection->user; + $s = "$dbms error: [$errno: $errmsg] in $fn($p1, '$user', '****', $p2)\n"; + break; + default: + $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n"; + break; + } + + $this->dbms = $dbms; + $this->host = $thisConnection->host; + $this->database = $thisConnection->database; + $this->fn = $fn; + $this->msg = $errmsg; + + if (!is_numeric($errno)) $errno = -1; + parent::__construct($s,$errno); + } +} + +/** +* Default Error Handler. This will be called with the following params +* +* @param $dbms the RDBMS you are connecting to +* @param $fn the name of the calling function (in uppercase) +* @param $errno the native error number from the database +* @param $errmsg the native error msg from the database +* @param $p1 $fn specific parameter - see below +* @param $P2 $fn specific parameter - see below +*/ + +function adodb_throw($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection) +{ +global $ADODB_EXCEPTION; + + if (error_reporting() == 0) return; // obey @ protocol + if (is_string($ADODB_EXCEPTION)) $errfn = $ADODB_EXCEPTION; + else $errfn = 'ADODB_EXCEPTION'; + throw new $errfn($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection); +} + + +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-iterator.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-iterator.inc.php new file mode 100644 index 0000000..3770b1d --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-iterator.inc.php @@ -0,0 +1,84 @@ +Execute("select * from adoxyz"); + foreach($rs as $k => $v) { + echo $k; print_r($v); echo "
    "; + } + + + Iterator code based on http://cvs.php.net/cvs.php/php-src/ext/spl/examples/cachingiterator.inc?login=2 + */ + + + class ADODB_Iterator implements Iterator { + + private $rs; + + function __construct($rs) + { + $this->rs = $rs; + } + function rewind() + { + $this->rs->MoveFirst(); + } + + function valid() + { + return !$this->rs->EOF; + } + + function key() + { + return $this->rs->_currentRow; + } + + function current() + { + return $this->rs->fields; + } + + function next() + { + $this->rs->MoveNext(); + } + + function __call($func, $params) + { + return call_user_func_array(array($this->rs, $func), $params); + } + + + function hasMore() + { + return !$this->rs->EOF; + } + +} + + +class ADODB_BASE_RS implements IteratorAggregate { + function getIterator() { + return new ADODB_Iterator($this); + } + + /* this is experimental - i don't really know what to return... */ + function __toString() + { + include_once(ADODB_DIR.'/toexport.inc.php'); + return _adodb_export($this,',',',',false,true); + } +} + +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-lib.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-lib.inc.php new file mode 100644 index 0000000..783f262 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-lib.inc.php @@ -0,0 +1,1016 @@ +$value) + $new_array[strtoupper($key)] = $value; + + return $new_array; + } + + return $an_array; +} + +function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc) +{ + if (count($fieldArray) == 0) return 0; + $first = true; + $uSet = ''; + + if (!is_array($keyCol)) { + $keyCol = array($keyCol); + } + foreach($fieldArray as $k => $v) { + if ($autoQuote && !is_numeric($v) and strncmp($v,"'",1) !== 0 and strcasecmp($v,'null')!=0) { + $v = $zthis->qstr($v); + $fieldArray[$k] = $v; + } + if (in_array($k,$keyCol)) continue; // skip UPDATE if is key + + if ($first) { + $first = false; + $uSet = "$k=$v"; + } else + $uSet .= ",$k=$v"; + } + + $where = false; + foreach ($keyCol as $v) { + if (isset($fieldArray[$v])) { + if ($where) $where .= ' and '.$v.'='.$fieldArray[$v]; + else $where = $v.'='.$fieldArray[$v]; + } + } + + if ($uSet && $where) { + $update = "UPDATE $table SET $uSet WHERE $where"; + + $rs = $zthis->Execute($update); + + + if ($rs) { + if ($zthis->poorAffectedRows) { + /* + The Select count(*) wipes out any errors that the update would have returned. + http://phplens.com/lens/lensforum/msgs.php?id=5696 + */ + if ($zthis->ErrorNo()<>0) return 0; + + # affected_rows == 0 if update field values identical to old values + # for mysql - which is silly. + + $cnt = $zthis->GetOne("select count(*) from $table where $where"); + if ($cnt > 0) return 1; // record already exists + } else { + if (($zthis->Affected_Rows()>0)) return 1; + } + } else + return 0; + } + + // print "

    Error=".$this->ErrorNo().'

    '; + $first = true; + foreach($fieldArray as $k => $v) { + if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col + + if ($first) { + $first = false; + $iCols = "$k"; + $iVals = "$v"; + } else { + $iCols .= ",$k"; + $iVals .= ",$v"; + } + } + $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)"; + $rs = $zthis->Execute($insert); + return ($rs) ? 2 : 0; +} + +// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM +function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false, + $size=0, $selectAttr='',$compareFields0=true) +{ + $hasvalue = false; + + if ($multiple or is_array($defstr)) { + if ($size==0) $size=5; + $attr = ' multiple size="'.$size.'"'; + if (!strpos($name,'[]')) $name .= '[]'; + } else if ($size) $attr = ' size="'.$size.'"'; + else $attr =''; + + $s = '\n"; +} + +// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM +function _adodb_getmenu_gp(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false, + $size=0, $selectAttr='',$compareFields0=true) +{ + $hasvalue = false; + + if ($multiple or is_array($defstr)) { + if ($size==0) $size=5; + $attr = ' multiple size="'.$size.'"'; + if (!strpos($name,'[]')) $name .= '[]'; + } else if ($size) $attr = ' size="'.$size.'"'; + else $attr =''; + + $s = '\n"; +} + + +/* + Count the number of records this sql statement will return by using + query rewriting techniques... + + Does not work with UNIONs, except with postgresql and oracle. + + Usage: + + $conn->Connect(...); + $cnt = _adodb_getcount($conn, $sql); + +*/ +function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) +{ + $qryRecs = 0; + + if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || + preg_match('/\s+GROUP\s+BY\s+/is',$sql) || + preg_match('/\s+UNION\s+/is',$sql)) { + // ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias + // but this is only supported by oracle and postgresql... + if ($zthis->dataProvider == 'oci8') { + + $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql); + + // Allow Oracle hints to be used for query optimization, Chris Wrye + if (preg_match('#/\\*+.*?\\*\\/#', $sql, $hint)) { + $rewritesql = "SELECT ".$hint[0]." COUNT(*) FROM (".$rewritesql.")"; + } else + $rewritesql = "SELECT COUNT(*) FROM (".$rewritesql.")"; + + } else if (strncmp($zthis->databaseType,'postgres',8) == 0) { + + $info = $zthis->ServerInfo(); + if (substr($info['version'],0,3) >= 7.1) { // good till version 999 + $rewritesql = preg_replace('/(\sORDER\s+BY\s[^)]*)/is','',$sql); + $rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_"; + } + } + } else { + // now replace SELECT ... FROM with SELECT COUNT(*) FROM + $rewritesql = preg_replace( + '/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql); + + // fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails + // with mssql, access and postgresql. Also a good speedup optimization - skips sorting! + $rewritesql = preg_replace('/(\sORDER\s+BY\s[^)]*)/is','',$rewritesql); + } + + if (isset($rewritesql) && $rewritesql != $sql) { + if ($secs2cache) { + // we only use half the time of secs2cache because the count can quickly + // become inaccurate if new records are added + $qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr); + + } else { + $qryRecs = $zthis->GetOne($rewritesql,$inputarr); + } + if ($qryRecs !== false) return $qryRecs; + } + //-------------------------------------------- + // query rewrite failed - so try slower way... + + + // strip off unneeded ORDER BY if no UNION + if (preg_match('/\s*UNION\s*/is', $sql)) $rewritesql = $sql; + else $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql); + + $rstest = &$zthis->Execute($rewritesql,$inputarr); + if (!$rstest) $rstest = $zthis->Execute($sql,$inputarr); + + if ($rstest) { + $qryRecs = $rstest->RecordCount(); + if ($qryRecs == -1) { + global $ADODB_EXTENSION; + // some databases will return -1 on MoveLast() - change to MoveNext() + if ($ADODB_EXTENSION) { + while(!$rstest->EOF) { + adodb_movenext($rstest); + } + } else { + while(!$rstest->EOF) { + $rstest->MoveNext(); + } + } + $qryRecs = $rstest->_currentRow; + } + $rstest->Close(); + if ($qryRecs == -1) return 0; + } + + return $qryRecs; +} + +/* + Code originally from "Cornel G" + + This code might not work with SQL that has UNION in it + + Also if you are using CachePageExecute(), there is a strong possibility that + data will get out of synch. use CachePageExecute() only with tables that + rarely change. +*/ +function _adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page, + $inputarr=false, $secs2cache=0) +{ + $atfirstpage = false; + $atlastpage = false; + $lastpageno=1; + + // If an invalid nrows is supplied, + // we assume a default value of 10 rows per page + if (!isset($nrows) || $nrows <= 0) $nrows = 10; + + $qryRecs = false; //count records for no offset + + $qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache); + $lastpageno = (int) ceil($qryRecs / $nrows); + $zthis->_maxRecordCount = $qryRecs; + + + + // ***** Here we check whether $page is the last page or + // whether we are trying to retrieve + // a page number greater than the last page number. + if ($page >= $lastpageno) { + $page = $lastpageno; + $atlastpage = true; + } + + // If page number <= 1, then we are at the first page + if (empty($page) || $page <= 1) { + $page = 1; + $atfirstpage = true; + } + + // We get the data we want + $offset = $nrows * ($page-1); + if ($secs2cache > 0) + $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr); + else + $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); + + + // Before returning the RecordSet, we set the pagination properties we need + if ($rsreturn) { + $rsreturn->_maxRecordCount = $qryRecs; + $rsreturn->rowsPerPage = $nrows; + $rsreturn->AbsolutePage($page); + $rsreturn->AtFirstPage($atfirstpage); + $rsreturn->AtLastPage($atlastpage); + $rsreturn->LastPageNo($lastpageno); + } + return $rsreturn; +} + +// Iván Oliva version +function _adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0) +{ + + $atfirstpage = false; + $atlastpage = false; + + if (!isset($page) || $page <= 1) { // If page number <= 1, then we are at the first page + $page = 1; + $atfirstpage = true; + } + if ($nrows <= 0) $nrows = 10; // If an invalid nrows is supplied, we assume a default value of 10 rows per page + + // ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than + // the last page number. + $pagecounter = $page + 1; + $pagecounteroffset = ($pagecounter * $nrows) - $nrows; + if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr); + else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache); + if ($rstest) { + while ($rstest && $rstest->EOF && $pagecounter>0) { + $atlastpage = true; + $pagecounter--; + $pagecounteroffset = $nrows * ($pagecounter - 1); + $rstest->Close(); + if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr); + else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache); + } + if ($rstest) $rstest->Close(); + } + if ($atlastpage) { // If we are at the last page or beyond it, we are going to retrieve it + $page = $pagecounter; + if ($page == 1) $atfirstpage = true; // We have to do this again in case the last page is the same as the first + //... page, that is, the recordset has only 1 page. + } + + // We get the data we want + $offset = $nrows * ($page-1); + if ($secs2cache > 0) $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr); + else $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); + + // Before returning the RecordSet, we set the pagination properties we need + if ($rsreturn) { + $rsreturn->rowsPerPage = $nrows; + $rsreturn->AbsolutePage($page); + $rsreturn->AtFirstPage($atfirstpage); + $rsreturn->AtLastPage($atlastpage); + } + return $rsreturn; +} + +function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=2) +{ + if (!$rs) { + printf(ADODB_BAD_RS,'GetUpdateSQL'); + return false; + } + + $fieldUpdatedCount = 0; + $arrFields = _array_change_key_case($arrFields); + + $hasnumeric = isset($rs->fields[0]); + $setFields = ''; + + // Loop through all of the fields in the recordset + for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) { + // Get the field from the recordset + $field = $rs->FetchField($i); + + // If the recordset field is one + // of the fields passed in then process. + $upperfname = strtoupper($field->name); + if (adodb_key_exists($upperfname,$arrFields,$force)) { + + // If the existing field value in the recordset + // is different from the value passed in then + // go ahead and append the field name and new value to + // the update query. + + if ($hasnumeric) $val = $rs->fields[$i]; + else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname]; + else if (isset($rs->fields[$field->name])) $val = $rs->fields[$field->name]; + else if (isset($rs->fields[strtolower($upperfname)])) $val = $rs->fields[strtolower($upperfname)]; + else $val = ''; + + + if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) { + // Set the counter for the number of fields that will be updated. + $fieldUpdatedCount++; + + // Based on the datatype of the field + // Format the value properly for the database + $type = $rs->MetaType($field->type); + + + if ($type == 'null') { + $type = 'C'; + } + + if (strpos($upperfname,' ') !== false) + $fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote; + else + $fnameq = $upperfname; + + + // is_null requires php 4.0.4 + //********************************************************// + if (is_null($arrFields[$upperfname]) + || (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0) + || $arrFields[$upperfname] === 'null' + ) + { + switch ($force) { + + //case 0: + // //Ignore empty values. This is allready handled in "adodb_key_exists" function. + //break; + + case 1: + //Set null + $setFields .= $field->name . " = null, "; + break; + + case 2: + //Set empty + $arrFields[$upperfname] = ""; + $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq); + break; + default: + case 3: + //Set the value that was given in array, so you can give both null and empty values + if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === 'null') { + $setFields .= $field->name . " = null, "; + } else { + $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq); + } + break; + } + //********************************************************// + } else { + //we do this so each driver can customize the sql for + //DB specific column types. + //Oracle needs BLOB types to be handled with a returning clause + //postgres has special needs as well + $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq, + $arrFields, $magicq); + } + } + } + } + + // If there were any modified fields then build the rest of the update query. + if ($fieldUpdatedCount > 0 || $forceUpdate) { + // Get the table name from the existing query. + if (!empty($rs->tableName)) $tableName = $rs->tableName; + else { + preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName); + $tableName = $tableName[1]; + } + // Get the full where clause excluding the word "WHERE" from + // the existing query. + preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause); + + $discard = false; + // not a good hack, improvements? + if ($whereClause) { + #var_dump($whereClause); + if (preg_match('/\s(ORDER\s.*)/is', $whereClause[1], $discard)); + else if (preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard)); + else if (preg_match('/\s(FOR UPDATE.*)/is', $whereClause[1], $discard)); + else preg_match('/\s.*(\) WHERE .*)/is', $whereClause[1], $discard); # see http://sourceforge.net/tracker/index.php?func=detail&aid=1379638&group_id=42718&atid=433976 + } else + $whereClause = array(false,false); + + if ($discard) + $whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1])); + + $sql = 'UPDATE '.$tableName.' SET '.substr($setFields, 0, -2); + if (strlen($whereClause[1]) > 0) + $sql .= ' WHERE '.$whereClause[1]; + + return $sql; + + } else { + return false; + } +} + +function adodb_key_exists($key, &$arr,$force=2) +{ + if ($force<=0) { + // the following is the old behaviour where null or empty fields are ignored + return (!empty($arr[$key])) || (isset($arr[$key]) && strlen($arr[$key])>0); + } + + if (isset($arr[$key])) return true; + ## null check below + if (ADODB_PHPVER >= 0x4010) return array_key_exists($key,$arr); + return false; +} + +/** + * There is a special case of this function for the oci8 driver. + * The proper way to handle an insert w/ a blob in oracle requires + * a returning clause with bind variables and a descriptor blob. + * + * + */ +function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$force=2) +{ +static $cacheRS = false; +static $cacheSig = 0; +static $cacheCols; + + $tableName = ''; + $values = ''; + $fields = ''; + $recordSet = null; + $arrFields = _array_change_key_case($arrFields); + $fieldInsertedCount = 0; + + if (is_string($rs)) { + //ok we have a table name + //try and get the column info ourself. + $tableName = $rs; + + //we need an object for the recordSet + //because we have to call MetaType. + //php can't do a $rsclass::MetaType() + $rsclass = $zthis->rsPrefix.$zthis->databaseType; + $recordSet = new $rsclass(-1,$zthis->fetchMode); + $recordSet->connection = &$zthis; + + if (is_string($cacheRS) && $cacheRS == $rs) { + $columns =& $cacheCols; + } else { + $columns = $zthis->MetaColumns( $tableName ); + $cacheRS = $tableName; + $cacheCols = $columns; + } + } else if (is_subclass_of($rs, 'adorecordset')) { + if (isset($rs->insertSig) && is_integer($cacheRS) && $cacheRS == $rs->insertSig) { + $columns =& $cacheCols; + } else { + for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) + $columns[] = $rs->FetchField($i); + $cacheRS = $cacheSig; + $cacheCols = $columns; + $rs->insertSig = $cacheSig++; + } + $recordSet =& $rs; + + } else { + printf(ADODB_BAD_RS,'GetInsertSQL'); + return false; + } + + // Loop through all of the fields in the recordset + foreach( $columns as $field ) { + $upperfname = strtoupper($field->name); + if (adodb_key_exists($upperfname,$arrFields,$force)) { + $bad = false; + if (strpos($upperfname,' ') !== false) + $fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote; + else + $fnameq = $upperfname; + + $type = $recordSet->MetaType($field->type); + + /********************************************************/ + if (is_null($arrFields[$upperfname]) + || (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0) + || $arrFields[$upperfname] === 'null' + ) + { + switch ($force) { + + case 0: // we must always set null if missing + $bad = true; + break; + + case 1: + $values .= "null, "; + break; + + case 2: + //Set empty + $arrFields[$upperfname] = ""; + $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq,$arrFields, $magicq); + break; + + default: + case 3: + //Set the value that was given in array, so you can give both null and empty values + if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === 'null') { + $values .= "null, "; + } else { + $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq, $arrFields, $magicq); + } + break; + } // switch + + /*********************************************************/ + } else { + //we do this so each driver can customize the sql for + //DB specific column types. + //Oracle needs BLOB types to be handled with a returning clause + //postgres has special needs as well + $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq, + $arrFields, $magicq); + } + + if ($bad) continue; + // Set the counter for the number of fields that will be inserted. + $fieldInsertedCount++; + + + // Get the name of the fields to insert + $fields .= $fnameq . ", "; + } + } + + + // If there were any inserted fields then build the rest of the insert query. + if ($fieldInsertedCount <= 0) return false; + + // Get the table name from the existing query. + if (!$tableName) { + if (!empty($rs->tableName)) $tableName = $rs->tableName; + else if (preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName)) + $tableName = $tableName[1]; + else + return false; + } + + // Strip off the comma and space on the end of both the fields + // and their values. + $fields = substr($fields, 0, -2); + $values = substr($values, 0, -2); + + // Append the fields and their values to the insert query. + return 'INSERT INTO '.$tableName.' ( '.$fields.' ) VALUES ( '.$values.' )'; +} + + +/** + * This private method is used to help construct + * the update/sql which is generated by GetInsertSQL and GetUpdateSQL. + * It handles the string construction of 1 column -> sql string based on + * the column type. We want to do 'safe' handling of BLOBs + * + * @param string the type of sql we are trying to create + * 'I' or 'U'. + * @param string column data type from the db::MetaType() method + * @param string the column name + * @param array the column value + * + * @return string + * + */ +function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $fnameq, $arrFields, $magicq) +{ + $sql = ''; + + // Based on the datatype of the field + // Format the value properly for the database + switch($type) { + case 'B': + //in order to handle Blobs correctly, we need + //to do some magic for Oracle + + //we need to create a new descriptor to handle + //this properly + if (!empty($zthis->hasReturningInto)) { + if ($action == 'I') { + $sql = 'empty_blob(), '; + } else { + $sql = $fnameq. '=empty_blob(), '; + } + //add the variable to the returning clause array + //so the user can build this later in + //case they want to add more to it + $zthis->_returningArray[$fname] = ':xx'.$fname.'xx'; + } else if (empty($arrFields[$fname])){ + if ($action == 'I') { + $sql = 'empty_blob(), '; + } else { + $sql = $fnameq. '=empty_blob(), '; + } + } else { + //this is to maintain compatibility + //with older adodb versions. + $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false); + } + break; + + case "X": + //we need to do some more magic here for long variables + //to handle these correctly in oracle. + + //create a safe bind var name + //to avoid conflicts w/ dupes. + if (!empty($zthis->hasReturningInto)) { + if ($action == 'I') { + $sql = ':xx'.$fname.'xx, '; + } else { + $sql = $fnameq.'=:xx'.$fname.'xx, '; + } + //add the variable to the returning clause array + //so the user can build this later in + //case they want to add more to it + $zthis->_returningArray[$fname] = ':xx'.$fname.'xx'; + } else { + //this is to maintain compatibility + //with older adodb versions. + $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false); + } + break; + + default: + $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false); + break; + } + + return $sql; +} + +function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq, $recurse=true) +{ + + if ($recurse) { + switch($zthis->dataProvider) { + case 'postgres': + if ($type == 'L') $type = 'C'; + break; + case 'oci8': + return _adodb_column_sql_oci8($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq); + + } + } + + switch($type) { + case "C": + case "X": + case 'B': + $val = $zthis->qstr($arrFields[$fname],$magicq); + break; + + case "D": + $val = $zthis->DBDate($arrFields[$fname]); + break; + + case "T": + $val = $zthis->DBTimeStamp($arrFields[$fname]); + break; + + default: + $val = $arrFields[$fname]; + if (empty($val)) $val = '0'; + break; + } + + if ($action == 'I') return $val . ", "; + + + return $fnameq . "=" . $val . ", "; + +} + + + +function _adodb_debug_execute(&$zthis, $sql, $inputarr) +{ + $ss = ''; + if ($inputarr) { + foreach($inputarr as $kk=>$vv) { + if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...'; + $ss .= "($kk=>'$vv') "; + } + $ss = "[ $ss ]"; + } + $sqlTxt = is_array($sql) ? $sql[0] : $sql; + /*str_replace(', ','##1#__^LF',is_array($sql) ? $sql[0] : $sql); + $sqlTxt = str_replace(',',', ',$sqlTxt); + $sqlTxt = str_replace('##1#__^LF', ', ' ,$sqlTxt); + */ + // check if running from browser or command-line + $inBrowser = isset($_SERVER['HTTP_USER_AGENT']); + + $dbt = $zthis->databaseType; + if (isset($zthis->dsnType)) $dbt .= '-'.$zthis->dsnType; + if ($inBrowser) { + if ($ss) { + $ss = ''.htmlspecialchars($ss).''; + } + if ($zthis->debug === -1) + ADOConnection::outp( "
    \n($dbt): ".htmlspecialchars($sqlTxt)."   $ss\n
    \n",false); + else + ADOConnection::outp( "


    \n($dbt): ".htmlspecialchars($sqlTxt)."   $ss\n
    \n",false); + } else { + ADOConnection::outp("-----\n($dbt): ".$sqlTxt."\n-----\n",false); + } + + $qID = $zthis->_query($sql,$inputarr); + + /* + Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql + because ErrorNo() calls Execute('SELECT @ERROR'), causing recursion + */ + if ($zthis->databaseType == 'mssql') { + // ErrorNo is a slow function call in mssql, and not reliable in PHP 4.0.6 + if($emsg = $zthis->ErrorMsg()) { + if ($err = $zthis->ErrorNo()) ADOConnection::outp($err.': '.$emsg); + } + } else if (!$qID) { + ADOConnection::outp($zthis->ErrorNo() .': '. $zthis->ErrorMsg()); + } + + if ($zthis->debug === 99) _adodb_backtrace(true,9999,2); + return $qID; +} + +# pretty print the debug_backtrace function +function _adodb_backtrace($printOrArr=true,$levels=9999,$skippy=0) +{ + if (!function_exists('debug_backtrace')) return ''; + + $html = (isset($_SERVER['HTTP_USER_AGENT'])); + $fmt = ($html) ? " %% line %4d, file: %s" : "%% line %4d, file: %s"; + + $MAXSTRLEN = 128; + + $s = ($html) ? '
    ' : '';
    +	
    +	if (is_array($printOrArr)) $traceArr = $printOrArr;
    +	else $traceArr = debug_backtrace();
    +	array_shift($traceArr);
    +	array_shift($traceArr);
    +	$tabs = sizeof($traceArr)-2;
    +	
    +	foreach ($traceArr as $arr) {
    +		if ($skippy) {$skippy -= 1; continue;}
    +		$levels -= 1;
    +		if ($levels < 0) break;
    +		
    +		$args = array();
    +		for ($i=0; $i < $tabs; $i++) $s .=  ($html) ? '   ' : "\t";
    +		$tabs -= 1;
    +		if ($html) $s .= '';
    +		if (isset($arr['class'])) $s .= $arr['class'].'.';
    +		if (isset($arr['args']))
    +		 foreach($arr['args'] as $v) {
    +			if (is_null($v)) $args[] = 'null';
    +			else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
    +			else if (is_object($v)) $args[] = 'Object:'.get_class($v);
    +			else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
    +			else {
    +				$v = (string) @$v;
    +				$str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
    +				if (strlen($v) > $MAXSTRLEN) $str .= '...';
    +				$args[] = $str;
    +			}
    +		}
    +		$s .= $arr['function'].'('.implode(', ',$args).')';
    +		
    +		
    +		$s .= @sprintf($fmt, $arr['line'],$arr['file'],basename($arr['file']));
    +			
    +		$s .= "\n";
    +	}	
    +	if ($html) $s .= '
    '; + if ($printOrArr) print $s; + + return $s; +} + +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-pager.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-pager.inc.php new file mode 100644 index 0000000..b9cce73 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-pager.inc.php @@ -0,0 +1,290 @@ + implemented Render_PageLinks(). + + Please note, this class is entirely unsupported, + and no free support requests except for bug reports + will be entertained by the author. + +*/ +class ADODB_Pager { + var $id; // unique id for pager (defaults to 'adodb') + var $db; // ADODB connection object + var $sql; // sql used + var $rs; // recordset generated + var $curr_page; // current page number before Render() called, calculated in constructor + var $rows; // number of rows per page + var $linksPerPage=10; // number of links per page in navigation bar + var $showPageLinks; + + var $gridAttributes = 'width=100% border=1 bgcolor=white'; + + // Localize text strings here + var $first = '|<'; + var $prev = '<<'; + var $next = '>>'; + var $last = '>|'; + var $moreLinks = '...'; + var $startLinks = '...'; + var $gridHeader = false; + var $htmlSpecialChars = true; + var $page = 'Page'; + var $linkSelectedColor = 'red'; + var $cache = 0; #secs to cache with CachePageExecute() + + //---------------------------------------------- + // constructor + // + // $db adodb connection object + // $sql sql statement + // $id optional id to identify which pager, + // if you have multiple on 1 page. + // $id should be only be [a-z0-9]* + // + function ADODB_Pager(&$db,$sql,$id = 'adodb', $showPageLinks = false) + { + global $PHP_SELF; + + $curr_page = $id.'_curr_page'; + if (empty($PHP_SELF)) $PHP_SELF = $_SERVER['PHP_SELF']; + + $this->sql = $sql; + $this->id = $id; + $this->db = $db; + $this->showPageLinks = $showPageLinks; + + $next_page = $id.'_next_page'; + + if (isset($_GET[$next_page])) { + $_SESSION[$curr_page] = $_GET[$next_page]; + } + if (empty($_SESSION[$curr_page])) $_SESSION[$curr_page] = 1; ## at first page + + $this->curr_page = $_SESSION[$curr_page]; + + } + + //--------------------------- + // Display link to first page + function Render_First($anchor=true) + { + global $PHP_SELF; + if ($anchor) { + ?> + first;?>   + first   "; + } + } + + //-------------------------- + // Display link to next page + function render_next($anchor=true) + { + global $PHP_SELF; + + if ($anchor) { + ?> + next;?>   + next   "; + } + } + + //------------------ + // Link to last page + // + // for better performance with large recordsets, you can set + // $this->db->pageExecuteCountRows = false, which disables + // last page counting. + function render_last($anchor=true) + { + global $PHP_SELF; + + if (!$this->db->pageExecuteCountRows) return; + + if ($anchor) { + ?> + last;?>   + last   "; + } + } + + //--------------------------------------------------- + // original code by "Pablo Costa" + function render_pagelinks() + { + global $PHP_SELF; + $pages = $this->rs->LastPageNo(); + $linksperpage = $this->linksPerPage ? $this->linksPerPage : $pages; + for($i=1; $i <= $pages; $i+=$linksperpage) + { + if($this->rs->AbsolutePage() >= $i) + { + $start = $i; + } + } + $numbers = ''; + $end = $start+$linksperpage-1; + $link = $this->id . "_next_page"; + if($end > $pages) $end = $pages; + + + if ($this->startLinks && $start > 1) { + $pos = $start - 1; + $numbers .= "$this->startLinks "; + } + + for($i=$start; $i <= $end; $i++) { + if ($this->rs->AbsolutePage() == $i) + $numbers .= "linkSelectedColor>$i "; + else + $numbers .= "$i "; + + } + if ($this->moreLinks && $end < $pages) + $numbers .= "$this->moreLinks "; + print $numbers . '   '; + } + // Link to previous page + function render_prev($anchor=true) + { + global $PHP_SELF; + if ($anchor) { + ?> + prev;?>   + prev   "; + } + } + + //-------------------------------------------------------- + // Simply rendering of grid. You should override this for + // better control over the format of the grid + // + // We use output buffering to keep code clean and readable. + function RenderGrid() + { + global $gSQLBlockRows; // used by rs2html to indicate how many rows to display + include_once(ADODB_DIR.'/tohtml.inc.php'); + ob_start(); + $gSQLBlockRows = $this->rows; + rs2html($this->rs,$this->gridAttributes,$this->gridHeader,$this->htmlSpecialChars); + $s = ob_get_contents(); + ob_end_clean(); + return $s; + } + + //------------------------------------------------------- + // Navigation bar + // + // we use output buffering to keep the code easy to read. + function RenderNav() + { + ob_start(); + if (!$this->rs->AtFirstPage()) { + $this->Render_First(); + $this->Render_Prev(); + } else { + $this->Render_First(false); + $this->Render_Prev(false); + } + if ($this->showPageLinks){ + $this->Render_PageLinks(); + } + if (!$this->rs->AtLastPage()) { + $this->Render_Next(); + $this->Render_Last(); + } else { + $this->Render_Next(false); + $this->Render_Last(false); + } + $s = ob_get_contents(); + ob_end_clean(); + return $s; + } + + //------------------- + // This is the footer + function RenderPageCount() + { + if (!$this->db->pageExecuteCountRows) return ''; + $lastPage = $this->rs->LastPageNo(); + if ($lastPage == -1) $lastPage = 1; // check for empty rs. + if ($this->curr_page > $lastPage) $this->curr_page = 1; + return "$this->page ".$this->curr_page."/".$lastPage.""; + } + + //----------------------------------- + // Call this class to draw everything. + function Render($rows=10) + { + global $ADODB_COUNTRECS; + + $this->rows = $rows; + + if ($this->db->dataProvider == 'informix') $this->db->cursorType = IFX_SCROLL; + + $savec = $ADODB_COUNTRECS; + if ($this->db->pageExecuteCountRows) $ADODB_COUNTRECS = true; + if ($this->cache) + $rs = &$this->db->CachePageExecute($this->cache,$this->sql,$rows,$this->curr_page); + else + $rs = &$this->db->PageExecute($this->sql,$rows,$this->curr_page); + $ADODB_COUNTRECS = $savec; + + $this->rs = &$rs; + if (!$rs) { + print "

    Query failed: $this->sql

    "; + return; + } + + if (!$rs->EOF && (!$rs->AtFirstPage() || !$rs->AtLastPage())) + $header = $this->RenderNav(); + else + $header = " "; + + $grid = $this->RenderGrid(); + $footer = $this->RenderPageCount(); + + $this->RenderLayout($header,$grid,$footer); + + $rs->Close(); + $this->rs = false; + } + + //------------------------------------------------------ + // override this to control overall layout and formating + function RenderLayout($header,$grid,$footer,$attributes='border=1 bgcolor=beige') + { + echo "
    ", + $header, + "
    ", + $grid, + "
    ", + $footer, + "
    "; + } +} + + +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-pear.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-pear.inc.php new file mode 100644 index 0000000..e0545d1 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-pear.inc.php @@ -0,0 +1,374 @@ + | + * and Tomas V.V.Cox . Portions (c)1997-2002 The PHP Group. + */ + + /* + We support: + + DB_Common + --------- + query - returns PEAR_Error on error + limitQuery - return PEAR_Error on error + prepare - does not return PEAR_Error on error + execute - does not return PEAR_Error on error + setFetchMode - supports ASSOC and ORDERED + errorNative + quote + nextID + disconnect + + getOne + getAssoc + getRow + getCol + getAll + + DB_Result + --------- + numRows - returns -1 if not supported + numCols + fetchInto - does not support passing of fetchmode + fetchRows - does not support passing of fetchmode + free + */ + +define('ADODB_PEAR',dirname(__FILE__)); +include_once "PEAR.php"; +include_once ADODB_PEAR."/adodb-errorpear.inc.php"; +include_once ADODB_PEAR."/adodb.inc.php"; + +if (!defined('DB_OK')) { +define("DB_OK", 1); +define("DB_ERROR",-1); + +// autoExecute constants +define('DB_AUTOQUERY_INSERT', 1); +define('DB_AUTOQUERY_UPDATE', 2); + +/** + * This is a special constant that tells DB the user hasn't specified + * any particular get mode, so the default should be used. + */ + +define('DB_FETCHMODE_DEFAULT', 0); + +/** + * Column data indexed by numbers, ordered from 0 and up + */ + +define('DB_FETCHMODE_ORDERED', 1); + +/** + * Column data indexed by column names + */ + +define('DB_FETCHMODE_ASSOC', 2); + +/* for compatibility */ + +define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED); +define('DB_GETMODE_ASSOC', DB_FETCHMODE_ASSOC); + +/** + * these are constants for the tableInfo-function + * they are bitwised or'ed. so if there are more constants to be defined + * in the future, adjust DB_TABLEINFO_FULL accordingly + */ + +define('DB_TABLEINFO_ORDER', 1); +define('DB_TABLEINFO_ORDERTABLE', 2); +define('DB_TABLEINFO_FULL', 3); +} + +/** + * The main "DB" class is simply a container class with some static + * methods for creating DB objects as well as some utility functions + * common to all parts of DB. + * + */ + +class DB +{ + /** + * Create a new DB object for the specified database type + * + * @param $type string database type, for example "mysql" + * + * @return object a newly created DB object, or a DB error code on + * error + */ + + function factory($type) + { + include_once(ADODB_DIR."/drivers/adodb-$type.inc.php"); + $obj = &NewADOConnection($type); + if (!is_object($obj)) $obj = new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1); + return $obj; + } + + /** + * Create a new DB object and connect to the specified database + * + * @param $dsn mixed "data source name", see the DB::parseDSN + * method for a description of the dsn format. Can also be + * specified as an array of the format returned by DB::parseDSN. + * + * @param $options mixed if boolean (or scalar), tells whether + * this connection should be persistent (for backends that support + * this). This parameter can also be an array of options, see + * DB_common::setOption for more information on connection + * options. + * + * @return object a newly created DB connection object, or a DB + * error object on error + * + * @see DB::parseDSN + * @see DB::isError + */ + function connect($dsn, $options = false) + { + if (is_array($dsn)) { + $dsninfo = $dsn; + } else { + $dsninfo = DB::parseDSN($dsn); + } + switch ($dsninfo["phptype"]) { + case 'pgsql': $type = 'postgres7'; break; + case 'ifx': $type = 'informix9'; break; + default: $type = $dsninfo["phptype"]; break; + } + + if (is_array($options) && isset($options["debug"]) && + $options["debug"] >= 2) { + // expose php errors with sufficient debug level + @include_once("adodb-$type.inc.php"); + } else { + @include_once("adodb-$type.inc.php"); + } + + @$obj =& NewADOConnection($type); + if (!is_object($obj)) { + $obj = new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1); + return $obj; + } + if (is_array($options)) { + foreach($options as $k => $v) { + switch(strtolower($k)) { + case 'persist': + case 'persistent': $persist = $v; break; + #ibase + case 'dialect': $obj->dialect = $v; break; + case 'charset': $obj->charset = $v; break; + case 'buffers': $obj->buffers = $v; break; + #ado + case 'charpage': $obj->charPage = $v; break; + #mysql + case 'clientflags': $obj->clientFlags = $v; break; + } + } + } else { + $persist = false; + } + + if (isset($dsninfo['socket'])) $dsninfo['hostspec'] .= ':'.$dsninfo['socket']; + else if (isset($dsninfo['port'])) $dsninfo['hostspec'] .= ':'.$dsninfo['port']; + + if($persist) $ok = $obj->PConnect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']); + else $ok = $obj->Connect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']); + + if (!$ok) $obj = ADODB_PEAR_Error(); + return $obj; + } + + /** + * Return the DB API version + * + * @return int the DB API version number + */ + function apiVersion() + { + return 2; + } + + /** + * Tell whether a result code from a DB method is an error + * + * @param $value int result code + * + * @return bool whether $value is an error + */ + function isError($value) + { + if (!is_object($value)) return false; + $class = get_class($value); + return $class == 'pear_error' || is_subclass_of($value, 'pear_error') || + $class == 'db_error' || is_subclass_of($value, 'db_error'); + } + + + /** + * Tell whether a result code from a DB method is a warning. + * Warnings differ from errors in that they are generated by DB, + * and are not fatal. + * + * @param $value mixed result value + * + * @return bool whether $value is a warning + */ + function isWarning($value) + { + return false; + /* + return is_object($value) && + (get_class( $value ) == "db_warning" || + is_subclass_of($value, "db_warning"));*/ + } + + /** + * Parse a data source name + * + * @param $dsn string Data Source Name to be parsed + * + * @return array an associative array with the following keys: + * + * phptype: Database backend used in PHP (mysql, odbc etc.) + * dbsyntax: Database used with regards to SQL syntax etc. + * protocol: Communication protocol to use (tcp, unix etc.) + * hostspec: Host specification (hostname[:port]) + * database: Database to use on the DBMS server + * username: User name for login + * password: Password for login + * + * The format of the supplied DSN is in its fullest form: + * + * phptype(dbsyntax)://username:password@protocol+hostspec/database + * + * Most variations are allowed: + * + * phptype://username:password@protocol+hostspec:110//usr/db_file.db + * phptype://username:password@hostspec/database_name + * phptype://username:password@hostspec + * phptype://username@hostspec + * phptype://hostspec/database + * phptype://hostspec + * phptype(dbsyntax) + * phptype + * + * @author Tomas V.V.Cox + */ + function parseDSN($dsn) + { + if (is_array($dsn)) { + return $dsn; + } + + $parsed = array( + 'phptype' => false, + 'dbsyntax' => false, + 'protocol' => false, + 'hostspec' => false, + 'database' => false, + 'username' => false, + 'password' => false + ); + + // Find phptype and dbsyntax + if (($pos = strpos($dsn, '://')) !== false) { + $str = substr($dsn, 0, $pos); + $dsn = substr($dsn, $pos + 3); + } else { + $str = $dsn; + $dsn = NULL; + } + + // Get phptype and dbsyntax + // $str => phptype(dbsyntax) + if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) { + $parsed['phptype'] = $arr[1]; + $parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2]; + } else { + $parsed['phptype'] = $str; + $parsed['dbsyntax'] = $str; + } + + if (empty($dsn)) { + return $parsed; + } + + // Get (if found): username and password + // $dsn => username:password@protocol+hostspec/database + if (($at = strpos($dsn,'@')) !== false) { + $str = substr($dsn, 0, $at); + $dsn = substr($dsn, $at + 1); + if (($pos = strpos($str, ':')) !== false) { + $parsed['username'] = urldecode(substr($str, 0, $pos)); + $parsed['password'] = urldecode(substr($str, $pos + 1)); + } else { + $parsed['username'] = urldecode($str); + } + } + + // Find protocol and hostspec + // $dsn => protocol+hostspec/database + if (($pos=strpos($dsn, '/')) !== false) { + $str = substr($dsn, 0, $pos); + $dsn = substr($dsn, $pos + 1); + } else { + $str = $dsn; + $dsn = NULL; + } + + // Get protocol + hostspec + // $str => protocol+hostspec + if (($pos=strpos($str, '+')) !== false) { + $parsed['protocol'] = substr($str, 0, $pos); + $parsed['hostspec'] = urldecode(substr($str, $pos + 1)); + } else { + $parsed['hostspec'] = urldecode($str); + } + + // Get dabase if any + // $dsn => database + if (!empty($dsn)) { + $parsed['database'] = $dsn; + } + + return $parsed; + } + + /** + * Load a PHP database extension if it is not loaded already. + * + * @access public + * + * @param $name the base name of the extension (without the .so or + * .dll suffix) + * + * @return bool true if the extension was already or successfully + * loaded, false if it could not be loaded + */ + function assertExtension($name) + { + if (!extension_loaded($name)) { + $dlext = (strncmp(PHP_OS,'WIN',3) === 0) ? '.dll' : '.so'; + @dl($name . $dlext); + } + if (!extension_loaded($name)) { + return false; + } + return true; + } +} + +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-perf.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-perf.inc.php new file mode 100644 index 0000000..13df59a --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-perf.inc.php @@ -0,0 +1,1053 @@ +=2) return (integer) $memarr[1]; + + return 0; +} + +// avoids localization problems where , is used instead of . +function adodb_round($n,$prec) +{ + return number_format($n, $prec, '.', ''); +} + +/* return microtime value as a float */ +function adodb_microtime() +{ + $t = microtime(); + $t = explode(' ',$t); + return (float)$t[1]+ (float)$t[0]; +} + +/* sql code timing */ +function& adodb_log_sql(&$conn,$sql,$inputarr) +{ + + $perf_table = adodb_perf::table(); + $conn->fnExecute = false; + $t0 = microtime(); + $rs =& $conn->Execute($sql,$inputarr); + $t1 = microtime(); + + if (!empty($conn->_logsql)) { + $conn->_logsql = false; // disable logsql error simulation + $dbT = $conn->databaseType; + + $a0 = split(' ',$t0); + $a0 = (float)$a0[1]+(float)$a0[0]; + + $a1 = split(' ',$t1); + $a1 = (float)$a1[1]+(float)$a1[0]; + + $time = $a1 - $a0; + + if (!$rs) { + $errM = $conn->ErrorMsg(); + $errN = $conn->ErrorNo(); + $conn->lastInsID = 0; + $tracer = substr('ERROR: '.htmlspecialchars($errM),0,250); + } else { + $tracer = ''; + $errM = ''; + $errN = 0; + $dbg = $conn->debug; + $conn->debug = false; + if (!is_object($rs) || $rs->dataProvider == 'empty') + $conn->_affected = $conn->affected_rows(true); + $conn->lastInsID = @$conn->Insert_ID(); + $conn->debug = $dbg; + } + if (isset($_SERVER['HTTP_HOST'])) { + $tracer .= '
    '.$_SERVER['HTTP_HOST']; + if (isset($_SERVER['PHP_SELF'])) $tracer .= $_SERVER['PHP_SELF']; + } else + if (isset($_SERVER['PHP_SELF'])) $tracer .= '
    '.$_SERVER['PHP_SELF']; + //$tracer .= (string) adodb_backtrace(false); + + $tracer = (string) substr($tracer,0,500); + + if (is_array($inputarr)) { + if (is_array(reset($inputarr))) $params = 'Array sizeof='.sizeof($inputarr); + else { + // Quote string parameters so we can see them in the + // performance stats. This helps spot disabled indexes. + $xar_params = $inputarr; + foreach ($xar_params as $xar_param_key => $xar_param) { + if (gettype($xar_param) == 'string') + $xar_params[$xar_param_key] = '"' . $xar_param . '"'; + } + $params = implode(', ', $xar_params); + if (strlen($params) >= 3000) $params = substr($params, 0, 3000); + } + } else { + $params = ''; + } + + if (is_array($sql)) $sql = $sql[0]; + $arr = array('b'=>strlen($sql).'.'.crc32($sql), + 'c'=>substr($sql,0,3900), 'd'=>$params,'e'=>$tracer,'f'=>adodb_round($time,6)); + //var_dump($arr); + $saved = $conn->debug; + $conn->debug = 0; + + $d = $conn->sysTimeStamp; + if (empty($d)) $d = date("'Y-m-d H:i:s'"); + if ($conn->dataProvider == 'oci8' && $dbT != 'oci8po') { + $isql = "insert into $perf_table values($d,:b,:c,:d,:e,:f)"; + } else if ($dbT == 'odbc_mssql' || $dbT == 'informix' || $dbT == 'odbtp') { + $timer = $arr['f']; + if ($dbT == 'informix') $sql2 = substr($sql2,0,230); + + $sql1 = $conn->qstr($arr['b']); + $sql2 = $conn->qstr($arr['c']); + $params = $conn->qstr($arr['d']); + $tracer = $conn->qstr($arr['e']); + + $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values($d,$sql1,$sql2,$params,$tracer,$timer)"; + if ($dbT == 'informix') $isql = str_replace(chr(10),' ',$isql); + $arr = false; + } else { + $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values( $d,?,?,?,?,?)"; + } + + $ok = $conn->Execute($isql,$arr); + $conn->debug = $saved; + + if ($ok) { + $conn->_logsql = true; + } else { + $err2 = $conn->ErrorMsg(); + $conn->_logsql = true; // enable logsql error simulation + $perf =& NewPerfMonitor($conn); + if ($perf) { + if ($perf->CreateLogTable()) $ok = $conn->Execute($isql,$arr); + } else { + $ok = $conn->Execute("create table $perf_table ( + created varchar(50), + sql0 varchar(250), + sql1 varchar(4000), + params varchar(3000), + tracer varchar(500), + timer decimal(16,6))"); + } + if (!$ok) { + ADOConnection::outp( "

    LOGSQL Insert Failed: $isql
    $err2

    "); + $conn->_logsql = false; + } + } + $conn->_errorMsg = $errM; + $conn->_errorCode = $errN; + } + $conn->fnExecute = 'adodb_log_sql'; + return $rs; +} + + +/* +The settings data structure is an associative array that database parameter per element. + +Each database parameter element in the array is itself an array consisting of: + +0: category code, used to group related db parameters +1: either + a. sql string to retrieve value, eg. "select value from v\$parameter where name='db_block_size'", + b. array holding sql string and field to look for, e.g. array('show variables','table_cache'), + c. a string prefixed by =, then a PHP method of the class is invoked, + e.g. to invoke $this->GetIndexValue(), set this array element to '=GetIndexValue', +2: description of the database parameter +*/ + +class adodb_perf { + var $conn; + var $color = '#F0F0F0'; + var $table = ''; + var $titles = ''; + var $warnRatio = 90; + var $tablesSQL = false; + var $cliFormat = "%32s => %s \r\n"; + var $sql1 = 'sql1'; // used for casting sql1 to text for mssql + var $explain = true; + var $helpurl = "LogSQL help"; + var $createTableSQL = false; + var $maxLength = 2000; + + // Sets the tablename to be used + function table($newtable = false) + { + static $_table; + + if (!empty($newtable)) $_table = $newtable; + if (empty($_table)) $_table = 'adodb_logsql'; + return $_table; + } + + // returns array with info to calculate CPU Load + function _CPULoad() + { +/* + +cpu 524152 2662 2515228 336057010 +cpu0 264339 1408 1257951 168025827 +cpu1 259813 1254 1257277 168031181 +page 622307 25475680 +swap 24 1891 +intr 890153570 868093576 6 0 4 4 0 6 1 2 0 0 0 124 0 8098760 2 13961053 0 0 0 0 0 0 0 0 0 0 0 0 0 16 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +disk_io: (3,0):(3144904,54369,610378,3090535,50936192) (3,1):(3630212,54097,633016,3576115,50951320) +ctxt 66155838 +btime 1062315585 +processes 69293 + +*/ + // Algorithm is taken from + // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/example__obtaining_raw_performance_data.asp + if (strncmp(PHP_OS,'WIN',3)==0) { + if (PHP_VERSION == '5.0.0') return false; + if (PHP_VERSION == '5.0.1') return false; + if (PHP_VERSION == '5.0.2') return false; + if (PHP_VERSION == '5.0.3') return false; + if (PHP_VERSION == '4.3.10') return false; # see http://bugs.php.net/bug.php?id=31737 + + @$c = new COM("WinMgmts:{impersonationLevel=impersonate}!Win32_PerfRawData_PerfOS_Processor.Name='_Total'"); + if (!$c) return false; + + $info[0] = $c->PercentProcessorTime; + $info[1] = 0; + $info[2] = 0; + $info[3] = $c->TimeStamp_Sys100NS; + //print_r($info); + return $info; + } + + // Algorithm - Steve Blinch (BlitzAffe Online, http://www.blitzaffe.com) + $statfile = '/proc/stat'; + if (!file_exists($statfile)) return false; + + $fd = fopen($statfile,"r"); + if (!$fd) return false; + + $statinfo = explode("\n",fgets($fd, 1024)); + fclose($fd); + foreach($statinfo as $line) { + $info = explode(" ",$line); + if($info[0]=="cpu") { + array_shift($info); // pop off "cpu" + if(!$info[0]) array_shift($info); // pop off blank space (if any) + return $info; + } + } + + return false; + + } + + /* NOT IMPLEMENTED */ + function MemInfo() + { + /* + + total: used: free: shared: buffers: cached: +Mem: 1055289344 917299200 137990144 0 165437440 599773184 +Swap: 2146775040 11055104 2135719936 +MemTotal: 1030556 kB +MemFree: 134756 kB +MemShared: 0 kB +Buffers: 161560 kB +Cached: 581384 kB +SwapCached: 4332 kB +Active: 494468 kB +Inact_dirty: 322856 kB +Inact_clean: 24256 kB +Inact_target: 168316 kB +HighTotal: 131064 kB +HighFree: 1024 kB +LowTotal: 899492 kB +LowFree: 133732 kB +SwapTotal: 2096460 kB +SwapFree: 2085664 kB +Committed_AS: 348732 kB + */ + } + + + /* + Remember that this is client load, not db server load! + */ + var $_lastLoad; + function CPULoad() + { + $info = $this->_CPULoad(); + if (!$info) return false; + + if (empty($this->_lastLoad)) { + sleep(1); + $this->_lastLoad = $info; + $info = $this->_CPULoad(); + } + + $last = $this->_lastLoad; + $this->_lastLoad = $info; + + $d_user = $info[0] - $last[0]; + $d_nice = $info[1] - $last[1]; + $d_system = $info[2] - $last[2]; + $d_idle = $info[3] - $last[3]; + + //printf("Delta - User: %f Nice: %f System: %f Idle: %f
    ",$d_user,$d_nice,$d_system,$d_idle); + + if (strncmp(PHP_OS,'WIN',3)==0) { + if ($d_idle < 1) $d_idle = 1; + return 100*(1-$d_user/$d_idle); + }else { + $total=$d_user+$d_nice+$d_system+$d_idle; + if ($total<1) $total=1; + return 100*($d_user+$d_nice+$d_system)/$total; + } + } + + function Tracer($sql) + { + $perf_table = adodb_perf::table(); + $saveE = $this->conn->fnExecute; + $this->conn->fnExecute = false; + + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false); + + $sqlq = $this->conn->qstr($sql); + $arr = $this->conn->GetArray( +"select count(*),tracer + from $perf_table where sql1=$sqlq + group by tracer + order by 1 desc"); + $s = ''; + if ($arr) { + $s .= '

    Scripts Affected

    '; + foreach($arr as $k) { + $s .= sprintf("%4d",$k[0]).'   '.strip_tags($k[1]).'
    '; + } + } + + if (isset($savem)) $this->conn->SetFetchMode($savem); + $ADODB_CACHE_MODE = $save; + $this->conn->fnExecute = $saveE; + return $s; + } + + /* + Explain Plan for $sql. + If only a snippet of the $sql is passed in, then $partial will hold the crc32 of the + actual sql. + */ + function Explain($sql,$partial=false) + { + return false; + } + + function InvalidSQL($numsql = 10) + { + + if (isset($_GET['sql'])) return; + $s = '

    Invalid SQL

    '; + $saveE = $this->conn->fnExecute; + $this->conn->fnExecute = false; + $perf_table = adodb_perf::table(); + $rs =& $this->conn->SelectLimit("select distinct count(*),sql1,tracer as error_msg from $perf_table where tracer like 'ERROR:%' group by sql1,tracer order by 1 desc",$numsql);//,$numsql); + $this->conn->fnExecute = $saveE; + if ($rs) { + $s .= rs2html($rs,false,false,false,false); + } else + return "

    $this->helpurl. ".$this->conn->ErrorMsg()."

    "; + + return $s; + } + + + /* + This script identifies the longest running SQL + */ + function _SuspiciousSQL($numsql = 10) + { + global $ADODB_FETCH_MODE; + + $perf_table = adodb_perf::table(); + $saveE = $this->conn->fnExecute; + $this->conn->fnExecute = false; + + if (isset($_GET['exps']) && isset($_GET['sql'])) { + $partial = !empty($_GET['part']); + echo "".$this->Explain($_GET['sql'],$partial)."\n"; + } + + if (isset($_GET['sql'])) return; + $sql1 = $this->sql1; + + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false); + //$this->conn->debug=1; + $rs =& $this->conn->SelectLimit( + "select avg(timer) as avg_timer,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer + from $perf_table + where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT') + and (tracer is null or tracer not like 'ERROR:%') + group by sql1 + order by 1 desc",$numsql); + if (isset($savem)) $this->conn->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + $this->conn->fnExecute = $saveE; + + if (!$rs) return "

    $this->helpurl. ".$this->conn->ErrorMsg()."

    "; + $s = "

    Suspicious SQL

    +The following SQL have high average execution times
    +
    ParameterValueDescription
    \n"; + $max = $this->maxLength; + while (!$rs->EOF) { + $sql = $rs->fields[1]; + $raw = urlencode($sql); + if (strlen($raw)>$max-100) { + $sql2 = substr($sql,0,$max-500); + $raw = urlencode($sql2).'&part='.crc32($sql); + } + $prefix = ""; + $suffix = ""; + if ($this->explain == false || strlen($prefix)>$max) { + $suffix = ' ... String too long for GET parameter: '.strlen($prefix).''; + $prefix = ''; + } + $s .= ""; + $rs->MoveNext(); + } + return $s."
    Avg TimeCountSQLMaxMin
    ".adodb_round($rs->fields[0],6)."".$rs->fields[2]."".$prefix.htmlspecialchars($sql).$suffix."". + "".$rs->fields[3]."".$rs->fields[4]."
    "; + + } + + function CheckMemory() + { + return ''; + } + + + function SuspiciousSQL($numsql=10) + { + return adodb_perf::_SuspiciousSQL($numsql); + } + + function ExpensiveSQL($numsql=10) + { + return adodb_perf::_ExpensiveSQL($numsql); + } + + + /* + This reports the percentage of load on the instance due to the most + expensive few SQL statements. Tuning these statements can often + make huge improvements in overall system performance. + */ + function _ExpensiveSQL($numsql = 10) + { + global $ADODB_FETCH_MODE; + + $perf_table = adodb_perf::table(); + $saveE = $this->conn->fnExecute; + $this->conn->fnExecute = false; + + if (isset($_GET['expe']) && isset($_GET['sql'])) { + $partial = !empty($_GET['part']); + echo "".$this->Explain($_GET['sql'],$partial)."\n"; + } + + if (isset($_GET['sql'])) return; + + $sql1 = $this->sql1; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false); + + $rs =& $this->conn->SelectLimit( + "select sum(timer) as total,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer + from $perf_table + where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT') + and (tracer is null or tracer not like 'ERROR:%') + group by sql1 + having count(*)>1 + order by 1 desc",$numsql); + if (isset($savem)) $this->conn->SetFetchMode($savem); + $this->conn->fnExecute = $saveE; + $ADODB_FETCH_MODE = $save; + if (!$rs) return "

    $this->helpurl. ".$this->conn->ErrorMsg()."

    "; + $s = "

    Expensive SQL

    +Tuning the following SQL could reduce the server load substantially
    +\n"; + $max = $this->maxLength; + while (!$rs->EOF) { + $sql = $rs->fields[1]; + $raw = urlencode($sql); + if (strlen($raw)>$max-100) { + $sql2 = substr($sql,0,$max-500); + $raw = urlencode($sql2).'&part='.crc32($sql); + } + $prefix = ""; + $suffix = ""; + if($this->explain == false || strlen($prefix>$max)) { + $prefix = ''; + $suffix = ''; + } + $s .= ""; + $rs->MoveNext(); + } + return $s."
    LoadCountSQLMaxMin
    ".adodb_round($rs->fields[0],6)."".$rs->fields[2]."".$prefix.htmlspecialchars($sql).$suffix."". + "".$rs->fields[3]."".$rs->fields[4]."
    "; + } + + /* + Raw function to return parameter value from $settings. + */ + function DBParameter($param) + { + if (empty($this->settings[$param])) return false; + $sql = $this->settings[$param][1]; + return $this->_DBParameter($sql); + } + + /* + Raw function returning array of poll paramters + */ + function PollParameters() + { + $arr[0] = (float)$this->DBParameter('data cache hit ratio'); + $arr[1] = (float)$this->DBParameter('data reads'); + $arr[2] = (float)$this->DBParameter('data writes'); + $arr[3] = (integer) $this->DBParameter('current connections'); + return $arr; + } + + /* + Low-level Get Database Parameter + */ + function _DBParameter($sql) + { + $savelog = $this->conn->LogSQL(false); + if (is_array($sql)) { + global $ADODB_FETCH_MODE; + + $sql1 = $sql[0]; + $key = $sql[1]; + if (sizeof($sql)>2) $pos = $sql[2]; + else $pos = 1; + if (sizeof($sql)>3) $coef = $sql[3]; + else $coef = false; + $ret = false; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false); + + $rs = $this->conn->Execute($sql1); + + if (isset($savem)) $this->conn->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + if ($rs) { + while (!$rs->EOF) { + $keyf = reset($rs->fields); + if (trim($keyf) == $key) { + $ret = $rs->fields[$pos]; + if ($coef) $ret *= $coef; + break; + } + $rs->MoveNext(); + } + $rs->Close(); + } + $this->conn->LogSQL($savelog); + return $ret; + } else { + if (strncmp($sql,'=',1) == 0) { + $fn = substr($sql,1); + return $this->$fn(); + } + $sql = str_replace('$DATABASE',$this->conn->database,$sql); + $ret = $this->conn->GetOne($sql); + $this->conn->LogSQL($savelog); + + return $ret; + } + } + + /* + Warn if cache ratio falls below threshold. Displayed in "Description" column. + */ + function WarnCacheRatio($val) + { + if ($val < $this->warnRatio) + return 'Cache ratio should be at least '.$this->warnRatio.'%'; + else return ''; + } + + /***********************************************************************************************/ + // HIGH LEVEL UI FUNCTIONS + /***********************************************************************************************/ + + + function UI($pollsecs=5) + { + + $perf_table = adodb_perf::table(); + $conn = $this->conn; + + $app = $conn->host; + if ($conn->host && $conn->database) $app .= ', db='; + $app .= $conn->database; + + if ($app) $app .= ', '; + $savelog = $this->conn->LogSQL(false); + $info = $conn->ServerInfo(); + if (isset($_GET['clearsql'])) { + $this->conn->Execute("delete from $perf_table"); + } + $this->conn->LogSQL($savelog); + + // magic quotes + + if (isset($_GET['sql']) && get_magic_quotes_gpc()) { + $_GET['sql'] = $_GET['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$_GET['sql']); + } + + if (!isset($_SESSION['ADODB_PERF_SQL'])) $nsql = $_SESSION['ADODB_PERF_SQL'] = 10; + else $nsql = $_SESSION['ADODB_PERF_SQL']; + + $app .= $info['description']; + + + if (isset($_GET['do'])) $do = $_GET['do']; + else if (isset($_POST['do'])) $do = $_POST['do']; + else if (isset($_GET['sql'])) $do = 'viewsql'; + else $do = 'stats'; + + if (isset($_GET['nsql'])) { + if ($_GET['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $_GET['nsql']; + } + echo "ADOdb Performance Monitor on $app"; + if ($do == 'viewsql') $form = "
    # SQL:
    "; + else $form = " "; + + $allowsql = !defined('ADODB_PERF_NO_RUN_SQL'); + + if (empty($_GET['hidem'])) + echo "
    + ADOdb Performance Monitor for $app
    + Performance Stats   View SQL +   View Tables   Poll Stats", + $allowsql ? '   Run SQL' : '', + "$form", + "
    "; + + + switch ($do) { + default: + case 'stats': + echo $this->HealthCheck(); + //$this->conn->debug=1; + echo $this->CheckMemory(); + break; + case 'poll': + echo ""; + break; + case 'poll2': + echo "
    ";
    +			$this->Poll($pollsecs);
    +			break;
    +		
    +		case 'dosql':
    +			if (!$allowsql) break;
    +			
    +			$this->DoSQLForm();
    +			break;
    +		case 'viewsql':
    +			if (empty($_GET['hidem']))
    +				echo "  Clear SQL Log
    "; + echo($this->SuspiciousSQL($nsql)); + echo($this->ExpensiveSQL($nsql)); + echo($this->InvalidSQL($nsql)); + break; + case 'tables': + echo $this->Tables(); break; + } + global $ADODB_vers; + echo "

    $ADODB_vers Sponsored by phpLens
    "; + } + + /* + Runs in infinite loop, returning real-time statistics + */ + function Poll($secs=5) + { + $this->conn->fnExecute = false; + //$this->conn->debug=1; + if ($secs <= 1) $secs = 1; + echo "Accumulating statistics, every $secs seconds...\n";flush(); + $arro =& $this->PollParameters(); + $cnt = 0; + set_time_limit(0); + sleep($secs); + while (1) { + + $arr =& $this->PollParameters(); + + $hits = sprintf('%2.2f',$arr[0]); + $reads = sprintf('%12.4f',($arr[1]-$arro[1])/$secs); + $writes = sprintf('%12.4f',($arr[2]-$arro[2])/$secs); + $sess = sprintf('%5d',$arr[3]); + + $load = $this->CPULoad(); + if ($load !== false) { + $oslabel = 'WS-CPU%'; + $osval = sprintf(" %2.1f ",(float) $load); + }else { + $oslabel = ''; + $osval = ''; + } + if ($cnt % 10 == 0) echo " Time ".$oslabel." Hit% Sess Reads/s Writes/s\n"; + $cnt += 1; + echo date('H:i:s').' '.$osval."$hits $sess $reads $writes\n"; + flush(); + + if (connection_aborted()) return; + + sleep($secs); + $arro = $arr; + } + } + + /* + Returns basic health check in a command line interface + */ + function HealthCheckCLI() + { + return $this->HealthCheck(true); + } + + + /* + Returns basic health check as HTML + */ + function HealthCheck($cli=false) + { + $saveE = $this->conn->fnExecute; + $this->conn->fnExecute = false; + if ($cli) $html = ''; + else $html = $this->table.'

    '.$this->conn->databaseType.'

    '.$this->titles; + + $oldc = false; + $bgc = ''; + foreach($this->settings as $name => $arr) { + if ($arr === false) break; + + if (!is_string($name)) { + if ($cli) $html .= " -- $arr -- \n"; + else $html .= "color>$arr  "; + continue; + } + + if (!is_array($arr)) break; + $category = $arr[0]; + $how = $arr[1]; + if (sizeof($arr)>2) $desc = $arr[2]; + else $desc = '   '; + + + if ($category == 'HIDE') continue; + + $val = $this->_DBParameter($how); + + if ($desc && strncmp($desc,"=",1) === 0) { + $fn = substr($desc,1); + $desc = $this->$fn($val); + } + + if ($val === false) { + $m = $this->conn->ErrorMsg(); + $val = "Error: $m"; + } else { + if (is_numeric($val) && $val >= 256*1024) { + if ($val % (1024*1024) == 0) { + $val /= (1024*1024); + $val .= 'M'; + } else if ($val % 1024 == 0) { + $val /= 1024; + $val .= 'K'; + } + //$val = htmlspecialchars($val); + } + } + if ($category != $oldc) { + $oldc = $category; + //$bgc = ($bgc == ' bgcolor='.$this->color) ? ' bgcolor=white' : ' bgcolor='.$this->color; + } + if (strlen($desc)==0) $desc = ' '; + if (strlen($val)==0) $val = ' '; + if ($cli) { + $html .= str_replace(' ','',sprintf($this->cliFormat,strip_tags($name),strip_tags($val),strip_tags($desc))); + + }else { + $html .= "".$name.''.$val.''.$desc."\n"; + } + } + + if (!$cli) $html .= "\n"; + $this->conn->fnExecute = $saveE; + + return $html; + } + + function Tables($orderby='1') + { + if (!$this->tablesSQL) return false; + + $savelog = $this->conn->LogSQL(false); + $rs = $this->conn->Execute($this->tablesSQL.' order by '.$orderby); + $this->conn->LogSQL($savelog); + $html = rs2html($rs,false,false,false,false); + return $html; + } + + + function CreateLogTable() + { + if (!$this->createTableSQL) return false; + + $savelog = $this->conn->LogSQL(false); + $ok = $this->conn->Execute($this->createTableSQL); + $this->conn->LogSQL($savelog); + return ($ok) ? true : false; + } + + function DoSQLForm() + { + + + $PHP_SELF = $_SERVER['PHP_SELF']; + $sql = isset($_REQUEST['sql']) ? $_REQUEST['sql'] : ''; + + if (isset($_SESSION['phplens_sqlrows'])) $rows = $_SESSION['phplens_sqlrows']; + else $rows = 3; + + if (isset($_REQUEST['SMALLER'])) { + $rows /= 2; + if ($rows < 3) $rows = 3; + $_SESSION['phplens_sqlrows'] = $rows; + } + if (isset($_REQUEST['BIGGER'])) { + $rows *= 2; + $_SESSION['phplens_sqlrows'] = $rows; + } + +?> + +
    + + + + + + +
    Form size: + + +
    +
    +
    + +undomq(trim($sql)); + if (substr($sql,strlen($sql)-1) === ';') { + $print = true; + $sqla = $this->SplitSQL($sql); + } else { + $print = false; + $sqla = array($sql); + } + foreach($sqla as $sqls) { + + if (!$sqls) continue; + + if ($print) { + print "

    ".htmlspecialchars($sqls)."

    "; + flush(); + } + $savelog = $this->conn->LogSQL(false); + $rs = $this->conn->Execute($sqls); + $this->conn->LogSQL($savelog); + if ($rs && is_object($rs) && !$rs->EOF) { + rs2html($rs); + while ($rs->NextRecordSet()) { + print "
     
    "; + rs2html($rs); + } + } else { + $e1 = (integer) $this->conn->ErrorNo(); + $e2 = $this->conn->ErrorMsg(); + if (($e1) || ($e2)) { + if (empty($e1)) $e1 = '-1'; // postgresql fix + print '   '.$e1.': '.$e2; + } else { + print "

    No Recordset returned

    "; + } + } + } // foreach + } + + function SplitSQL($sql) + { + $arr = explode(';',$sql); + return $arr; + } + + function undomq($m) + { + if (get_magic_quotes_gpc()) { + // undo the damage + $m = str_replace('\\\\','\\',$m); + $m = str_replace('\"','"',$m); + $m = str_replace('\\\'','\'',$m); + } + return $m; +} + + + /************************************************************************/ + + /** + * Reorganise multiple table-indices/statistics/.. + * OptimizeMode could be given by last Parameter + * + * @example + *
    +     *          optimizeTables( 'tableA');
    +     *      
    + *
    +     *          optimizeTables( 'tableA', 'tableB', 'tableC');
    +     *      
    + *
    +     *          optimizeTables( 'tableA', 'tableB', ADODB_OPT_LOW);
    +     *      
    + * + * @param string table name of the table to optimize + * @param int mode optimization-mode + * ADODB_OPT_HIGH for full optimization + * ADODB_OPT_LOW for CPU-less optimization + * Default is LOW ADODB_OPT_LOW + * @author Markus Staab + * @return Returns true on success and false on error + */ + function OptimizeTables() + { + $args = func_get_args(); + $numArgs = func_num_args(); + + if ( $numArgs == 0) return false; + + $mode = ADODB_OPT_LOW; + $lastArg = $args[ $numArgs - 1]; + if ( !is_string($lastArg)) { + $mode = $lastArg; + unset( $args[ $numArgs - 1]); + } + + foreach( $args as $table) { + $this->optimizeTable( $table, $mode); + } + } + + /** + * Reorganise the table-indices/statistics/.. depending on the given mode. + * Default Implementation throws an error. + * + * @param string table name of the table to optimize + * @param int mode optimization-mode + * ADODB_OPT_HIGH for full optimization + * ADODB_OPT_LOW for CPU-less optimization + * Default is LOW ADODB_OPT_LOW + * @author Markus Staab + * @return Returns true on success and false on error + */ + function OptimizeTable( $table, $mode = ADODB_OPT_LOW) + { + ADOConnection::outp( sprintf( "

    %s: '%s' not implemented for driver '%s'

    ", __CLASS__, __FUNCTION__, $this->conn->databaseType)); + return false; + } + + /** + * Reorganise current database. + * Default implementation loops over all MetaTables() and + * optimize each using optmizeTable() + * + * @author Markus Staab + * @return Returns true on success and false on error + */ + function optimizeDatabase() + { + $conn = $this->conn; + if ( !$conn) return false; + + $tables = $conn->MetaTables( 'TABLES'); + if ( !$tables ) return false; + + foreach( $tables as $table) { + if ( !$this->optimizeTable( $table)) { + return false; + } + } + + return true; + } + // end hack +} + +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-php4.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-php4.inc.php new file mode 100644 index 0000000..76c00c6 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-php4.inc.php @@ -0,0 +1,16 @@ + \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-time.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-time.inc.php new file mode 100644 index 0000000..79e0dbc --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-time.inc.php @@ -0,0 +1,1312 @@ + 4 digit year conversion. The maximum is billions of years in the +future, but this is a theoretical limit as the computation of that year +would take too long with the current implementation of adodb_mktime(). + +This library replaces native functions as follows: + +
    	
    +	getdate()  with  adodb_getdate()
    +	date()     with  adodb_date() 
    +	gmdate()   with  adodb_gmdate()
    +	mktime()   with  adodb_mktime()
    +	gmmktime() with  adodb_gmmktime()
    +	strftime() with  adodb_strftime()
    +	strftime() with  adodb_gmstrftime()
    +
    + +The parameters are identical, except that adodb_date() accepts a subset +of date()'s field formats. Mktime() will convert from local time to GMT, +and date() will convert from GMT to local time, but daylight savings is +not handled currently. + +This library is independant of the rest of ADOdb, and can be used +as standalone code. + +PERFORMANCE + +For high speed, this library uses the native date functions where +possible, and only switches to PHP code when the dates fall outside +the 32-bit signed integer range. + +GREGORIAN CORRECTION + +Pope Gregory shortened October of A.D. 1582 by ten days. Thursday, +October 4, 1582 (Julian) was followed immediately by Friday, October 15, +1582 (Gregorian). + +Since 0.06, we handle this correctly, so: + +adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582) + == 24 * 3600 (1 day) + +============================================================================= + +COPYRIGHT + +(c) 2003-2005 John Lim and released under BSD-style license except for code by +jackbbs, which includes adodb_mktime, adodb_get_gmt_diff, adodb_is_leap_year +and originally found at http://www.php.net/manual/en/function.mktime.php + +============================================================================= + +BUG REPORTS + +These should be posted to the ADOdb forums at + + http://phplens.com/lens/lensforum/topics.php?id=4 + +============================================================================= + +FUNCTION DESCRIPTIONS + + +** FUNCTION adodb_getdate($date=false) + +Returns an array containing date information, as getdate(), but supports +dates greater than 1901 to 2038. The local date/time format is derived from a +heuristic the first time adodb_getdate is called. + + +** FUNCTION adodb_date($fmt, $timestamp = false) + +Convert a timestamp to a formatted local date. If $timestamp is not defined, the +current timestamp is used. Unlike the function date(), it supports dates +outside the 1901 to 2038 range. + +The format fields that adodb_date supports: + +
    +	a - "am" or "pm" 
    +	A - "AM" or "PM" 
    +	d - day of the month, 2 digits with leading zeros; i.e. "01" to "31" 
    +	D - day of the week, textual, 3 letters; e.g. "Fri" 
    +	F - month, textual, long; e.g. "January" 
    +	g - hour, 12-hour format without leading zeros; i.e. "1" to "12" 
    +	G - hour, 24-hour format without leading zeros; i.e. "0" to "23" 
    +	h - hour, 12-hour format; i.e. "01" to "12" 
    +	H - hour, 24-hour format; i.e. "00" to "23" 
    +	i - minutes; i.e. "00" to "59" 
    +	j - day of the month without leading zeros; i.e. "1" to "31" 
    +	l (lowercase 'L') - day of the week, textual, long; e.g. "Friday"  
    +	L - boolean for whether it is a leap year; i.e. "0" or "1" 
    +	m - month; i.e. "01" to "12" 
    +	M - month, textual, 3 letters; e.g. "Jan" 
    +	n - month without leading zeros; i.e. "1" to "12" 
    +	O - Difference to Greenwich time in hours; e.g. "+0200" 
    +	Q - Quarter, as in 1, 2, 3, 4 
    +	r - RFC 822 formatted date; e.g. "Thu, 21 Dec 2000 16:01:07 +0200" 
    +	s - seconds; i.e. "00" to "59" 
    +	S - English ordinal suffix for the day of the month, 2 characters; 
    +	   			i.e. "st", "nd", "rd" or "th" 
    +	t - number of days in the given month; i.e. "28" to "31"
    +	T - Timezone setting of this machine; e.g. "EST" or "MDT" 
    +	U - seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)  
    +	w - day of the week, numeric, i.e. "0" (Sunday) to "6" (Saturday) 
    +	Y - year, 4 digits; e.g. "1999" 
    +	y - year, 2 digits; e.g. "99" 
    +	z - day of the year; i.e. "0" to "365" 
    +	Z - timezone offset in seconds (i.e. "-43200" to "43200"). 
    +	   			The offset for timezones west of UTC is always negative, 
    +				and for those east of UTC is always positive. 
    +
    + +Unsupported: +
    +	B - Swatch Internet time 
    +	I (capital i) - "1" if Daylight Savings Time, "0" otherwise.
    +	W - ISO-8601 week number of year, weeks starting on Monday 
    +
    +
    + + +** FUNCTION adodb_date2($fmt, $isoDateString = false) +Same as adodb_date, but 2nd parameter accepts iso date, eg. + + adodb_date2('d-M-Y H:i','2003-12-25 13:01:34'); + + +** FUNCTION adodb_gmdate($fmt, $timestamp = false) + +Convert a timestamp to a formatted GMT date. If $timestamp is not defined, the +current timestamp is used. Unlike the function date(), it supports dates +outside the 1901 to 2038 range. + + +** FUNCTION adodb_mktime($hr, $min, $sec[, $month, $day, $year]) + +Converts a local date to a unix timestamp. Unlike the function mktime(), it supports +dates outside the 1901 to 2038 range. All parameters are optional. + + +** FUNCTION adodb_gmmktime($hr, $min, $sec [, $month, $day, $year]) + +Converts a gmt date to a unix timestamp. Unlike the function gmmktime(), it supports +dates outside the 1901 to 2038 range. Differs from gmmktime() in that all parameters +are currently compulsory. + +** FUNCTION adodb_gmstrftime($fmt, $timestamp = false) +Convert a timestamp to a formatted GMT date. + +** FUNCTION adodb_strftime($fmt, $timestamp = false) + +Convert a timestamp to a formatted local date. Internally converts $fmt into +adodb_date format, then echo result. + +For best results, you can define the local date format yourself. Define a global +variable $ADODB_DATE_LOCALE which is an array, 1st element is date format using +adodb_date syntax, and 2nd element is the time format, also in adodb_date syntax. + + eg. $ADODB_DATE_LOCALE = array('d/m/Y','H:i:s'); + + Supported format codes: + +
    +	%a - abbreviated weekday name according to the current locale 
    +	%A - full weekday name according to the current locale 
    +	%b - abbreviated month name according to the current locale 
    +	%B - full month name according to the current locale 
    +	%c - preferred date and time representation for the current locale 
    +	%d - day of the month as a decimal number (range 01 to 31) 
    +	%D - same as %m/%d/%y 
    +	%e - day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31') 
    +	%h - same as %b
    +	%H - hour as a decimal number using a 24-hour clock (range 00 to 23) 
    +	%I - hour as a decimal number using a 12-hour clock (range 01 to 12) 
    +	%m - month as a decimal number (range 01 to 12) 
    +	%M - minute as a decimal number 
    +	%n - newline character 
    +	%p - either `am' or `pm' according to the given time value, or the corresponding strings for the current locale 
    +	%r - time in a.m. and p.m. notation 
    +	%R - time in 24 hour notation 
    +	%S - second as a decimal number 
    +	%t - tab character 
    +	%T - current time, equal to %H:%M:%S 
    +	%x - preferred date representation for the current locale without the time 
    +	%X - preferred time representation for the current locale without the date 
    +	%y - year as a decimal number without a century (range 00 to 99) 
    +	%Y - year as a decimal number including the century 
    +	%Z - time zone or name or abbreviation 
    +	%% - a literal `%' character 
    +
    + + Unsupported codes: +
    +	%C - century number (the year divided by 100 and truncated to an integer, range 00 to 99) 
    +	%g - like %G, but without the century. 
    +	%G - The 4-digit year corresponding to the ISO week number (see %V). 
    +	     This has the same format and value as %Y, except that if the ISO week number belongs 
    +		 to the previous or next year, that year is used instead. 
    +	%j - day of the year as a decimal number (range 001 to 366) 
    +	%u - weekday as a decimal number [1,7], with 1 representing Monday 
    +	%U - week number of the current year as a decimal number, starting 
    +	    with the first Sunday as the first day of the first week 
    +	%V - The ISO 8601:1988 week number of the current year as a decimal number, 
    +	     range 01 to 53, where week 1 is the first week that has at least 4 days in the 
    +		 current year, and with Monday as the first day of the week. (Use %G or %g for 
    +		 the year component that corresponds to the week number for the specified timestamp.) 
    +	%w - day of the week as a decimal, Sunday being 0 
    +	%W - week number of the current year as a decimal number, starting with the 
    +	     first Monday as the first day of the first week 
    +
    + +============================================================================= + +NOTES + +Useful url for generating test timestamps: + http://www.4webhelp.net/us/timestamp.php + +Possible future optimizations include + +a. Using an algorithm similar to Plauger's in "The Standard C Library" +(page 428, xttotm.c _Ttotm() function). Plauger's algorithm will not +work outside 32-bit signed range, so i decided not to implement it. + +b. Implement daylight savings, which looks awfully complicated, see + http://webexhibits.org/daylightsaving/ + + +CHANGELOG +- 08 Sept 2005 0.22 +In adodb_date2(), $is_gmt not supported properly. Fixed. + +- 18 July 2005 0.21 +In PHP 4.3.11, the 'r' format has changed. Leading 0 in day is added. Changed for compat. +Added support for negative months in adodb_mktime(). + +- 24 Feb 2005 0.20 +Added limited strftime/gmstrftime support. x10 improvement in performance of adodb_date(). + +- 21 Dec 2004 0.17 +In adodb_getdate(), the timestamp was accidentally converted to gmt when $is_gmt is false. +Also adodb_mktime(0,0,0) did not work properly. Both fixed thx Mauro. + +- 17 Nov 2004 0.16 +Removed intval typecast in adodb_mktime() for secs, allowing: + adodb_mktime(0,0,0 + 2236672153,1,1,1934); +Suggested by Ryan. + +- 18 July 2004 0.15 +All params in adodb_mktime were formerly compulsory. Now only the hour, min, secs is compulsory. +This brings it more in line with mktime (still not identical). + +- 23 June 2004 0.14 + +Allow you to define your own daylights savings function, adodb_daylight_sv. +If the function is defined (somewhere in an include), then you can correct for daylights savings. + +In this example, we apply daylights savings in June or July, adding one hour. This is extremely +unrealistic as it does not take into account time-zone, geographic location, current year. + +function adodb_daylight_sv(&$arr, $is_gmt) +{ + if ($is_gmt) return; + $m = $arr['mon']; + if ($m == 6 || $m == 7) $arr['hours'] += 1; +} + +This is only called by adodb_date() and not by adodb_mktime(). + +The format of $arr is +Array ( + [seconds] => 0 + [minutes] => 0 + [hours] => 0 + [mday] => 1 # day of month, eg 1st day of the month + [mon] => 2 # month (eg. Feb) + [year] => 2102 + [yday] => 31 # days in current year + [leap] => # true if leap year + [ndays] => 28 # no of days in current month + ) + + +- 28 Apr 2004 0.13 +Fixed adodb_date to properly support $is_gmt. Thx to Dimitar Angelov. + +- 20 Mar 2004 0.12 +Fixed month calculation error in adodb_date. 2102-June-01 appeared as 2102-May-32. + +- 26 Oct 2003 0.11 +Because of daylight savings problems (some systems apply daylight savings to +January!!!), changed adodb_get_gmt_diff() to ignore daylight savings. + +- 9 Aug 2003 0.10 +Fixed bug with dates after 2038. +See http://phplens.com/lens/lensforum/msgs.php?id=6980 + +- 1 July 2003 0.09 +Added support for Q (Quarter). +Added adodb_date2(), which accepts ISO date in 2nd param + +- 3 March 2003 0.08 +Added support for 'S' adodb_date() format char. Added constant ADODB_ALLOW_NEGATIVE_TS +if you want PHP to handle negative timestamps between 1901 to 1969. + +- 27 Feb 2003 0.07 +All negative numbers handled by adodb now because of RH 7.3+ problems. +See http://bugs.php.net/bug.php?id=20048&edit=2 + +- 4 Feb 2003 0.06 +Fixed a typo, 1852 changed to 1582! This means that pre-1852 dates +are now correctly handled. + +- 29 Jan 2003 0.05 + +Leap year checking differs under Julian calendar (pre 1582). Also +leap year code optimized by checking for most common case first. + +We also handle month overflow correctly in mktime (eg month set to 13). + +Day overflow for less than one month's days is supported. + +- 28 Jan 2003 0.04 + +Gregorian correction handled. In PHP5, we might throw an error if +mktime uses invalid dates around 5-14 Oct 1582. Released with ADOdb 3.10. +Added limbo 5-14 Oct 1582 check, when we set to 15 Oct 1582. + +- 27 Jan 2003 0.03 + +Fixed some more month problems due to gmt issues. Added constant ADODB_DATE_VERSION. +Fixed calculation of days since start of year for <1970. + +- 27 Jan 2003 0.02 + +Changed _adodb_getdate() to inline leap year checking for better performance. +Fixed problem with time-zones west of GMT +0000. + +- 24 Jan 2003 0.01 + +First implementation. +*/ + + +/* Initialization */ + +/* + Version Number +*/ +define('ADODB_DATE_VERSION',0.22); + +/* + This code was originally for windows. But apparently this problem happens + also with Linux, RH 7.3 and later! + + glibc-2.2.5-34 and greater has been changed to return -1 for dates < + 1970. This used to work. The problem exists with RedHat 7.3 and 8.0 + echo (mktime(0, 0, 0, 1, 1, 1960)); // prints -1 + + References: + http://bugs.php.net/bug.php?id=20048&edit=2 + http://lists.debian.org/debian-glibc/2002/debian-glibc-200205/msg00010.html +*/ + +if (!defined('ADODB_ALLOW_NEGATIVE_TS')) define('ADODB_NO_NEGATIVE_TS',1); + +function adodb_date_test_date($y1,$m,$d=13) +{ + $t = adodb_mktime(0,0,0,$m,$d,$y1); + $rez = adodb_date('Y-n-j H:i:s',$t); + if ("$y1-$m-$d 00:00:00" != $rez) { + print "$y1 error, expected=$y1-$m-$d 00:00:00, adodb=$rez
    "; + return false; + } + return true; +} + +function adodb_date_test_strftime($fmt) +{ + $s1 = strftime($fmt); + $s2 = adodb_strftime($fmt); + + if ($s1 == $s2) return true; + + echo "error for $fmt, strftime=$s1, $adodb=$s2
    "; + return false; +} + +/** + Test Suite +*/ +function adodb_date_test() +{ + + error_reporting(E_ALL); + print "

    Testing adodb_date and adodb_mktime. version=".ADODB_DATE_VERSION.' PHP='.PHP_VERSION."

    "; + @set_time_limit(0); + $fail = false; + + // This flag disables calling of PHP native functions, so we can properly test the code + if (!defined('ADODB_TEST_DATES')) define('ADODB_TEST_DATES',1); + + adodb_date_test_strftime('%Y %m %x %X'); + adodb_date_test_strftime("%A %d %B %Y"); + adodb_date_test_strftime("%H %M S"); + + $t = adodb_mktime(0,0,0); + if (!(adodb_date('Y-m-d') == date('Y-m-d'))) print 'Error in '.adodb_mktime(0,0,0).'
    '; + + $t = adodb_mktime(0,0,0,6,1,2102); + if (!(adodb_date('Y-m-d',$t) == '2102-06-01')) print 'Error in '.adodb_date('Y-m-d',$t).'
    '; + + $t = adodb_mktime(0,0,0,2,1,2102); + if (!(adodb_date('Y-m-d',$t) == '2102-02-01')) print 'Error in '.adodb_date('Y-m-d',$t).'
    '; + + + print "

    Testing gregorian <=> julian conversion

    "; + $t = adodb_mktime(0,0,0,10,11,1492); + //http://www.holidayorigins.com/html/columbus_day.html - Friday check + if (!(adodb_date('D Y-m-d',$t) == 'Fri 1492-10-11')) print 'Error in Columbus landing
    '; + + $t = adodb_mktime(0,0,0,2,29,1500); + if (!(adodb_date('Y-m-d',$t) == '1500-02-29')) print 'Error in julian leap years
    '; + + $t = adodb_mktime(0,0,0,2,29,1700); + if (!(adodb_date('Y-m-d',$t) == '1700-03-01')) print 'Error in gregorian leap years
    '; + + print adodb_mktime(0,0,0,10,4,1582).' '; + print adodb_mktime(0,0,0,10,15,1582); + $diff = (adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582)); + if ($diff != 3600*24) print " Error in gregorian correction = ".($diff/3600/24)." days
    "; + + print " 15 Oct 1582, Fri=".(adodb_dow(1582,10,15) == 5 ? 'Fri' : 'Error')."
    "; + print " 4 Oct 1582, Thu=".(adodb_dow(1582,10,4) == 4 ? 'Thu' : 'Error')."
    "; + + print "

    Testing overflow

    "; + + $t = adodb_mktime(0,0,0,3,33,1965); + if (!(adodb_date('Y-m-d',$t) == '1965-04-02')) print 'Error in day overflow 1
    '; + $t = adodb_mktime(0,0,0,4,33,1971); + if (!(adodb_date('Y-m-d',$t) == '1971-05-03')) print 'Error in day overflow 2
    '; + $t = adodb_mktime(0,0,0,1,60,1965); + if (!(adodb_date('Y-m-d',$t) == '1965-03-01')) print 'Error in day overflow 3 '.adodb_date('Y-m-d',$t).'
    '; + $t = adodb_mktime(0,0,0,12,32,1965); + if (!(adodb_date('Y-m-d',$t) == '1966-01-01')) print 'Error in day overflow 4 '.adodb_date('Y-m-d',$t).'
    '; + $t = adodb_mktime(0,0,0,12,63,1965); + if (!(adodb_date('Y-m-d',$t) == '1966-02-01')) print 'Error in day overflow 5 '.adodb_date('Y-m-d',$t).'
    '; + $t = adodb_mktime(0,0,0,13,3,1965); + if (!(adodb_date('Y-m-d',$t) == '1966-01-03')) print 'Error in mth overflow 1
    '; + + print "Testing 2-digit => 4-digit year conversion

    "; + if (adodb_year_digit_check(00) != 2000) print "Err 2-digit 2000
    "; + if (adodb_year_digit_check(10) != 2010) print "Err 2-digit 2010
    "; + if (adodb_year_digit_check(20) != 2020) print "Err 2-digit 2020
    "; + if (adodb_year_digit_check(30) != 2030) print "Err 2-digit 2030
    "; + if (adodb_year_digit_check(40) != 1940) print "Err 2-digit 1940
    "; + if (adodb_year_digit_check(50) != 1950) print "Err 2-digit 1950
    "; + if (adodb_year_digit_check(90) != 1990) print "Err 2-digit 1990
    "; + + // Test string formating + print "

    Testing date formating

    "; + $fmt = '\d\a\t\e T Y-m-d H:i:s a A d D F g G h H i j l L m M n O \R\F\C822 r s t U w y Y z Z 2003'; + $s1 = date($fmt,0); + $s2 = adodb_date($fmt,0); + if ($s1 != $s2) { + print " date() 0 failed
    $s1
    $s2
    "; + } + flush(); + for ($i=100; --$i > 0; ) { + + $ts = 3600.0*((rand()%60000)+(rand()%60000))+(rand()%60000); + $s1 = date($fmt,$ts); + $s2 = adodb_date($fmt,$ts); + //print "$s1
    $s2

    "; + $pos = strcmp($s1,$s2); + + if (($s1) != ($s2)) { + for ($j=0,$k=strlen($s1); $j < $k; $j++) { + if ($s1[$j] != $s2[$j]) { + print substr($s1,$j).' '; + break; + } + } + print "Error date(): $ts

     
    +  \"$s1\" (date len=".strlen($s1).")
    +  \"$s2\" (adodb_date len=".strlen($s2).")

    "; + $fail = true; + } + + $a1 = getdate($ts); + $a2 = adodb_getdate($ts); + $rez = array_diff($a1,$a2); + if (sizeof($rez)>0) { + print "Error getdate() $ts
    "; + print_r($a1); + print "
    "; + print_r($a2); + print "

    "; + $fail = true; + } + } + + // Test generation of dates outside 1901-2038 + print "

    Testing random dates between 100 and 4000

    "; + adodb_date_test_date(100,1); + for ($i=100; --$i >= 0;) { + $y1 = 100+rand(0,1970-100); + $m = rand(1,12); + adodb_date_test_date($y1,$m); + + $y1 = 3000-rand(0,3000-1970); + adodb_date_test_date($y1,$m); + } + print '

    '; + $start = 1960+rand(0,10); + $yrs = 12; + $i = 365.25*86400*($start-1970); + $offset = 36000+rand(10000,60000); + $max = 365*$yrs*86400; + $lastyear = 0; + + // we generate a timestamp, convert it to a date, and convert it back to a timestamp + // and check if the roundtrip broke the original timestamp value. + print "Testing $start to ".($start+$yrs).", or $max seconds, offset=$offset: "; + $cnt = 0; + for ($max += $i; $i < $max; $i += $offset) { + $ret = adodb_date('m,d,Y,H,i,s',$i); + $arr = explode(',',$ret); + if ($lastyear != $arr[2]) { + $lastyear = $arr[2]; + print " $lastyear "; + flush(); + } + $newi = adodb_mktime($arr[3],$arr[4],$arr[5],$arr[0],$arr[1],$arr[2]); + if ($i != $newi) { + print "Error at $i, adodb_mktime returned $newi ($ret)"; + $fail = true; + break; + } + $cnt += 1; + } + echo "Tested $cnt dates
    "; + if (!$fail) print "

    Passed !

    "; + else print "

    Failed :-(

    "; +} + +/** + Returns day of week, 0 = Sunday,... 6=Saturday. + Algorithm from PEAR::Date_Calc +*/ +function adodb_dow($year, $month, $day) +{ +/* +Pope Gregory removed 10 days - October 5 to October 14 - from the year 1582 and +proclaimed that from that time onwards 3 days would be dropped from the calendar +every 400 years. + +Thursday, October 4, 1582 (Julian) was followed immediately by Friday, October 15, 1582 (Gregorian). +*/ + if ($year <= 1582) { + if ($year < 1582 || + ($year == 1582 && ($month < 10 || ($month == 10 && $day < 15)))) $greg_correction = 3; + else + $greg_correction = 0; + } else + $greg_correction = 0; + + if($month > 2) + $month -= 2; + else { + $month += 10; + $year--; + } + + $day = floor((13 * $month - 1) / 5) + + $day + ($year % 100) + + floor(($year % 100) / 4) + + floor(($year / 100) / 4) - 2 * + floor($year / 100) + 77 + $greg_correction; + + return $day - 7 * floor($day / 7); +} + + +/** + Checks for leap year, returns true if it is. No 2-digit year check. Also + handles julian calendar correctly. +*/ +function _adodb_is_leap_year($year) +{ + if ($year % 4 != 0) return false; + + if ($year % 400 == 0) { + return true; + // if gregorian calendar (>1582), century not-divisible by 400 is not leap + } else if ($year > 1582 && $year % 100 == 0 ) { + return false; + } + + return true; +} + + +/** + checks for leap year, returns true if it is. Has 2-digit year check +*/ +function adodb_is_leap_year($year) +{ + return _adodb_is_leap_year(adodb_year_digit_check($year)); +} + +/** + Fix 2-digit years. Works for any century. + Assumes that if 2-digit is more than 30 years in future, then previous century. +*/ +function adodb_year_digit_check($y) +{ + if ($y < 100) { + + $yr = (integer) date("Y"); + $century = (integer) ($yr /100); + + if ($yr%100 > 50) { + $c1 = $century + 1; + $c0 = $century; + } else { + $c1 = $century; + $c0 = $century - 1; + } + $c1 *= 100; + // if 2-digit year is less than 30 years in future, set it to this century + // otherwise if more than 30 years in future, then we set 2-digit year to the prev century. + if (($y + $c1) < $yr+30) $y = $y + $c1; + else $y = $y + $c0*100; + } + return $y; +} + +/** + get local time zone offset from GMT +*/ +function adodb_get_gmt_diff() +{ +static $TZ; + if (isset($TZ)) return $TZ; + + $TZ = mktime(0,0,0,1,2,1970,0) - gmmktime(0,0,0,1,2,1970,0); + return $TZ; +} + +/** + Returns an array with date info. +*/ +function adodb_getdate($d=false,$fast=false) +{ + if ($d === false) return getdate(); + if (!defined('ADODB_TEST_DATES')) { + if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range + if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) // if windows, must be +ve integer + return @getdate($d); + } + } + return _adodb_getdate($d); +} + +/* +// generate $YRS table for _adodb_getdate() +function adodb_date_gentable($out=true) +{ + + for ($i=1970; $i >= 1600; $i-=10) { + $s = adodb_gmmktime(0,0,0,1,1,$i); + echo "$i => $s,
    "; + } +} +adodb_date_gentable(); + +for ($i=1970; $i > 1500; $i--) { + +echo "
    $i "; + adodb_date_test_date($i,1,1); +} + +*/ + + +$_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31); +$_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31); + +function adodb_validdate($y,$m,$d) +{ +global $_month_table_normal,$_month_table_leaf; + + if (_adodb_is_leap_year($y)) $marr =& $_month_table_leaf; + else $marr =& $_month_table_normal; + + if ($m > 12 || $m < 1) return false; + + if ($d > 31 || $d < 1) return false; + + if ($marr[$m] < $d) return false; + + if ($y < 1000 && $y > 3000) return false; + + return true; +} + +/** + Low-level function that returns the getdate() array. We have a special + $fast flag, which if set to true, will return fewer array values, + and is much faster as it does not calculate dow, etc. +*/ +function _adodb_getdate($origd=false,$fast=false,$is_gmt=false) +{ +static $YRS; +global $_month_table_normal,$_month_table_leaf; + + $d = $origd - ($is_gmt ? 0 : adodb_get_gmt_diff()); + + $_day_power = 86400; + $_hour_power = 3600; + $_min_power = 60; + + if ($d < -12219321600) $d -= 86400*10; // if 15 Oct 1582 or earlier, gregorian correction + + $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31); + $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31); + + $d366 = $_day_power * 366; + $d365 = $_day_power * 365; + + if ($d < 0) { + + if (empty($YRS)) $YRS = array( + 1970 => 0, + 1960 => -315619200, + 1950 => -631152000, + 1940 => -946771200, + 1930 => -1262304000, + 1920 => -1577923200, + 1910 => -1893456000, + 1900 => -2208988800, + 1890 => -2524521600, + 1880 => -2840140800, + 1870 => -3155673600, + 1860 => -3471292800, + 1850 => -3786825600, + 1840 => -4102444800, + 1830 => -4417977600, + 1820 => -4733596800, + 1810 => -5049129600, + 1800 => -5364662400, + 1790 => -5680195200, + 1780 => -5995814400, + 1770 => -6311347200, + 1760 => -6626966400, + 1750 => -6942499200, + 1740 => -7258118400, + 1730 => -7573651200, + 1720 => -7889270400, + 1710 => -8204803200, + 1700 => -8520336000, + 1690 => -8835868800, + 1680 => -9151488000, + 1670 => -9467020800, + 1660 => -9782640000, + 1650 => -10098172800, + 1640 => -10413792000, + 1630 => -10729324800, + 1620 => -11044944000, + 1610 => -11360476800, + 1600 => -11676096000); + + if ($is_gmt) $origd = $d; + // The valid range of a 32bit signed timestamp is typically from + // Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT + // + + # old algorithm iterates through all years. new algorithm does it in + # 10 year blocks + + /* + # old algo + for ($a = 1970 ; --$a >= 0;) { + $lastd = $d; + + if ($leaf = _adodb_is_leap_year($a)) $d += $d366; + else $d += $d365; + + if ($d >= 0) { + $year = $a; + break; + } + } + */ + + $lastsecs = 0; + $lastyear = 1970; + foreach($YRS as $year => $secs) { + if ($d >= $secs) { + $a = $lastyear; + break; + } + $lastsecs = $secs; + $lastyear = $year; + } + + $d -= $lastsecs; + if (!isset($a)) $a = $lastyear; + + //echo ' yr=',$a,' ', $d,'.'; + + for (; --$a >= 0;) { + $lastd = $d; + + if ($leaf = _adodb_is_leap_year($a)) $d += $d366; + else $d += $d365; + + if ($d >= 0) { + $year = $a; + break; + } + } + /**/ + + $secsInYear = 86400 * ($leaf ? 366 : 365) + $lastd; + + $d = $lastd; + $mtab = ($leaf) ? $_month_table_leaf : $_month_table_normal; + for ($a = 13 ; --$a > 0;) { + $lastd = $d; + $d += $mtab[$a] * $_day_power; + if ($d >= 0) { + $month = $a; + $ndays = $mtab[$a]; + break; + } + } + + $d = $lastd; + $day = $ndays + ceil(($d+1) / ($_day_power)); + + $d += ($ndays - $day+1)* $_day_power; + $hour = floor($d/$_hour_power); + + } else { + for ($a = 1970 ;; $a++) { + $lastd = $d; + + if ($leaf = _adodb_is_leap_year($a)) $d -= $d366; + else $d -= $d365; + if ($d < 0) { + $year = $a; + break; + } + } + $secsInYear = $lastd; + $d = $lastd; + $mtab = ($leaf) ? $_month_table_leaf : $_month_table_normal; + for ($a = 1 ; $a <= 12; $a++) { + $lastd = $d; + $d -= $mtab[$a] * $_day_power; + if ($d < 0) { + $month = $a; + $ndays = $mtab[$a]; + break; + } + } + $d = $lastd; + $day = ceil(($d+1) / $_day_power); + $d = $d - ($day-1) * $_day_power; + $hour = floor($d /$_hour_power); + } + + $d -= $hour * $_hour_power; + $min = floor($d/$_min_power); + $secs = $d - $min * $_min_power; + if ($fast) { + return array( + 'seconds' => $secs, + 'minutes' => $min, + 'hours' => $hour, + 'mday' => $day, + 'mon' => $month, + 'year' => $year, + 'yday' => floor($secsInYear/$_day_power), + 'leap' => $leaf, + 'ndays' => $ndays + ); + } + + + $dow = adodb_dow($year,$month,$day); + + return array( + 'seconds' => $secs, + 'minutes' => $min, + 'hours' => $hour, + 'mday' => $day, + 'wday' => $dow, + 'mon' => $month, + 'year' => $year, + 'yday' => floor($secsInYear/$_day_power), + 'weekday' => gmdate('l',$_day_power*(3+$dow)), + 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)), + 0 => $origd + ); +} + +function adodb_gmdate($fmt,$d=false) +{ + return adodb_date($fmt,$d,true); +} + +// accepts unix timestamp and iso date format in $d +function adodb_date2($fmt, $d=false, $is_gmt=false) +{ + if ($d !== false) { + if (!preg_match( + "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ -]?(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", + ($d), $rr)) return adodb_date($fmt,false,$is_gmt); + + if ($rr[1] <= 100 && $rr[2]<= 1) return adodb_date($fmt,false,$is_gmt); + + // h-m-s-MM-DD-YY + if (!isset($rr[5])) $d = adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1],false,$is_gmt); + else $d = @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1],false,$is_gmt); + } + + return adodb_date($fmt,$d,$is_gmt); +} + + +/** + Return formatted date based on timestamp $d +*/ +function adodb_date($fmt,$d=false,$is_gmt=false) +{ +static $daylight; + + if ($d === false) return ($is_gmt)? @gmdate($fmt): @date($fmt); + if (!defined('ADODB_TEST_DATES')) { + if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range + if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) // if windows, must be +ve integer + return ($is_gmt)? @gmdate($fmt,$d): @date($fmt,$d); + + } + } + $_day_power = 86400; + + $arr = _adodb_getdate($d,true,$is_gmt); + + if (!isset($daylight)) $daylight = function_exists('adodb_daylight_sv'); + if ($daylight) adodb_daylight_sv($arr, $is_gmt); + + $year = $arr['year']; + $month = $arr['mon']; + $day = $arr['mday']; + $hour = $arr['hours']; + $min = $arr['minutes']; + $secs = $arr['seconds']; + + $max = strlen($fmt); + $dates = ''; + + /* + at this point, we have the following integer vars to manipulate: + $year, $month, $day, $hour, $min, $secs + */ + for ($i=0; $i < $max; $i++) { + switch($fmt[$i]) { + case 'T': $dates .= date('T');break; + // YEAR + case 'L': $dates .= $arr['leap'] ? '1' : '0'; break; + case 'r': // Thu, 21 Dec 2000 16:01:07 +0200 + + // 4.3.11 uses '04 Jun 2004' + // 4.3.8 uses ' 4 Jun 2004' + $dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))).', ' + . ($day<10?'0'.$day:$day) . ' '.date('M',mktime(0,0,0,$month,2,1971)).' '.$year.' '; + + if ($hour < 10) $dates .= '0'.$hour; else $dates .= $hour; + + if ($min < 10) $dates .= ':0'.$min; else $dates .= ':'.$min; + + if ($secs < 10) $dates .= ':0'.$secs; else $dates .= ':'.$secs; + + $gmt = adodb_get_gmt_diff(); + $dates .= sprintf(' %s%04d',($gmt<0)?'+':'-',abs($gmt)/36); break; + + case 'Y': $dates .= $year; break; + case 'y': $dates .= substr($year,strlen($year)-2,2); break; + // MONTH + case 'm': if ($month<10) $dates .= '0'.$month; else $dates .= $month; break; + case 'Q': $dates .= ($month+3)>>2; break; + case 'n': $dates .= $month; break; + case 'M': $dates .= date('M',mktime(0,0,0,$month,2,1971)); break; + case 'F': $dates .= date('F',mktime(0,0,0,$month,2,1971)); break; + // DAY + case 't': $dates .= $arr['ndays']; break; + case 'z': $dates .= $arr['yday']; break; + case 'w': $dates .= adodb_dow($year,$month,$day); break; + case 'l': $dates .= gmdate('l',$_day_power*(3+adodb_dow($year,$month,$day))); break; + case 'D': $dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))); break; + case 'j': $dates .= $day; break; + case 'd': if ($day<10) $dates .= '0'.$day; else $dates .= $day; break; + case 'S': + $d10 = $day % 10; + if ($d10 == 1) $dates .= 'st'; + else if ($d10 == 2 && $day != 12) $dates .= 'nd'; + else if ($d10 == 3) $dates .= 'rd'; + else $dates .= 'th'; + break; + + // HOUR + case 'Z': + $dates .= ($is_gmt) ? 0 : -adodb_get_gmt_diff(); break; + case 'O': + $gmt = ($is_gmt) ? 0 : adodb_get_gmt_diff(); + $dates .= sprintf('%s%04d',($gmt<0)?'+':'-',abs($gmt)/36); break; + + case 'H': + if ($hour < 10) $dates .= '0'.$hour; + else $dates .= $hour; + break; + case 'h': + if ($hour > 12) $hh = $hour - 12; + else { + if ($hour == 0) $hh = '12'; + else $hh = $hour; + } + + if ($hh < 10) $dates .= '0'.$hh; + else $dates .= $hh; + break; + + case 'G': + $dates .= $hour; + break; + + case 'g': + if ($hour > 12) $hh = $hour - 12; + else { + if ($hour == 0) $hh = '12'; + else $hh = $hour; + } + $dates .= $hh; + break; + // MINUTES + case 'i': if ($min < 10) $dates .= '0'.$min; else $dates .= $min; break; + // SECONDS + case 'U': $dates .= $d; break; + case 's': if ($secs < 10) $dates .= '0'.$secs; else $dates .= $secs; break; + // AM/PM + // Note 00:00 to 11:59 is AM, while 12:00 to 23:59 is PM + case 'a': + if ($hour>=12) $dates .= 'pm'; + else $dates .= 'am'; + break; + case 'A': + if ($hour>=12) $dates .= 'PM'; + else $dates .= 'AM'; + break; + default: + $dates .= $fmt[$i]; break; + // ESCAPE + case "\\": + $i++; + if ($i < $max) $dates .= $fmt[$i]; + break; + } + } + return $dates; +} + +/** + Returns a timestamp given a GMT/UTC time. + Note that $is_dst is not implemented and is ignored. +*/ +function adodb_gmmktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=false) +{ + return adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst,true); +} + +/** + Return a timestamp given a local time. Originally by jackbbs. + Note that $is_dst is not implemented and is ignored. + + Not a very fast algorithm - O(n) operation. Could be optimized to O(1). +*/ +function adodb_mktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=false,$is_gmt=false) +{ + if (!defined('ADODB_TEST_DATES')) { + + if ($mon === false) { + return $is_gmt? @gmmktime($hr,$min,$sec): @mktime($hr,$min,$sec); + } + + // for windows, we don't check 1970 because with timezone differences, + // 1 Jan 1970 could generate negative timestamp, which is illegal + if (1971 < $year && $year < 2038 + || !defined('ADODB_NO_NEGATIVE_TS') && (1901 < $year && $year < 2038) + ) { + return $is_gmt ? + @gmmktime($hr,$min,$sec,$mon,$day,$year): + @mktime($hr,$min,$sec,$mon,$day,$year); + } + } + + $gmt_different = ($is_gmt) ? 0 : adodb_get_gmt_diff(); + + /* + # disabled because some people place large values in $sec. + # however we need it for $mon because we use an array... + $hr = intval($hr); + $min = intval($min); + $sec = intval($sec); + */ + $mon = intval($mon); + $day = intval($day); + $year = intval($year); + + + $year = adodb_year_digit_check($year); + + if ($mon > 12) { + $y = floor($mon / 12); + $year += $y; + $mon -= $y*12; + } else if ($mon < 1) { + $y = ceil((1-$mon) / 12); + $year -= $y; + $mon += $y*12; + } + + $_day_power = 86400; + $_hour_power = 3600; + $_min_power = 60; + + $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31); + $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31); + + $_total_date = 0; + if ($year >= 1970) { + for ($a = 1970 ; $a <= $year; $a++) { + $leaf = _adodb_is_leap_year($a); + if ($leaf == true) { + $loop_table = $_month_table_leaf; + $_add_date = 366; + } else { + $loop_table = $_month_table_normal; + $_add_date = 365; + } + if ($a < $year) { + $_total_date += $_add_date; + } else { + for($b=1;$b<$mon;$b++) { + $_total_date += $loop_table[$b]; + } + } + } + $_total_date +=$day-1; + $ret = $_total_date * $_day_power + $hr * $_hour_power + $min * $_min_power + $sec + $gmt_different; + + } else { + for ($a = 1969 ; $a >= $year; $a--) { + $leaf = _adodb_is_leap_year($a); + if ($leaf == true) { + $loop_table = $_month_table_leaf; + $_add_date = 366; + } else { + $loop_table = $_month_table_normal; + $_add_date = 365; + } + if ($a > $year) { $_total_date += $_add_date; + } else { + for($b=12;$b>$mon;$b--) { + $_total_date += $loop_table[$b]; + } + } + } + $_total_date += $loop_table[$mon] - $day; + + $_day_time = $hr * $_hour_power + $min * $_min_power + $sec; + $_day_time = $_day_power - $_day_time; + $ret = -( $_total_date * $_day_power + $_day_time - $gmt_different); + if ($ret < -12220185600) $ret += 10*86400; // if earlier than 5 Oct 1582 - gregorian correction + else if ($ret < -12219321600) $ret = -12219321600; // if in limbo, reset to 15 Oct 1582. + } + //print " dmy=$day/$mon/$year $hr:$min:$sec => " .$ret; + return $ret; +} + +function adodb_gmstrftime($fmt, $ts=false) +{ + return adodb_strftime($fmt,$ts,true); +} + +// hack - convert to adodb_date +function adodb_strftime($fmt, $ts=false,$is_gmt=false) +{ +global $ADODB_DATE_LOCALE; + + if (!defined('ADODB_TEST_DATES')) { + if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range + if (!defined('ADODB_NO_NEGATIVE_TS') || $ts >= 0) // if windows, must be +ve integer + return ($is_gmt)? @gmstrftime($fmt,$ts): @strftime($fmt,$ts); + + } + } + + if (empty($ADODB_DATE_LOCALE)) { + $tstr = strtoupper(gmstrftime('%c',31366800)); // 30 Dec 1970, 1 am + $sep = substr($tstr,2,1); + $hasAM = strrpos($tstr,'M') !== false; + + $ADODB_DATE_LOCALE = array(); + $ADODB_DATE_LOCALE[] = strncmp($tstr,'30',2) == 0 ? 'd'.$sep.'m'.$sep.'y' : 'm'.$sep.'d'.$sep.'y'; + $ADODB_DATE_LOCALE[] = ($hasAM) ? 'h:i:s a' : 'H:i:s'; + + } + $inpct = false; + $fmtdate = ''; + for ($i=0,$max = strlen($fmt); $i < $max; $i++) { + $ch = $fmt[$i]; + if ($ch == '%') { + if ($inpct) { + $fmtdate .= '%'; + $inpct = false; + } else + $inpct = true; + } else if ($inpct) { + + $inpct = false; + switch($ch) { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case 'E': + case 'O': + /* ignore format modifiers */ + $inpct = true; + break; + + case 'a': $fmtdate .= 'D'; break; + case 'A': $fmtdate .= 'l'; break; + case 'h': + case 'b': $fmtdate .= 'M'; break; + case 'B': $fmtdate .= 'F'; break; + case 'c': $fmtdate .= $ADODB_DATE_LOCALE[0].$ADODB_DATE_LOCALE[1]; break; + case 'C': $fmtdate .= '\C?'; break; // century + case 'd': $fmtdate .= 'd'; break; + case 'D': $fmtdate .= 'm/d/y'; break; + case 'e': $fmtdate .= 'j'; break; + case 'g': $fmtdate .= '\g?'; break; //? + case 'G': $fmtdate .= '\G?'; break; //? + case 'H': $fmtdate .= 'H'; break; + case 'I': $fmtdate .= 'h'; break; + case 'j': $fmtdate .= '?z'; $parsej = true; break; // wrong as j=1-based, z=0-basd + case 'm': $fmtdate .= 'm'; break; + case 'M': $fmtdate .= 'i'; break; + case 'n': $fmtdate .= "\n"; break; + case 'p': $fmtdate .= 'a'; break; + case 'r': $fmtdate .= 'h:i:s a'; break; + case 'R': $fmtdate .= 'H:i:s'; break; + case 'S': $fmtdate .= 's'; break; + case 't': $fmtdate .= "\t"; break; + case 'T': $fmtdate .= 'H:i:s'; break; + case 'u': $fmtdate .= '?u'; $parseu = true; break; // wrong strftime=1-based, date=0-based + case 'U': $fmtdate .= '?U'; $parseU = true; break;// wrong strftime=1-based, date=0-based + case 'x': $fmtdate .= $ADODB_DATE_LOCALE[0]; break; + case 'X': $fmtdate .= $ADODB_DATE_LOCALE[1]; break; + case 'w': $fmtdate .= '?w'; $parseu = true; break; // wrong strftime=1-based, date=0-based + case 'W': $fmtdate .= '?W'; $parseU = true; break;// wrong strftime=1-based, date=0-based + case 'y': $fmtdate .= 'y'; break; + case 'Y': $fmtdate .= 'Y'; break; + case 'Z': $fmtdate .= 'T'; break; + } + } else if (('A' <= ($ch) && ($ch) <= 'Z' ) || ('a' <= ($ch) && ($ch) <= 'z' )) + $fmtdate .= "\\".$ch; + else + $fmtdate .= $ch; + } + //echo "fmt=",$fmtdate,"
    "; + if ($ts === false) $ts = time(); + $ret = adodb_date($fmtdate, $ts, $is_gmt); + return $ret; +} + + +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-xmlschema.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-xmlschema.inc.php new file mode 100644 index 0000000..b78ad51 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb-xmlschema.inc.php @@ -0,0 +1,2221 @@ +parent =& $parent; + } + + /** + * XML Callback to process start elements + * + * @access private + */ + function _tag_open( &$parser, $tag, $attributes ) { + + } + + /** + * XML Callback to process CDATA elements + * + * @access private + */ + function _tag_cdata( &$parser, $cdata ) { + + } + + /** + * XML Callback to process end elements + * + * @access private + */ + function _tag_close( &$parser, $tag ) { + + } + + function create() { + return array(); + } + + /** + * Destroys the object + */ + function destroy() { + unset( $this ); + } + + /** + * Checks whether the specified RDBMS is supported by the current + * database object or its ranking ancestor. + * + * @param string $platform RDBMS platform name (from ADODB platform list). + * @return boolean TRUE if RDBMS is supported; otherwise returns FALSE. + */ + function supportedPlatform( $platform = NULL ) { + return is_object( $this->parent ) ? $this->parent->supportedPlatform( $platform ) : TRUE; + } + + /** + * Returns the prefix set by the ranking ancestor of the database object. + * + * @param string $name Prefix string. + * @return string Prefix. + */ + function prefix( $name = '' ) { + return is_object( $this->parent ) ? $this->parent->prefix( $name ) : $name; + } + + /** + * Extracts a field ID from the specified field. + * + * @param string $field Field. + * @return string Field ID. + */ + function FieldID( $field ) { + return strtoupper( preg_replace( '/^`(.+)`$/', '$1', $field ) ); + } +} + +/** +* Creates a table object in ADOdb's datadict format +* +* This class stores information about a database table. As charactaristics +* of the table are loaded from the external source, methods and properties +* of this class are used to build up the table description in ADOdb's +* datadict format. +* +* @package axmls +* @access private +*/ +class dbTable extends dbObject { + + /** + * @var string Table name + */ + var $name; + + /** + * @var array Field specifier: Meta-information about each field + */ + var $fields = array(); + + /** + * @var array List of table indexes. + */ + var $indexes = array(); + + /** + * @var array Table options: Table-level options + */ + var $opts = array(); + + /** + * @var string Field index: Keeps track of which field is currently being processed + */ + var $current_field; + + /** + * @var boolean Mark table for destruction + * @access private + */ + var $drop_table; + + /** + * @var boolean Mark field for destruction (not yet implemented) + * @access private + */ + var $drop_field = array(); + + /** + * Iniitializes a new table object. + * + * @param string $prefix DB Object prefix + * @param array $attributes Array of table attributes. + */ + function dbTable( &$parent, $attributes = NULL ) { + $this->parent =& $parent; + $this->name = $this->prefix($attributes['NAME']); + } + + /** + * XML Callback to process start elements. Elements currently + * processed are: INDEX, DROP, FIELD, KEY, NOTNULL, AUTOINCREMENT & DEFAULT. + * + * @access private + */ + function _tag_open( &$parser, $tag, $attributes ) { + $this->currentElement = strtoupper( $tag ); + + switch( $this->currentElement ) { + case 'INDEX': + if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) { + xml_set_object( $parser, $this->addIndex( $attributes ) ); + } + break; + case 'DATA': + if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) { + xml_set_object( $parser, $this->addData( $attributes ) ); + } + break; + case 'DROP': + $this->drop(); + break; + case 'FIELD': + // Add a field + $fieldName = $attributes['NAME']; + $fieldType = $attributes['TYPE']; + $fieldSize = isset( $attributes['SIZE'] ) ? $attributes['SIZE'] : NULL; + $fieldOpts = isset( $attributes['OPTS'] ) ? $attributes['OPTS'] : NULL; + + $this->addField( $fieldName, $fieldType, $fieldSize, $fieldOpts ); + break; + case 'KEY': + case 'NOTNULL': + case 'AUTOINCREMENT': + // Add a field option + $this->addFieldOpt( $this->current_field, $this->currentElement ); + break; + case 'DEFAULT': + // Add a field option to the table object + + // Work around ADOdb datadict issue that misinterprets empty strings. + if( $attributes['VALUE'] == '' ) { + $attributes['VALUE'] = " '' "; + } + + $this->addFieldOpt( $this->current_field, $this->currentElement, $attributes['VALUE'] ); + break; + case 'DEFDATE': + case 'DEFTIMESTAMP': + // Add a field option to the table object + $this->addFieldOpt( $this->current_field, $this->currentElement ); + break; + default: + // print_r( array( $tag, $attributes ) ); + } + } + + /** + * XML Callback to process CDATA elements + * + * @access private + */ + function _tag_cdata( &$parser, $cdata ) { + switch( $this->currentElement ) { + // Table constraint + case 'CONSTRAINT': + if( isset( $this->current_field ) ) { + $this->addFieldOpt( $this->current_field, $this->currentElement, $cdata ); + } else { + $this->addTableOpt( $cdata ); + } + break; + // Table option + case 'OPT': + $this->addTableOpt( $cdata ); + break; + default: + + } + } + + /** + * XML Callback to process end elements + * + * @access private + */ + function _tag_close( &$parser, $tag ) { + $this->currentElement = ''; + + switch( strtoupper( $tag ) ) { + case 'TABLE': + $this->parent->addSQL( $this->create( $this->parent ) ); + xml_set_object( $parser, $this->parent ); + $this->destroy(); + break; + case 'FIELD': + unset($this->current_field); + break; + + } + } + + /** + * Adds an index to a table object + * + * @param array $attributes Index attributes + * @return object dbIndex object + */ + function addIndex( $attributes ) { + $name = strtoupper( $attributes['NAME'] ); + $this->indexes[$name] = new dbIndex( $this, $attributes ); + return $this->indexes[$name]; + } + + /** + * Adds data to a table object + * + * @param array $attributes Data attributes + * @return object dbData object + */ + function addData( $attributes ) { + if( !isset( $this->data ) ) { + $this->data = new dbData( $this, $attributes ); + } + return $this->data; + } + + /** + * Adds a field to a table object + * + * $name is the name of the table to which the field should be added. + * $type is an ADODB datadict field type. The following field types + * are supported as of ADODB 3.40: + * - C: varchar + * - X: CLOB (character large object) or largest varchar size + * if CLOB is not supported + * - C2: Multibyte varchar + * - X2: Multibyte CLOB + * - B: BLOB (binary large object) + * - D: Date (some databases do not support this, and we return a datetime type) + * - T: Datetime or Timestamp + * - L: Integer field suitable for storing booleans (0 or 1) + * - I: Integer (mapped to I4) + * - I1: 1-byte integer + * - I2: 2-byte integer + * - I4: 4-byte integer + * - I8: 8-byte integer + * - F: Floating point number + * - N: Numeric or decimal number + * + * @param string $name Name of the table to which the field will be added. + * @param string $type ADODB datadict field type. + * @param string $size Field size + * @param array $opts Field options array + * @return array Field specifier array + */ + function addField( $name, $type, $size = NULL, $opts = NULL ) { + $field_id = $this->FieldID( $name ); + + // Set the field index so we know where we are + $this->current_field = $field_id; + + // Set the field name (required) + $this->fields[$field_id]['NAME'] = $name; + + // Set the field type (required) + $this->fields[$field_id]['TYPE'] = $type; + + // Set the field size (optional) + if( isset( $size ) ) { + $this->fields[$field_id]['SIZE'] = $size; + } + + // Set the field options + if( isset( $opts ) ) { + $this->fields[$field_id]['OPTS'][] = $opts; + } + } + + /** + * Adds a field option to the current field specifier + * + * This method adds a field option allowed by the ADOdb datadict + * and appends it to the given field. + * + * @param string $field Field name + * @param string $opt ADOdb field option + * @param mixed $value Field option value + * @return array Field specifier array + */ + function addFieldOpt( $field, $opt, $value = NULL ) { + if( !isset( $value ) ) { + $this->fields[$this->FieldID( $field )]['OPTS'][] = $opt; + // Add the option and value + } else { + $this->fields[$this->FieldID( $field )]['OPTS'][] = array( $opt => $value ); + } + } + + /** + * Adds an option to the table + * + * This method takes a comma-separated list of table-level options + * and appends them to the table object. + * + * @param string $opt Table option + * @return array Options + */ + function addTableOpt( $opt ) { + $this->opts[] = $opt; + + return $this->opts; + } + + /** + * Generates the SQL that will create the table in the database + * + * @param object $xmls adoSchema object + * @return array Array containing table creation SQL + */ + function create( &$xmls ) { + $sql = array(); + + // drop any existing indexes + if( is_array( $legacy_indexes = $xmls->dict->MetaIndexes( $this->name ) ) ) { + foreach( $legacy_indexes as $index => $index_details ) { + $sql[] = $xmls->dict->DropIndexSQL( $index, $this->name ); + } + } + + // remove fields to be dropped from table object + foreach( $this->drop_field as $field ) { + unset( $this->fields[$field] ); + } + + // if table exists + if( is_array( $legacy_fields = $xmls->dict->MetaColumns( $this->name ) ) ) { + // drop table + if( $this->drop_table ) { + $sql[] = $xmls->dict->DropTableSQL( $this->name ); + + return $sql; + } + + // drop any existing fields not in schema + foreach( $legacy_fields as $field_id => $field ) { + if( !isset( $this->fields[$field_id] ) ) { + $sql[] = $xmls->dict->DropColumnSQL( $this->name, '`'.$field->name.'`' ); + } + } + // if table doesn't exist + } else { + if( $this->drop_table ) { + return $sql; + } + + $legacy_fields = array(); + } + + // Loop through the field specifier array, building the associative array for the field options + $fldarray = array(); + + foreach( $this->fields as $field_id => $finfo ) { + // Set an empty size if it isn't supplied + if( !isset( $finfo['SIZE'] ) ) { + $finfo['SIZE'] = ''; + } + + // Initialize the field array with the type and size + $fldarray[$field_id] = array( + 'NAME' => $finfo['NAME'], + 'TYPE' => $finfo['TYPE'], + 'SIZE' => $finfo['SIZE'] + ); + + // Loop through the options array and add the field options. + if( isset( $finfo['OPTS'] ) ) { + foreach( $finfo['OPTS'] as $opt ) { + // Option has an argument. + if( is_array( $opt ) ) { + $key = key( $opt ); + $value = $opt[key( $opt )]; + @$fldarray[$field_id][$key] .= $value; + // Option doesn't have arguments + } else { + $fldarray[$field_id][$opt] = $opt; + } + } + } + } + + if( empty( $legacy_fields ) ) { + // Create the new table + $sql[] = $xmls->dict->CreateTableSQL( $this->name, $fldarray, $this->opts ); + logMsg( end( $sql ), 'Generated CreateTableSQL' ); + } else { + // Upgrade an existing table + logMsg( "Upgrading {$this->name} using '{$xmls->upgrade}'" ); + switch( $xmls->upgrade ) { + // Use ChangeTableSQL + case 'ALTER': + logMsg( 'Generated ChangeTableSQL (ALTERing table)' ); + $sql[] = $xmls->dict->ChangeTableSQL( $this->name, $fldarray, $this->opts ); + break; + case 'REPLACE': + logMsg( 'Doing upgrade REPLACE (testing)' ); + $sql[] = $xmls->dict->DropTableSQL( $this->name ); + $sql[] = $xmls->dict->CreateTableSQL( $this->name, $fldarray, $this->opts ); + break; + // ignore table + default: + return array(); + } + } + + foreach( $this->indexes as $index ) { + $sql[] = $index->create( $xmls ); + } + + if( isset( $this->data ) ) { + $sql[] = $this->data->create( $xmls ); + } + + return $sql; + } + + /** + * Marks a field or table for destruction + */ + function drop() { + if( isset( $this->current_field ) ) { + // Drop the current field + logMsg( "Dropping field '{$this->current_field}' from table '{$this->name}'" ); + // $this->drop_field[$this->current_field] = $xmls->dict->DropColumnSQL( $this->name, $this->current_field ); + $this->drop_field[$this->current_field] = $this->current_field; + } else { + // Drop the current table + logMsg( "Dropping table '{$this->name}'" ); + // $this->drop_table = $xmls->dict->DropTableSQL( $this->name ); + $this->drop_table = TRUE; + } + } +} + +/** +* Creates an index object in ADOdb's datadict format +* +* This class stores information about a database index. As charactaristics +* of the index are loaded from the external source, methods and properties +* of this class are used to build up the index description in ADOdb's +* datadict format. +* +* @package axmls +* @access private +*/ +class dbIndex extends dbObject { + + /** + * @var string Index name + */ + var $name; + + /** + * @var array Index options: Index-level options + */ + var $opts = array(); + + /** + * @var array Indexed fields: Table columns included in this index + */ + var $columns = array(); + + /** + * @var boolean Mark index for destruction + * @access private + */ + var $drop = FALSE; + + /** + * Initializes the new dbIndex object. + * + * @param object $parent Parent object + * @param array $attributes Attributes + * + * @internal + */ + function dbIndex( &$parent, $attributes = NULL ) { + $this->parent =& $parent; + + $this->name = $this->prefix ($attributes['NAME']); + } + + /** + * XML Callback to process start elements + * + * Processes XML opening tags. + * Elements currently processed are: DROP, CLUSTERED, BITMAP, UNIQUE, FULLTEXT & HASH. + * + * @access private + */ + function _tag_open( &$parser, $tag, $attributes ) { + $this->currentElement = strtoupper( $tag ); + + switch( $this->currentElement ) { + case 'DROP': + $this->drop(); + break; + case 'CLUSTERED': + case 'BITMAP': + case 'UNIQUE': + case 'FULLTEXT': + case 'HASH': + // Add index Option + $this->addIndexOpt( $this->currentElement ); + break; + default: + // print_r( array( $tag, $attributes ) ); + } + } + + /** + * XML Callback to process CDATA elements + * + * Processes XML cdata. + * + * @access private + */ + function _tag_cdata( &$parser, $cdata ) { + switch( $this->currentElement ) { + // Index field name + case 'COL': + $this->addField( $cdata ); + break; + default: + + } + } + + /** + * XML Callback to process end elements + * + * @access private + */ + function _tag_close( &$parser, $tag ) { + $this->currentElement = ''; + + switch( strtoupper( $tag ) ) { + case 'INDEX': + xml_set_object( $parser, $this->parent ); + break; + } + } + + /** + * Adds a field to the index + * + * @param string $name Field name + * @return string Field list + */ + function addField( $name ) { + $this->columns[$this->FieldID( $name )] = $name; + + // Return the field list + return $this->columns; + } + + /** + * Adds options to the index + * + * @param string $opt Comma-separated list of index options. + * @return string Option list + */ + function addIndexOpt( $opt ) { + $this->opts[] = $opt; + + // Return the options list + return $this->opts; + } + + /** + * Generates the SQL that will create the index in the database + * + * @param object $xmls adoSchema object + * @return array Array containing index creation SQL + */ + function create( &$xmls ) { + if( $this->drop ) { + return NULL; + } + + // eliminate any columns that aren't in the table + foreach( $this->columns as $id => $col ) { + if( !isset( $this->parent->fields[$id] ) ) { + unset( $this->columns[$id] ); + } + } + + return $xmls->dict->CreateIndexSQL( $this->name, $this->parent->name, $this->columns, $this->opts ); + } + + /** + * Marks an index for destruction + */ + function drop() { + $this->drop = TRUE; + } +} + +/** +* Creates a data object in ADOdb's datadict format +* +* This class stores information about table data. +* +* @package axmls +* @access private +*/ +class dbData extends dbObject { + + var $data = array(); + + var $row; + + /** + * Initializes the new dbIndex object. + * + * @param object $parent Parent object + * @param array $attributes Attributes + * + * @internal + */ + function dbData( &$parent, $attributes = NULL ) { + $this->parent =& $parent; + } + + /** + * XML Callback to process start elements + * + * Processes XML opening tags. + * Elements currently processed are: DROP, CLUSTERED, BITMAP, UNIQUE, FULLTEXT & HASH. + * + * @access private + */ + function _tag_open( &$parser, $tag, $attributes ) { + $this->currentElement = strtoupper( $tag ); + + switch( $this->currentElement ) { + case 'ROW': + $this->row = count( $this->data ); + $this->data[$this->row] = array(); + break; + case 'F': + $this->addField($attributes); + default: + // print_r( array( $tag, $attributes ) ); + } + } + + /** + * XML Callback to process CDATA elements + * + * Processes XML cdata. + * + * @access private + */ + function _tag_cdata( &$parser, $cdata ) { + switch( $this->currentElement ) { + // Index field name + case 'F': + $this->addData( $cdata ); + break; + default: + + } + } + + /** + * XML Callback to process end elements + * + * @access private + */ + function _tag_close( &$parser, $tag ) { + $this->currentElement = ''; + + switch( strtoupper( $tag ) ) { + case 'DATA': + xml_set_object( $parser, $this->parent ); + break; + } + } + + /** + * Adds a field to the index + * + * @param string $name Field name + * @return string Field list + */ + function addField( $attributes ) { + if( isset( $attributes['NAME'] ) ) { + $name = $attributes['NAME']; + } else { + $name = count($this->data[$this->row]); + } + + // Set the field index so we know where we are + $this->current_field = $this->FieldID( $name ); + } + + /** + * Adds options to the index + * + * @param string $opt Comma-separated list of index options. + * @return string Option list + */ + function addData( $cdata ) { + if( !isset( $this->data[$this->row] ) ) { + $this->data[$this->row] = array(); + } + + if( !isset( $this->data[$this->row][$this->current_field] ) ) { + $this->data[$this->row][$this->current_field] = ''; + } + + $this->data[$this->row][$this->current_field] .= $cdata; + } + + /** + * Generates the SQL that will create the index in the database + * + * @param object $xmls adoSchema object + * @return array Array containing index creation SQL + */ + function create( &$xmls ) { + $table = $xmls->dict->TableName($this->parent->name); + $table_field_count = count($this->parent->fields); + $sql = array(); + + // eliminate any columns that aren't in the table + foreach( $this->data as $row ) { + $table_fields = $this->parent->fields; + $fields = array(); + + foreach( $row as $field_id => $field_data ) { + if( !array_key_exists( $field_id, $table_fields ) ) { + if( is_numeric( $field_id ) ) { + $field_id = reset( array_keys( $table_fields ) ); + } else { + continue; + } + } + + $name = $table_fields[$field_id]['NAME']; + + switch( $table_fields[$field_id]['TYPE'] ) { + case 'C': + case 'C2': + case 'X': + case 'X2': + $fields[$name] = $xmls->db->qstr( $field_data ); + break; + case 'I': + case 'I1': + case 'I2': + case 'I4': + case 'I8': + $fields[$name] = intval($field_data); + break; + default: + $fields[$name] = $field_data; + } + + unset($table_fields[$field_id]); + } + + // check that at least 1 column is specified + if( empty( $fields ) ) { + continue; + } + + // check that no required columns are missing + if( count( $fields ) < $table_field_count ) { + foreach( $table_fields as $field ) { + if (isset( $field['OPTS'] )) + if( ( in_array( 'NOTNULL', $field['OPTS'] ) || in_array( 'KEY', $field['OPTS'] ) ) && !in_array( 'AUTOINCREMENT', $field['OPTS'] ) ) { + continue(2); + } + } + } + + $sql[] = 'INSERT INTO '. $table .' ('. implode( ',', array_keys( $fields ) ) .') VALUES ('. implode( ',', $fields ) .')'; + } + + return $sql; + } +} + +/** +* Creates the SQL to execute a list of provided SQL queries +* +* @package axmls +* @access private +*/ +class dbQuerySet extends dbObject { + + /** + * @var array List of SQL queries + */ + var $queries = array(); + + /** + * @var string String used to build of a query line by line + */ + var $query; + + /** + * @var string Query prefix key + */ + var $prefixKey = ''; + + /** + * @var boolean Auto prefix enable (TRUE) + */ + var $prefixMethod = 'AUTO'; + + /** + * Initializes the query set. + * + * @param object $parent Parent object + * @param array $attributes Attributes + */ + function dbQuerySet( &$parent, $attributes = NULL ) { + $this->parent =& $parent; + + // Overrides the manual prefix key + if( isset( $attributes['KEY'] ) ) { + $this->prefixKey = $attributes['KEY']; + } + + $prefixMethod = isset( $attributes['PREFIXMETHOD'] ) ? strtoupper( trim( $attributes['PREFIXMETHOD'] ) ) : ''; + + // Enables or disables automatic prefix prepending + switch( $prefixMethod ) { + case 'AUTO': + $this->prefixMethod = 'AUTO'; + break; + case 'MANUAL': + $this->prefixMethod = 'MANUAL'; + break; + case 'NONE': + $this->prefixMethod = 'NONE'; + break; + } + } + + /** + * XML Callback to process start elements. Elements currently + * processed are: QUERY. + * + * @access private + */ + function _tag_open( &$parser, $tag, $attributes ) { + $this->currentElement = strtoupper( $tag ); + + switch( $this->currentElement ) { + case 'QUERY': + // Create a new query in a SQL queryset. + // Ignore this query set if a platform is specified and it's different than the + // current connection platform. + if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) { + $this->newQuery(); + } else { + $this->discardQuery(); + } + break; + default: + // print_r( array( $tag, $attributes ) ); + } + } + + /** + * XML Callback to process CDATA elements + */ + function _tag_cdata( &$parser, $cdata ) { + switch( $this->currentElement ) { + // Line of queryset SQL data + case 'QUERY': + $this->buildQuery( $cdata ); + break; + default: + + } + } + + /** + * XML Callback to process end elements + * + * @access private + */ + function _tag_close( &$parser, $tag ) { + $this->currentElement = ''; + + switch( strtoupper( $tag ) ) { + case 'QUERY': + // Add the finished query to the open query set. + $this->addQuery(); + break; + case 'SQL': + $this->parent->addSQL( $this->create( $this->parent ) ); + xml_set_object( $parser, $this->parent ); + $this->destroy(); + break; + default: + + } + } + + /** + * Re-initializes the query. + * + * @return boolean TRUE + */ + function newQuery() { + $this->query = ''; + + return TRUE; + } + + /** + * Discards the existing query. + * + * @return boolean TRUE + */ + function discardQuery() { + unset( $this->query ); + + return TRUE; + } + + /** + * Appends a line to a query that is being built line by line + * + * @param string $data Line of SQL data or NULL to initialize a new query + * @return string SQL query string. + */ + function buildQuery( $sql = NULL ) { + if( !isset( $this->query ) OR empty( $sql ) ) { + return FALSE; + } + + $this->query .= $sql; + + return $this->query; + } + + /** + * Adds a completed query to the query list + * + * @return string SQL of added query + */ + function addQuery() { + if( !isset( $this->query ) ) { + return FALSE; + } + + $this->queries[] = $return = trim($this->query); + + unset( $this->query ); + + return $return; + } + + /** + * Creates and returns the current query set + * + * @param object $xmls adoSchema object + * @return array Query set + */ + function create( &$xmls ) { + foreach( $this->queries as $id => $query ) { + switch( $this->prefixMethod ) { + case 'AUTO': + // Enable auto prefix replacement + + // Process object prefix. + // Evaluate SQL statements to prepend prefix to objects + $query = $this->prefixQuery( '/^\s*((?is)INSERT\s+(INTO\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix ); + $query = $this->prefixQuery( '/^\s*((?is)UPDATE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix ); + $query = $this->prefixQuery( '/^\s*((?is)DELETE\s+(FROM\s+)?)((\w+\s*,?\s*)+)(\s.*$)/', $query, $xmls->objectPrefix ); + + // SELECT statements aren't working yet + #$data = preg_replace( '/(?ias)(^\s*SELECT\s+.*\s+FROM)\s+(\W\s*,?\s*)+((?i)\s+WHERE.*$)/', "\1 $prefix\2 \3", $data ); + + case 'MANUAL': + // If prefixKey is set and has a value then we use it to override the default constant XMLS_PREFIX. + // If prefixKey is not set, we use the default constant XMLS_PREFIX + if( isset( $this->prefixKey ) AND( $this->prefixKey !== '' ) ) { + // Enable prefix override + $query = str_replace( $this->prefixKey, $xmls->objectPrefix, $query ); + } else { + // Use default replacement + $query = str_replace( XMLS_PREFIX , $xmls->objectPrefix, $query ); + } + } + + $this->queries[$id] = trim( $query ); + } + + // Return the query set array + return $this->queries; + } + + /** + * Rebuilds the query with the prefix attached to any objects + * + * @param string $regex Regex used to add prefix + * @param string $query SQL query string + * @param string $prefix Prefix to be appended to tables, indices, etc. + * @return string Prefixed SQL query string. + */ + function prefixQuery( $regex, $query, $prefix = NULL ) { + if( !isset( $prefix ) ) { + return $query; + } + + if( preg_match( $regex, $query, $match ) ) { + $preamble = $match[1]; + $postamble = $match[5]; + $objectList = explode( ',', $match[3] ); + // $prefix = $prefix . '_'; + + $prefixedList = ''; + + foreach( $objectList as $object ) { + if( $prefixedList !== '' ) { + $prefixedList .= ', '; + } + + $prefixedList .= $prefix . trim( $object ); + } + + $query = $preamble . ' ' . $prefixedList . ' ' . $postamble; + } + + return $query; + } +} + +/** +* Loads and parses an XML file, creating an array of "ready-to-run" SQL statements +* +* This class is used to load and parse the XML file, to create an array of SQL statements +* that can be used to build a database, and to build the database using the SQL array. +* +* @tutorial getting_started.pkg +* +* @author Richard Tango-Lowy & Dan Cech +* @version $Revision: 1.12 $ +* +* @package axmls +*/ +class adoSchema { + + /** + * @var array Array containing SQL queries to generate all objects + * @access private + */ + var $sqlArray; + + /** + * @var object ADOdb connection object + * @access private + */ + var $db; + + /** + * @var object ADOdb Data Dictionary + * @access private + */ + var $dict; + + /** + * @var string Current XML element + * @access private + */ + var $currentElement = ''; + + /** + * @var string If set (to 'ALTER' or 'REPLACE'), upgrade an existing database + * @access private + */ + var $upgrade = ''; + + /** + * @var string Optional object prefix + * @access private + */ + var $objectPrefix = ''; + + /** + * @var long Original Magic Quotes Runtime value + * @access private + */ + var $mgq; + + /** + * @var long System debug + * @access private + */ + var $debug; + + /** + * @var string Regular expression to find schema version + * @access private + */ + var $versionRegex = '//'; + + /** + * @var string Current schema version + * @access private + */ + var $schemaVersion; + + /** + * @var int Success of last Schema execution + */ + var $success; + + /** + * @var bool Execute SQL inline as it is generated + */ + var $executeInline; + + /** + * @var bool Continue SQL execution if errors occur + */ + var $continueOnError; + + /** + * Creates an adoSchema object + * + * Creating an adoSchema object is the first step in processing an XML schema. + * The only parameter is an ADOdb database connection object, which must already + * have been created. + * + * @param object $db ADOdb database connection object. + */ + function adoSchema( &$db ) { + // Initialize the environment + $this->mgq = get_magic_quotes_runtime(); + set_magic_quotes_runtime(0); + + $this->db =& $db; + $this->debug = $this->db->debug; + $this->dict = NewDataDictionary( $this->db ); + $this->sqlArray = array(); + $this->schemaVersion = XMLS_SCHEMA_VERSION; + $this->executeInline( XMLS_EXECUTE_INLINE ); + $this->continueOnError( XMLS_CONTINUE_ON_ERROR ); + $this->setUpgradeMethod(); + } + + /** + * Sets the method to be used for upgrading an existing database + * + * Use this method to specify how existing database objects should be upgraded. + * The method option can be set to ALTER, REPLACE, BEST, or NONE. ALTER attempts to + * alter each database object directly, REPLACE attempts to rebuild each object + * from scratch, BEST attempts to determine the best upgrade method for each + * object, and NONE disables upgrading. + * + * This method is not yet used by AXMLS, but exists for backward compatibility. + * The ALTER method is automatically assumed when the adoSchema object is + * instantiated; other upgrade methods are not currently supported. + * + * @param string $method Upgrade method (ALTER|REPLACE|BEST|NONE) + * @returns string Upgrade method used + */ + function SetUpgradeMethod( $method = '' ) { + if( !is_string( $method ) ) { + return FALSE; + } + + $method = strtoupper( $method ); + + // Handle the upgrade methods + switch( $method ) { + case 'ALTER': + $this->upgrade = $method; + break; + case 'REPLACE': + $this->upgrade = $method; + break; + case 'BEST': + $this->upgrade = 'ALTER'; + break; + case 'NONE': + $this->upgrade = 'NONE'; + break; + default: + // Use default if no legitimate method is passed. + $this->upgrade = XMLS_DEFAULT_UPGRADE_METHOD; + } + + return $this->upgrade; + } + + /** + * Enables/disables inline SQL execution. + * + * Call this method to enable or disable inline execution of the schema. If the mode is set to TRUE (inline execution), + * AXMLS applies the SQL to the database immediately as each schema entity is parsed. If the mode + * is set to FALSE (post execution), AXMLS parses the entire schema and you will need to call adoSchema::ExecuteSchema() + * to apply the schema to the database. + * + * @param bool $mode execute + * @return bool current execution mode + * + * @see ParseSchema(), ExecuteSchema() + */ + function ExecuteInline( $mode = NULL ) { + if( is_bool( $mode ) ) { + $this->executeInline = $mode; + } + + return $this->executeInline; + } + + /** + * Enables/disables SQL continue on error. + * + * Call this method to enable or disable continuation of SQL execution if an error occurs. + * If the mode is set to TRUE (continue), AXMLS will continue to apply SQL to the database, even if an error occurs. + * If the mode is set to FALSE (halt), AXMLS will halt execution of generated sql if an error occurs, though parsing + * of the schema will continue. + * + * @param bool $mode execute + * @return bool current continueOnError mode + * + * @see addSQL(), ExecuteSchema() + */ + function ContinueOnError( $mode = NULL ) { + if( is_bool( $mode ) ) { + $this->continueOnError = $mode; + } + + return $this->continueOnError; + } + + /** + * Loads an XML schema from a file and converts it to SQL. + * + * Call this method to load the specified schema (see the DTD for the proper format) from + * the filesystem and generate the SQL necessary to create the database described. + * @see ParseSchemaString() + * + * @param string $file Name of XML schema file. + * @param bool $returnSchema Return schema rather than parsing. + * @return array Array of SQL queries, ready to execute + */ + function ParseSchema( $filename, $returnSchema = FALSE ) { + return $this->ParseSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema ); + } + + /** + * Loads an XML schema from a file and converts it to SQL. + * + * Call this method to load the specified schema from a file (see the DTD for the proper format) + * and generate the SQL necessary to create the database described by the schema. + * + * @param string $file Name of XML schema file. + * @param bool $returnSchema Return schema rather than parsing. + * @return array Array of SQL queries, ready to execute. + * + * @deprecated Replaced by adoSchema::ParseSchema() and adoSchema::ParseSchemaString() + * @see ParseSchema(), ParseSchemaString() + */ + function ParseSchemaFile( $filename, $returnSchema = FALSE ) { + // Open the file + if( !($fp = fopen( $filename, 'r' )) ) { + // die( 'Unable to open file' ); + return FALSE; + } + + // do version detection here + if( $this->SchemaFileVersion( $filename ) != $this->schemaVersion ) { + return FALSE; + } + + if ( $returnSchema ) + { + $xmlstring = ''; + while( $data = fread( $fp, 100000 ) ) { + $xmlstring .= $data; + } + return $xmlstring; + } + + $this->success = 2; + + $xmlParser = $this->create_parser(); + + // Process the file + while( $data = fread( $fp, 4096 ) ) { + if( !xml_parse( $xmlParser, $data, feof( $fp ) ) ) { + die( sprintf( + "XML error: %s at line %d", + xml_error_string( xml_get_error_code( $xmlParser) ), + xml_get_current_line_number( $xmlParser) + ) ); + } + } + + xml_parser_free( $xmlParser ); + + return $this->sqlArray; + } + + /** + * Converts an XML schema string to SQL. + * + * Call this method to parse a string containing an XML schema (see the DTD for the proper format) + * and generate the SQL necessary to create the database described by the schema. + * @see ParseSchema() + * + * @param string $xmlstring XML schema string. + * @param bool $returnSchema Return schema rather than parsing. + * @return array Array of SQL queries, ready to execute. + */ + function ParseSchemaString( $xmlstring, $returnSchema = FALSE ) { + if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) { + return FALSE; + } + + // do version detection here + if( $this->SchemaStringVersion( $xmlstring ) != $this->schemaVersion ) { + return FALSE; + } + + if ( $returnSchema ) + { + return $xmlstring; + } + + $this->success = 2; + + $xmlParser = $this->create_parser(); + + if( !xml_parse( $xmlParser, $xmlstring, TRUE ) ) { + die( sprintf( + "XML error: %s at line %d", + xml_error_string( xml_get_error_code( $xmlParser) ), + xml_get_current_line_number( $xmlParser) + ) ); + } + + xml_parser_free( $xmlParser ); + + return $this->sqlArray; + } + + /** + * Loads an XML schema from a file and converts it to uninstallation SQL. + * + * Call this method to load the specified schema (see the DTD for the proper format) from + * the filesystem and generate the SQL necessary to remove the database described. + * @see RemoveSchemaString() + * + * @param string $file Name of XML schema file. + * @param bool $returnSchema Return schema rather than parsing. + * @return array Array of SQL queries, ready to execute + */ + function RemoveSchema( $filename, $returnSchema = FALSE ) { + return $this->RemoveSchemaString( $this->ConvertSchemaFile( $filename ), $returnSchema ); + } + + /** + * Converts an XML schema string to uninstallation SQL. + * + * Call this method to parse a string containing an XML schema (see the DTD for the proper format) + * and generate the SQL necessary to uninstall the database described by the schema. + * @see RemoveSchema() + * + * @param string $schema XML schema string. + * @param bool $returnSchema Return schema rather than parsing. + * @return array Array of SQL queries, ready to execute. + */ + function RemoveSchemaString( $schema, $returnSchema = FALSE ) { + + // grab current version + if( !( $version = $this->SchemaStringVersion( $schema ) ) ) { + return FALSE; + } + + return $this->ParseSchemaString( $this->TransformSchema( $schema, 'remove-' . $version), $returnSchema ); + } + + /** + * Applies the current XML schema to the database (post execution). + * + * Call this method to apply the current schema (generally created by calling + * ParseSchema() or ParseSchemaString() ) to the database (creating the tables, indexes, + * and executing other SQL specified in the schema) after parsing. + * @see ParseSchema(), ParseSchemaString(), ExecuteInline() + * + * @param array $sqlArray Array of SQL statements that will be applied rather than + * the current schema. + * @param boolean $continueOnErr Continue to apply the schema even if an error occurs. + * @returns integer 0 if failure, 1 if errors, 2 if successful. + */ + function ExecuteSchema( $sqlArray = NULL, $continueOnErr = NULL ) { + if( !is_bool( $continueOnErr ) ) { + $continueOnErr = $this->ContinueOnError(); + } + + if( !isset( $sqlArray ) ) { + $sqlArray = $this->sqlArray; + } + + if( !is_array( $sqlArray ) ) { + $this->success = 0; + } else { + $this->success = $this->dict->ExecuteSQLArray( $sqlArray, $continueOnErr ); + } + + return $this->success; + } + + /** + * Returns the current SQL array. + * + * Call this method to fetch the array of SQL queries resulting from + * ParseSchema() or ParseSchemaString(). + * + * @param string $format Format: HTML, TEXT, or NONE (PHP array) + * @return array Array of SQL statements or FALSE if an error occurs + */ + function PrintSQL( $format = 'NONE' ) { + $sqlArray = null; + return $this->getSQL( $format, $sqlArray ); + } + + /** + * Saves the current SQL array to the local filesystem as a list of SQL queries. + * + * Call this method to save the array of SQL queries (generally resulting from a + * parsed XML schema) to the filesystem. + * + * @param string $filename Path and name where the file should be saved. + * @return boolean TRUE if save is successful, else FALSE. + */ + function SaveSQL( $filename = './schema.sql' ) { + + if( !isset( $sqlArray ) ) { + $sqlArray = $this->sqlArray; + } + if( !isset( $sqlArray ) ) { + return FALSE; + } + + $fp = fopen( $filename, "w" ); + + foreach( $sqlArray as $key => $query ) { + fwrite( $fp, $query . ";\n" ); + } + fclose( $fp ); + } + + /** + * Create an xml parser + * + * @return object PHP XML parser object + * + * @access private + */ + function create_parser() { + // Create the parser + $xmlParser = xml_parser_create(); + xml_set_object( $xmlParser, $this ); + + // Initialize the XML callback functions + xml_set_element_handler( $xmlParser, '_tag_open', '_tag_close' ); + xml_set_character_data_handler( $xmlParser, '_tag_cdata' ); + + return $xmlParser; + } + + /** + * XML Callback to process start elements + * + * @access private + */ + function _tag_open( &$parser, $tag, $attributes ) { + switch( strtoupper( $tag ) ) { + case 'TABLE': + $this->obj = new dbTable( $this, $attributes ); + xml_set_object( $parser, $this->obj ); + break; + case 'SQL': + if( !isset( $attributes['PLATFORM'] ) OR $this->supportedPlatform( $attributes['PLATFORM'] ) ) { + $this->obj = new dbQuerySet( $this, $attributes ); + xml_set_object( $parser, $this->obj ); + } + break; + default: + // print_r( array( $tag, $attributes ) ); + } + + } + + /** + * XML Callback to process CDATA elements + * + * @access private + */ + function _tag_cdata( &$parser, $cdata ) { + } + + /** + * XML Callback to process end elements + * + * @access private + * @internal + */ + function _tag_close( &$parser, $tag ) { + + } + + /** + * Converts an XML schema string to the specified DTD version. + * + * Call this method to convert a string containing an XML schema to a different AXMLS + * DTD version. For instance, to convert a schema created for an pre-1.0 version for + * AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version + * parameter is specified, the schema will be converted to the current DTD version. + * If the newFile parameter is provided, the converted schema will be written to the specified + * file. + * @see ConvertSchemaFile() + * + * @param string $schema String containing XML schema that will be converted. + * @param string $newVersion DTD version to convert to. + * @param string $newFile File name of (converted) output file. + * @return string Converted XML schema or FALSE if an error occurs. + */ + function ConvertSchemaString( $schema, $newVersion = NULL, $newFile = NULL ) { + + // grab current version + if( !( $version = $this->SchemaStringVersion( $schema ) ) ) { + return FALSE; + } + + if( !isset ($newVersion) ) { + $newVersion = $this->schemaVersion; + } + + if( $version == $newVersion ) { + $result = $schema; + } else { + $result = $this->TransformSchema( $schema, 'convert-' . $version . '-' . $newVersion); + } + + if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) { + fwrite( $fp, $result ); + fclose( $fp ); + } + + return $result; + } + + // compat for pre-4.3 - jlim + function _file_get_contents($path) + { + if (function_exists('file_get_contents')) return file_get_contents($path); + return join('',file($path)); + } + + /** + * Converts an XML schema file to the specified DTD version. + * + * Call this method to convert the specified XML schema file to a different AXMLS + * DTD version. For instance, to convert a schema created for an pre-1.0 version for + * AXMLS (DTD version 0.1) to a newer version of the DTD (e.g. 0.2). If no DTD version + * parameter is specified, the schema will be converted to the current DTD version. + * If the newFile parameter is provided, the converted schema will be written to the specified + * file. + * @see ConvertSchemaString() + * + * @param string $filename Name of XML schema file that will be converted. + * @param string $newVersion DTD version to convert to. + * @param string $newFile File name of (converted) output file. + * @return string Converted XML schema or FALSE if an error occurs. + */ + function ConvertSchemaFile( $filename, $newVersion = NULL, $newFile = NULL ) { + + // grab current version + if( !( $version = $this->SchemaFileVersion( $filename ) ) ) { + return FALSE; + } + + if( !isset ($newVersion) ) { + $newVersion = $this->schemaVersion; + } + + if( $version == $newVersion ) { + $result = _file_get_contents( $filename ); + + // remove unicode BOM if present + if( substr( $result, 0, 3 ) == sprintf( '%c%c%c', 239, 187, 191 ) ) { + $result = substr( $result, 3 ); + } + } else { + $result = $this->TransformSchema( $filename, 'convert-' . $version . '-' . $newVersion, 'file' ); + } + + if( is_string( $result ) AND is_string( $newFile ) AND ( $fp = fopen( $newFile, 'w' ) ) ) { + fwrite( $fp, $result ); + fclose( $fp ); + } + + return $result; + } + + function TransformSchema( $schema, $xsl, $schematype='string' ) + { + // Fail if XSLT extension is not available + if( ! function_exists( 'xslt_create' ) ) { + return FALSE; + } + + $xsl_file = dirname( __FILE__ ) . '/xsl/' . $xsl . '.xsl'; + + // look for xsl + if( !is_readable( $xsl_file ) ) { + return FALSE; + } + + switch( $schematype ) + { + case 'file': + if( !is_readable( $schema ) ) { + return FALSE; + } + + $schema = _file_get_contents( $schema ); + break; + case 'string': + default: + if( !is_string( $schema ) ) { + return FALSE; + } + } + + $arguments = array ( + '/_xml' => $schema, + '/_xsl' => _file_get_contents( $xsl_file ) + ); + + // create an XSLT processor + $xh = xslt_create (); + + // set error handler + xslt_set_error_handler ($xh, array (&$this, 'xslt_error_handler')); + + // process the schema + $result = xslt_process ($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments); + + xslt_free ($xh); + + return $result; + } + + /** + * Processes XSLT transformation errors + * + * @param object $parser XML parser object + * @param integer $errno Error number + * @param integer $level Error level + * @param array $fields Error information fields + * + * @access private + */ + function xslt_error_handler( $parser, $errno, $level, $fields ) { + if( is_array( $fields ) ) { + $msg = array( + 'Message Type' => ucfirst( $fields['msgtype'] ), + 'Message Code' => $fields['code'], + 'Message' => $fields['msg'], + 'Error Number' => $errno, + 'Level' => $level + ); + + switch( $fields['URI'] ) { + case 'arg:/_xml': + $msg['Input'] = 'XML'; + break; + case 'arg:/_xsl': + $msg['Input'] = 'XSL'; + break; + default: + $msg['Input'] = $fields['URI']; + } + + $msg['Line'] = $fields['line']; + } else { + $msg = array( + 'Message Type' => 'Error', + 'Error Number' => $errno, + 'Level' => $level, + 'Fields' => var_export( $fields, TRUE ) + ); + } + + $error_details = $msg['Message Type'] . ' in XSLT Transformation' . "\n" + . '' . "\n"; + + foreach( $msg as $label => $details ) { + $error_details .= '' . "\n"; + } + + $error_details .= '
    ' . $label . ': ' . htmlentities( $details ) . '
    '; + + trigger_error( $error_details, E_USER_ERROR ); + } + + /** + * Returns the AXMLS Schema Version of the requested XML schema file. + * + * Call this method to obtain the AXMLS DTD version of the requested XML schema file. + * @see SchemaStringVersion() + * + * @param string $filename AXMLS schema file + * @return string Schema version number or FALSE on error + */ + function SchemaFileVersion( $filename ) { + // Open the file + if( !($fp = fopen( $filename, 'r' )) ) { + // die( 'Unable to open file' ); + return FALSE; + } + + // Process the file + while( $data = fread( $fp, 4096 ) ) { + if( preg_match( $this->versionRegex, $data, $matches ) ) { + return !empty( $matches[2] ) ? $matches[2] : XMLS_DEFAULT_SCHEMA_VERSION; + } + } + + return FALSE; + } + + /** + * Returns the AXMLS Schema Version of the provided XML schema string. + * + * Call this method to obtain the AXMLS DTD version of the provided XML schema string. + * @see SchemaFileVersion() + * + * @param string $xmlstring XML schema string + * @return string Schema version number or FALSE on error + */ + function SchemaStringVersion( $xmlstring ) { + if( !is_string( $xmlstring ) OR empty( $xmlstring ) ) { + return FALSE; + } + + if( preg_match( $this->versionRegex, $xmlstring, $matches ) ) { + return !empty( $matches[2] ) ? $matches[2] : XMLS_DEFAULT_SCHEMA_VERSION; + } + + return FALSE; + } + + /** + * Extracts an XML schema from an existing database. + * + * Call this method to create an XML schema string from an existing database. + * If the data parameter is set to TRUE, AXMLS will include the data from the database + * in the schema. + * + * @param boolean $data Include data in schema dump + * @return string Generated XML schema + */ + function ExtractSchema( $data = FALSE ) { + $old_mode = $this->db->SetFetchMode( ADODB_FETCH_NUM ); + + $schema = '' . "\n" + . '' . "\n"; + + if( is_array( $tables = $this->db->MetaTables( 'TABLES' ) ) ) { + foreach( $tables as $table ) { + $schema .= ' ' . "\n"; + + // grab details from database + $rs = $this->db->Execute( 'SELECT * FROM ' . $table . ' WHERE 1=1' ); + $fields = $this->db->MetaColumns( $table ); + $indexes = $this->db->MetaIndexes( $table ); + + if( is_array( $fields ) ) { + foreach( $fields as $details ) { + $extra = ''; + $content = array(); + + if( $details->max_length > 0 ) { + $extra .= ' size="' . $details->max_length . '"'; + } + + if( $details->primary_key ) { + $content[] = ''; + } elseif( $details->not_null ) { + $content[] = ''; + } + + if( $details->has_default ) { + $content[] = ''; + } + + if( $details->auto_increment ) { + $content[] = ''; + } + + // this stops the creation of 'R' columns, + // AUTOINCREMENT is used to create auto columns + $details->primary_key = 0; + $type = $rs->MetaType( $details ); + + $schema .= ' '; + + if( !empty( $content ) ) { + $schema .= "\n " . implode( "\n ", $content ) . "\n "; + } + + $schema .= '' . "\n"; + } + } + + if( is_array( $indexes ) ) { + foreach( $indexes as $index => $details ) { + $schema .= ' ' . "\n"; + + if( $details['unique'] ) { + $schema .= ' ' . "\n"; + } + + foreach( $details['columns'] as $column ) { + $schema .= ' ' . $column . '' . "\n"; + } + + $schema .= ' ' . "\n"; + } + } + + if( $data ) { + $rs = $this->db->Execute( 'SELECT * FROM ' . $table ); + + if( is_object( $rs ) ) { + $schema .= ' ' . "\n"; + + while( $row = $rs->FetchRow() ) { + foreach( $row as $key => $val ) { + $row[$key] = htmlentities($val); + } + + $schema .= ' ' . implode( '', $row ) . '' . "\n"; + } + + $schema .= ' ' . "\n"; + } + } + + $schema .= '
    ' . "\n"; + } + } + + $this->db->SetFetchMode( $old_mode ); + + $schema .= '
    '; + return $schema; + } + + /** + * Sets a prefix for database objects + * + * Call this method to set a standard prefix that will be prepended to all database tables + * and indices when the schema is parsed. Calling setPrefix with no arguments clears the prefix. + * + * @param string $prefix Prefix that will be prepended. + * @param boolean $underscore If TRUE, automatically append an underscore character to the prefix. + * @return boolean TRUE if successful, else FALSE + */ + function SetPrefix( $prefix = '', $underscore = TRUE ) { + switch( TRUE ) { + // clear prefix + case empty( $prefix ): + logMsg( 'Cleared prefix' ); + $this->objectPrefix = ''; + return TRUE; + // prefix too long + case strlen( $prefix ) > XMLS_PREFIX_MAXLEN: + // prefix contains invalid characters + case !preg_match( '/^[a-z][a-z0-9_]+$/i', $prefix ): + logMsg( 'Invalid prefix: ' . $prefix ); + return FALSE; + } + + if( $underscore AND substr( $prefix, -1 ) != '_' ) { + $prefix .= '_'; + } + + // prefix valid + logMsg( 'Set prefix: ' . $prefix ); + $this->objectPrefix = $prefix; + return TRUE; + } + + /** + * Returns an object name with the current prefix prepended. + * + * @param string $name Name + * @return string Prefixed name + * + * @access private + */ + function prefix( $name = '' ) { + // if prefix is set + if( !empty( $this->objectPrefix ) ) { + // Prepend the object prefix to the table name + // prepend after quote if used + return preg_replace( '/^(`?)(.+)$/', '$1' . $this->objectPrefix . '$2', $name ); + } + + // No prefix set. Use name provided. + return $name; + } + + /** + * Checks if element references a specific platform + * + * @param string $platform Requested platform + * @returns boolean TRUE if platform check succeeds + * + * @access private + */ + function supportedPlatform( $platform = NULL ) { + $regex = '/^(\w*\|)*' . $this->db->databaseType . '(\|\w*)*$/'; + + if( !isset( $platform ) OR preg_match( $regex, $platform ) ) { + logMsg( "Platform $platform is supported" ); + return TRUE; + } else { + logMsg( "Platform $platform is NOT supported" ); + return FALSE; + } + } + + /** + * Clears the array of generated SQL. + * + * @access private + */ + function clearSQL() { + $this->sqlArray = array(); + } + + /** + * Adds SQL into the SQL array. + * + * @param mixed $sql SQL to Add + * @return boolean TRUE if successful, else FALSE. + * + * @access private + */ + function addSQL( $sql = NULL ) { + if( is_array( $sql ) ) { + foreach( $sql as $line ) { + $this->addSQL( $line ); + } + + return TRUE; + } + + if( is_string( $sql ) ) { + $this->sqlArray[] = $sql; + + // if executeInline is enabled, and either no errors have occurred or continueOnError is enabled, execute SQL. + if( $this->ExecuteInline() && ( $this->success == 2 || $this->ContinueOnError() ) ) { + $saved = $this->db->debug; + $this->db->debug = $this->debug; + $ok = $this->db->Execute( $sql ); + $this->db->debug = $saved; + + if( !$ok ) { + if( $this->debug ) { + ADOConnection::outp( $this->db->ErrorMsg() ); + } + + $this->success = 1; + } + } + + return TRUE; + } + + return FALSE; + } + + /** + * Gets the SQL array in the specified format. + * + * @param string $format Format + * @return mixed SQL + * + * @access private + */ + function getSQL( $format = NULL, $sqlArray = NULL ) { + if( !is_array( $sqlArray ) ) { + $sqlArray = $this->sqlArray; + } + + if( !is_array( $sqlArray ) ) { + return FALSE; + } + + switch( strtolower( $format ) ) { + case 'string': + case 'text': + return !empty( $sqlArray ) ? implode( ";\n\n", $sqlArray ) . ';' : ''; + case'html': + return !empty( $sqlArray ) ? nl2br( htmlentities( implode( ";\n\n", $sqlArray ) . ';' ) ) : ''; + } + + return $this->sqlArray; + } + + /** + * Destroys an adoSchema object. + * + * Call this method to clean up after an adoSchema object that is no longer in use. + * @deprecated adoSchema now cleans up automatically. + */ + function Destroy() { + set_magic_quotes_runtime( $this->mgq ); + unset( $this ); + } +} + +/** +* Message logging function +* +* @access private +*/ +function logMsg( $msg, $title = NULL, $force = FALSE ) { + if( XMLS_DEBUG or $force ) { + echo '
    ';
    +		
    +		if( isset( $title ) ) {
    +			echo '

    ' . htmlentities( $title ) . '

    '; + } + + if( is_object( $this ) ) { + echo '[' . get_class( $this ) . '] '; + } + + print_r( $msg ); + + echo '
    '; + } +} +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb.inc.php new file mode 100644 index 0000000..e47e34b --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/adodb.inc.php @@ -0,0 +1,3963 @@ +fields is available on EOF + $ADODB_FETCH_MODE; // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default... + + //============================================================================================== + // GLOBAL SETUP + //============================================================================================== + + $ADODB_EXTENSION = defined('ADODB_EXTENSION'); + + //********************************************************// + /* + Controls $ADODB_FORCE_TYPE mode. Default is ADODB_FORCE_VALUE (3). + Used in GetUpdateSql and GetInsertSql functions. Thx to Niko, nuko#mbnet.fi + + 0 = ignore empty fields. All empty fields in array are ignored. + 1 = force null. All empty, php null and string 'null' fields are changed to sql NULL values. + 2 = force empty. All empty, php null and string 'null' fields are changed to sql empty '' or 0 values. + 3 = force value. Value is left as it is. Php null and string 'null' are set to sql NULL values and empty fields '' are set to empty '' sql values. + */ + define('ADODB_FORCE_IGNORE',0); + define('ADODB_FORCE_NULL',1); + define('ADODB_FORCE_EMPTY',2); + define('ADODB_FORCE_VALUE',3); + //********************************************************// + + + if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) { + + define('ADODB_BAD_RS','

    Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;

    '); + + // allow [ ] @ ` " and . in table names + define('ADODB_TABLE_REGEX','([]0-9a-z_\:\"\`\.\@\[-]*)'); + + // prefetching used by oracle + if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10); + + + /* + Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names. + This currently works only with mssql, odbc, oci8po and ibase derived drivers. + + 0 = assoc lowercase field names. $rs->fields['orderid'] + 1 = assoc uppercase field names. $rs->fields['ORDERID'] + 2 = use native-case field names. $rs->fields['OrderID'] + */ + + define('ADODB_FETCH_DEFAULT',0); + define('ADODB_FETCH_NUM',1); + define('ADODB_FETCH_ASSOC',2); + define('ADODB_FETCH_BOTH',3); + + if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100); + + // PHP's version scheme makes converting to numbers difficult - workaround + $_adodb_ver = (float) PHP_VERSION; + if ($_adodb_ver >= 5.0) { + define('ADODB_PHPVER',0x5000); + } else if ($_adodb_ver > 4.299999) { # 4.3 + define('ADODB_PHPVER',0x4300); + } else if ($_adodb_ver > 4.199999) { # 4.2 + define('ADODB_PHPVER',0x4200); + } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) { + define('ADODB_PHPVER',0x4050); + } else { + define('ADODB_PHPVER',0x4000); + } + } + + //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2); + + + /** + Accepts $src and $dest arrays, replacing string $data + */ + function ADODB_str_replace($src, $dest, $data) + { + if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data); + + $s = reset($src); + $d = reset($dest); + while ($s !== false) { + $data = str_replace($s,$d,$data); + $s = next($src); + $d = next($dest); + } + return $data; + } + + function ADODB_Setup() + { + GLOBAL + $ADODB_vers, // database version + $ADODB_COUNTRECS, // count number of records returned - slows down query + $ADODB_CACHE_DIR, // directory to cache recordsets + $ADODB_FETCH_MODE, + $ADODB_FORCE_TYPE; + + $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT; + $ADODB_FORCE_TYPE = ADODB_FORCE_VALUE; + + + if (!isset($ADODB_CACHE_DIR)) { + $ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp'; + } else { + // do not accept url based paths, eg. http:/ or ftp:/ + if (strpos($ADODB_CACHE_DIR,'://') !== false) + die("Illegal path http:// or ftp://"); + } + + + // Initialize random number generator for randomizing cache flushes + srand(((double)microtime())*1000000); + + /** + * ADODB version as a string. + */ + $ADODB_vers = 'V4.71 24 Jan 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.'; + + /** + * Determines whether recordset->RecordCount() is used. + * Set to false for highest performance -- RecordCount() will always return -1 then + * for databases that provide "virtual" recordcounts... + */ + if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true; + } + + + //============================================================================================== + // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB + //============================================================================================== + + ADODB_Setup(); + + //============================================================================================== + // CLASS ADOFieldObject + //============================================================================================== + /** + * Helper class for FetchFields -- holds info on a column + */ + class ADOFieldObject { + var $name = ''; + var $max_length=0; + var $type=""; +/* + // additional fields by dannym... (danny_milo@yahoo.com) + var $not_null = false; + // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^ + // so we can as well make not_null standard (leaving it at "false" does not harm anyways) + + var $has_default = false; // this one I have done only in mysql and postgres for now ... + // others to come (dannym) + var $default_value; // default, if any, and supported. Check has_default first. +*/ + } + + + + function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection) + { + //print "Errorno ($fn errno=$errno m=$errmsg) "; + $thisConnection->_transOK = false; + if ($thisConnection->_oldRaiseFn) { + $fn = $thisConnection->_oldRaiseFn; + $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection); + } + } + + //============================================================================================== + // CLASS ADOConnection + //============================================================================================== + + /** + * Connection object. For connecting to databases, and executing queries. + */ + class ADOConnection { + // + // PUBLIC VARS + // + var $dataProvider = 'native'; + var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql + var $database = ''; /// Name of database to be used. + var $host = ''; /// The hostname of the database server + var $user = ''; /// The username which is used to connect to the database server. + var $password = ''; /// Password for the username. For security, we no longer store it. + var $debug = false; /// if set to true will output sql statements + var $maxblobsize = 262144; /// maximum size of blobs or large text fields (262144 = 256K)-- some db's die otherwise like foxpro + var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase + var $substr = 'substr'; /// substring operator + var $length = 'length'; /// string length ofperator + var $random = 'rand()'; /// random function + var $upperCase = 'upper'; /// uppercase function + var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database + var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt. + var $true = '1'; /// string that represents TRUE for a database + var $false = '0'; /// string that represents FALSE for a database + var $replaceQuote = "\\'"; /// string to use to replace quotes + var $nameQuote = '"'; /// string to use to quote identifiers and names + var $charSet=false; /// character set to use - only for interbase, postgres and oci8 + var $metaDatabasesSQL = ''; + var $metaTablesSQL = ''; + var $uniqueOrderBy = false; /// All order by columns have to be unique + var $emptyDate = ' '; + var $emptyTimeStamp = ' '; + var $lastInsID = false; + //-- + var $hasInsertID = false; /// supports autoincrement ID? + var $hasAffectedRows = false; /// supports affected rows for update/delete? + var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE + var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10 + var $readOnly = false; /// this is a readonly database - used by phpLens + var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards + var $hasGenID = false; /// can generate sequences using GenID(); + var $hasTransactions = true; /// has transactions + //-- + var $genID = 0; /// sequence id used by GenID(); + var $raiseErrorFn = false; /// error function to call + var $isoDates = false; /// accepts dates in ISO format + var $cacheSecs = 3600; /// cache for 1 hour + var $sysDate = false; /// name of function that returns the current date + var $sysTimeStamp = false; /// name of function that returns the current timestamp + var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets + + var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' ' + var $numCacheHits = 0; + var $numCacheMisses = 0; + var $pageExecuteCountRows = true; + var $uniqueSort = false; /// indicates that all fields in order by must be unique + var $leftOuter = false; /// operator to use for left outer join in WHERE clause + var $rightOuter = false; /// operator to use for right outer join in WHERE clause + var $ansiOuter = false; /// whether ansi outer join syntax supported + var $autoRollback = false; // autoRollback on PConnect(). + var $poorAffectedRows = false; // affectedRows not working or unreliable + + var $fnExecute = false; + var $fnCacheExecute = false; + var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char + var $rsPrefix = "ADORecordSet_"; + + var $autoCommit = true; /// do not modify this yourself - actually private + var $transOff = 0; /// temporarily disable transactions + var $transCnt = 0; /// count of nested transactions + + var $fetchMode=false; + // + // PRIVATE VARS + // + var $_oldRaiseFn = false; + var $_transOK = null; + var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made. + var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will + /// then returned by the errorMsg() function + var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8 + var $_queryID = false; /// This variable keeps the last created result link identifier + + var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */ + var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters. + var $_evalAll = false; + var $_affected = false; + var $_logsql = false; + + + /** + * Constructor + */ + function __construct() + { + die('Virtual Class -- cannot instantiate'); + } + + function Version() + { + global $ADODB_vers; + + return (float) substr($ADODB_vers,1); + } + + /** + Get server version info... + + @returns An array with 2 elements: $arr['string'] is the description string, + and $arr[version] is the version (also a string). + */ + function ServerInfo() + { + return array('description' => '', 'version' => ''); + } + + function IsConnected() + { + return !empty($this->_connectionID); + } + + function _findvers($str) + { + if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1]; + else return ''; + } + + /** + * All error messages go through this bottleneck function. + * You can define your own handler by defining the function name in ADODB_OUTP. + */ + function outp($msg,$newline=true) + { + global $ADODB_FLUSH,$ADODB_OUTP; + + if (defined('ADODB_OUTP')) { + $fn = ADODB_OUTP; + $fn($msg,$newline); + return; + } else if (isset($ADODB_OUTP)) { + $fn = $ADODB_OUTP; + $fn($msg,$newline); + return; + } + + if ($newline) $msg .= "
    \n"; + + if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) echo $msg; + else echo strip_tags($msg); + + + if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); // do not flush if output buffering enabled - useless - thx to Jesse Mullan + + } + + function Time() + { + $rs =& $this->_Execute("select $this->sysTimeStamp"); + if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields)); + + return false; + } + + /** + * Connect to database + * + * @param [argHostname] Host to connect to + * @param [argUsername] Userid to login + * @param [argPassword] Associated password + * @param [argDatabaseName] database + * @param [forceNew] force new connection + * + * @return true or false + */ + function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false) + { + if ($argHostname != "") $this->host = $argHostname; + if ($argUsername != "") $this->user = $argUsername; + if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons + if ($argDatabaseName != "") $this->database = $argDatabaseName; + + $this->_isPersistentConnection = false; + if ($forceNew) { + if ($rez=$this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true; + } else { + if ($rez=$this->_connect($this->host, $this->user, $this->password, $this->database)) return true; + } + if (isset($rez)) { + $err = $this->ErrorMsg(); + if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'"; + $ret = false; + } else { + $err = "Missing extension for ".$this->dataProvider; + $ret = 0; + } + if ($fn = $this->raiseErrorFn) + $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this); + + + $this->_connectionID = false; + if ($this->debug) ADOConnection::outp( $this->host.': '.$err); + return $ret; + } + + function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName) + { + return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName); + } + + + /** + * Always force a new connection to database - currently only works with oracle + * + * @param [argHostname] Host to connect to + * @param [argUsername] Userid to login + * @param [argPassword] Associated password + * @param [argDatabaseName] database + * + * @return true or false + */ + function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") + { + return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true); + } + + /** + * Establish persistent connect to database + * + * @param [argHostname] Host to connect to + * @param [argUsername] Userid to login + * @param [argPassword] Associated password + * @param [argDatabaseName] database + * + * @return return true or false + */ + function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") + { + if (defined('ADODB_NEVER_PERSIST')) + return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName); + + if ($argHostname != "") $this->host = $argHostname; + if ($argUsername != "") $this->user = $argUsername; + if ($argPassword != "") $this->password = $argPassword; + if ($argDatabaseName != "") $this->database = $argDatabaseName; + + $this->_isPersistentConnection = true; + if ($rez = $this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true; + if (isset($rez)) { + $err = $this->ErrorMsg(); + if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'"; + $ret = false; + } else { + $err = "Missing extension for ".$this->dataProvider; + $ret = 0; + } + if ($fn = $this->raiseErrorFn) { + $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this); + } + + $this->_connectionID = false; + if ($this->debug) ADOConnection::outp( $this->host.': '.$err); + return $ret; + } + + // Format date column in sql string given an input format that understands Y M D + function SQLDate($fmt, $col=false) + { + if (!$col) $col = $this->sysDate; + return $col; // child class implement + } + + /** + * Should prepare the sql statement and return the stmt resource. + * For databases that do not support this, we return the $sql. To ensure + * compatibility with databases that do not support prepare: + * + * $stmt = $db->Prepare("insert into table (id, name) values (?,?)"); + * $db->Execute($stmt,array(1,'Jill')) or die('insert failed'); + * $db->Execute($stmt,array(2,'Joe')) or die('insert failed'); + * + * @param sql SQL to send to database + * + * @return return FALSE, or the prepared statement, or the original sql if + * if the database does not support prepare. + * + */ + function Prepare($sql) + { + return $sql; + } + + /** + * Some databases, eg. mssql require a different function for preparing + * stored procedures. So we cannot use Prepare(). + * + * Should prepare the stored procedure and return the stmt resource. + * For databases that do not support this, we return the $sql. To ensure + * compatibility with databases that do not support prepare: + * + * @param sql SQL to send to database + * + * @return return FALSE, or the prepared statement, or the original sql if + * if the database does not support prepare. + * + */ + function PrepareSP($sql,$param=true) + { + return $this->Prepare($sql,$param); + } + + /** + * PEAR DB Compat + */ + function Quote($s) + { + return $this->qstr($s,false); + } + + /** + Requested by "Karsten Dambekalns" + */ + function QMagic($s) + { + return $this->qstr($s,get_magic_quotes_gpc()); + } + + function q(&$s) + { + $s = $this->qstr($s,false); + } + + /** + * PEAR DB Compat - do not use internally. + */ + function ErrorNative() + { + return $this->ErrorNo(); + } + + + /** + * PEAR DB Compat - do not use internally. + */ + function nextId($seq_name) + { + return $this->GenID($seq_name); + } + + /** + * Lock a row, will escalate and lock the table if row locking not supported + * will normally free the lock at the end of the transaction + * + * @param $table name of table to lock + * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock + */ + function RowLock($table,$where) + { + return false; + } + + function CommitLock($table) + { + return $this->CommitTrans(); + } + + function RollbackLock($table) + { + return $this->RollbackTrans(); + } + + /** + * PEAR DB Compat - do not use internally. + * + * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical + * for easy porting :-) + * + * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM + * @returns The previous fetch mode + */ + function SetFetchMode($mode) + { + $old = $this->fetchMode; + $this->fetchMode = $mode; + + if ($old === false) { + global $ADODB_FETCH_MODE; + return $ADODB_FETCH_MODE; + } + return $old; + } + + + /** + * PEAR DB Compat - do not use internally. + */ + function Query($sql, $inputarr=false) + { + $rs = &$this->Execute($sql, $inputarr); + if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error(); + return $rs; + } + + + /** + * PEAR DB Compat - do not use internally + */ + function LimitQuery($sql, $offset, $count, $params=false) + { + $rs = &$this->SelectLimit($sql, $count, $offset, $params); + if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error(); + return $rs; + } + + + /** + * PEAR DB Compat - do not use internally + */ + function Disconnect() + { + return $this->Close(); + } + + /* + Returns placeholder for parameter, eg. + $DB->Param('a') + + will return ':a' for Oracle, and '?' for most other databases... + + For databases that require positioned params, eg $1, $2, $3 for postgresql, + pass in Param(false) before setting the first parameter. + */ + function Param($name,$type='C') + { + return '?'; + } + + /* + InParameter and OutParameter are self-documenting versions of Parameter(). + */ + function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false) + { + return $this->Parameter($stmt,$var,$name,false,$maxLen,$type); + } + + /* + */ + function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false) + { + return $this->Parameter($stmt,$var,$name,true,$maxLen,$type); + + } + + /* + Usage in oracle + $stmt = $db->Prepare('select * from table where id =:myid and group=:group'); + $db->Parameter($stmt,$id,'myid'); + $db->Parameter($stmt,$group,'group',64); + $db->Execute(); + + @param $stmt Statement returned by Prepare() or PrepareSP(). + @param $var PHP variable to bind to + @param $name Name of stored procedure variable name to bind to. + @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8. + @param [$maxLen] Holds an maximum length of the variable. + @param [$type] The data type of $var. Legal values depend on driver. + + */ + function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false) + { + return false; + } + + /** + Improved method of initiating a transaction. Used together with CompleteTrans(). + Advantages include: + + a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans. + Only the outermost block is treated as a transaction.
    + b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.
    + c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block + are disabled, making it backward compatible. + */ + function StartTrans($errfn = 'ADODB_TransMonitor') + { + if ($this->transOff > 0) { + $this->transOff += 1; + return; + } + + $this->_oldRaiseFn = $this->raiseErrorFn; + $this->raiseErrorFn = $errfn; + $this->_transOK = true; + + if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans"); + $this->BeginTrans(); + $this->transOff = 1; + } + + + /** + Used together with StartTrans() to end a transaction. Monitors connection + for sql errors, and will commit or rollback as appropriate. + + @autoComplete if true, monitor sql errors and commit and rollback as appropriate, + and if set to false force rollback even if no SQL error detected. + @returns true on commit, false on rollback. + */ + function CompleteTrans($autoComplete = true) + { + if ($this->transOff > 1) { + $this->transOff -= 1; + return true; + } + $this->raiseErrorFn = $this->_oldRaiseFn; + + $this->transOff = 0; + if ($this->_transOK && $autoComplete) { + if (!$this->CommitTrans()) { + $this->_transOK = false; + if ($this->debug) ADOConnection::outp("Smart Commit failed"); + } else + if ($this->debug) ADOConnection::outp("Smart Commit occurred"); + } else { + $this->_transOK = false; + $this->RollbackTrans(); + if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred"); + } + + return $this->_transOK; + } + + /* + At the end of a StartTrans/CompleteTrans block, perform a rollback. + */ + function FailTrans() + { + if ($this->debug) + if ($this->transOff == 0) { + ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans"); + } else { + ADOConnection::outp("FailTrans was called"); + adodb_backtrace(); + } + $this->_transOK = false; + } + + /** + Check if transaction has failed, only for Smart Transactions. + */ + function HasFailedTrans() + { + if ($this->transOff > 0) return $this->_transOK == false; + return false; + } + + /** + * Execute SQL + * + * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text) + * @param [inputarr] holds the input data to bind to. Null elements will be set to null. + * @return RecordSet or false + */ + function Execute($sql,$inputarr=false) + { + if ($this->fnExecute) { + $fn = $this->fnExecute; + $ret =& $fn($this,$sql,$inputarr); + if (isset($ret)) return $ret; + } + if ($inputarr) { + if (!is_array($inputarr)) $inputarr = array($inputarr); + + $element0 = reset($inputarr); + # is_object check because oci8 descriptors can be passed in + $array_2d = is_array($element0) && !is_object(reset($element0)); + + if (!is_array($sql) && !$this->_bindInputArray) { + $sqlarr = explode('?',$sql); + + if (!$array_2d) $inputarr = array($inputarr); + foreach($inputarr as $arr) { + $sql = ''; $i = 0; + foreach($arr as $v) { + $sql .= $sqlarr[$i]; + // from Ron Baldwin + // Only quote string types + $typ = gettype($v); + if ($typ == 'string') + $sql .= $this->qstr($v); + else if ($typ == 'double') + $sql .= str_replace(',','.',$v); // locales fix so 1.1 does not get converted to 1,1 + else if ($typ == 'boolean') + $sql .= $v ? $this->true : $this->false; + else if ($v === null) + $sql .= 'NULL'; + else + $sql .= $v; + $i += 1; + } + if (isset($sqlarr[$i])) { + $sql .= $sqlarr[$i]; + if ($i+1 != sizeof($sqlarr)) ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql)); + } else if ($i != sizeof($sqlarr)) + ADOConnection::outp( "Input array does not match ?: ".htmlspecialchars($sql)); + + $ret =& $this->_Execute($sql); + if (!$ret) return $ret; + } + } else { + if ($array_2d) { + if (is_string($sql)) + $stmt = $this->Prepare($sql); + else + $stmt = $sql; + + foreach($inputarr as $arr) { + $ret =& $this->_Execute($stmt,$arr); + if (!$ret) return $ret; + } + } else { + $ret =& $this->_Execute($sql,$inputarr); + } + } + } else { + $ret = $this->_Execute($sql,false); + } + + return $ret; + } + + + function _Execute($sql,$inputarr=false) + { + if ($this->debug) { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php'); + $this->_queryID = _adodb_debug_execute($this, $sql,$inputarr); + } else { + $this->_queryID = @$this->_query($sql,$inputarr); + } + + /************************ + // OK, query executed + *************************/ + + if ($this->_queryID === false) { // error handling if query fails + if ($this->debug == 99) adodb_backtrace(true,5); + $fn = $this->raiseErrorFn; + if ($fn) { + $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this); + } + $false = false; + return $false; + } + + if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead + $rs = new ADORecordSet_empty(); + return $rs; + } + + // return real recordset from select statement + $rsclass = $this->rsPrefix.$this->databaseType; + $rs = new $rsclass($this->_queryID,$this->fetchMode); + $rs->connection = &$this; // Pablo suggestion + $rs->Init(); + if (is_array($sql)) $rs->sql = $sql[0]; + else $rs->sql = $sql; + if ($rs->_numOfRows <= 0) { + global $ADODB_COUNTRECS; + if ($ADODB_COUNTRECS) { + if (!$rs->EOF) { + $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql)); + $rs->_queryID = $this->_queryID; + } else + $rs->_numOfRows = 0; + } + } + return $rs; + } + + function CreateSequence($seqname='adodbseq',$startID=1) + { + if (empty($this->_genSeqSQL)) return false; + return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID)); + } + + function DropSequence($seqname='adodbseq') + { + if (empty($this->_dropSeqSQL)) return false; + return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); + } + + /** + * Generates a sequence id and stores it in $this->genID; + * GenID is only available if $this->hasGenID = true; + * + * @param seqname name of sequence to use + * @param startID if sequence does not exist, start at this ID + * @return 0 if not supported, otherwise a sequence id + */ + function GenID($seqname='adodbseq',$startID=1) + { + if (!$this->hasGenID) { + return 0; // formerly returns false pre 1.60 + } + + $getnext = sprintf($this->_genIDSQL,$seqname); + + $holdtransOK = $this->_transOK; + + $save_handler = $this->raiseErrorFn; + $this->raiseErrorFn = ''; + @($rs = $this->Execute($getnext)); + $this->raiseErrorFn = $save_handler; + + if (!$rs) { + $this->_transOK = $holdtransOK; //if the status was ok before reset + $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID)); + $rs = $this->Execute($getnext); + } + if ($rs && !$rs->EOF) $this->genID = reset($rs->fields); + else $this->genID = 0; // false + + if ($rs) $rs->Close(); + + return $this->genID; + } + + /** + * @param $table string name of the table, not needed by all databases (eg. mysql), default '' + * @param $column string name of the column, not needed by all databases (eg. mysql), default '' + * @return the last inserted ID. Not all databases support this. + */ + function Insert_ID($table='',$column='') + { + if ($this->_logsql && $this->lastInsID) return $this->lastInsID; + if ($this->hasInsertID) return $this->_insertid($table,$column); + if ($this->debug) { + ADOConnection::outp( '

    Insert_ID error

    '); + adodb_backtrace(); + } + return false; + } + + + /** + * Portable Insert ID. Pablo Roca + * + * @return the last inserted ID. All databases support this. But aware possible + * problems in multiuser environments. Heavy test this before deploying. + */ + function PO_Insert_ID($table="", $id="") + { + if ($this->hasInsertID){ + return $this->Insert_ID($table,$id); + } else { + return $this->GetOne("SELECT MAX($id) FROM $table"); + } + } + + /** + * @return # rows affected by UPDATE/DELETE + */ + function Affected_Rows() + { + if ($this->hasAffectedRows) { + if ($this->fnExecute === 'adodb_log_sql') { + if ($this->_logsql && $this->_affected !== false) return $this->_affected; + } + $val = $this->_affectedrows(); + return ($val < 0) ? false : $val; + } + + if ($this->debug) ADOConnection::outp( '

    Affected_Rows error

    ',false); + return false; + } + + + /** + * @return the last error message + */ + function ErrorMsg() + { + if ($this->_errorMsg) return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg; + else return ''; + } + + + /** + * @return the last error number. Normally 0 means no error. + */ + function ErrorNo() + { + return ($this->_errorMsg) ? -1 : 0; + } + + function MetaError($err=false) + { + include_once(ADODB_DIR."/adodb-error.inc.php"); + if ($err === false) $err = $this->ErrorNo(); + return adodb_error($this->dataProvider,$this->databaseType,$err); + } + + function MetaErrorMsg($errno) + { + include_once(ADODB_DIR."/adodb-error.inc.php"); + return adodb_errormsg($errno); + } + + /** + * @returns an array with the primary key columns in it. + */ + function MetaPrimaryKeys($table, $owner=false) + { + // owner not used in base class - see oci8 + $p = array(); + $objs =& $this->MetaColumns($table); + if ($objs) { + foreach($objs as $v) { + if (!empty($v->primary_key)) + $p[] = $v->name; + } + } + if (sizeof($p)) return $p; + if (function_exists('ADODB_VIEW_PRIMARYKEYS')) + return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner); + return false; + } + + /** + * @returns assoc array where keys are tables, and values are foreign keys + */ + function MetaForeignKeys($table, $owner=false, $upper=false) + { + return false; + } + /** + * Choose a database to connect to. Many databases do not support this. + * + * @param dbName is the name of the database to select + * @return true or false + */ + function SelectDB($dbName) + {return false;} + + + /** + * Will select, getting rows from $offset (1-based), for $nrows. + * This simulates the MySQL "select * from table limit $offset,$nrows" , and + * the PostgreSQL "select * from table limit $nrows offset $offset". Note that + * MySQL and PostgreSQL parameter ordering is the opposite of the other. + * eg. + * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based) + * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based) + * + * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set) + * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set + * + * @param sql + * @param [offset] is the row to start calculations from (1-based) + * @param [nrows] is the number of rows to get + * @param [inputarr] array of bind variables + * @param [secs2cache] is a private parameter only used by jlim + * @return the recordset ($rs->databaseType == 'array') + */ + function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) + { + if ($this->hasTop && $nrows > 0) { + // suggested by Reinhard Balling. Access requires top after distinct + // Informix requires first before distinct - F Riosa + $ismssql = (strpos($this->databaseType,'mssql') !== false); + if ($ismssql) $isaccess = false; + else $isaccess = (strpos($this->databaseType,'access') !== false); + + if ($offset <= 0) { + + // access includes ties in result + if ($isaccess) { + $sql = preg_replace( + '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql); + + if ($secs2cache>0) { + $ret =& $this->CacheExecute($secs2cache, $sql,$inputarr); + } else { + $ret =& $this->Execute($sql,$inputarr); + } + return $ret; // PHP5 fix + } else if ($ismssql){ + $sql = preg_replace( + '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql); + } else { + $sql = preg_replace( + '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql); + } + } else { + $nn = $nrows + $offset; + if ($isaccess || $ismssql) { + $sql = preg_replace( + '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql); + } else { + $sql = preg_replace( + '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql); + } + } + } + + // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows + // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS. + global $ADODB_COUNTRECS; + + $savec = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + + if ($offset>0){ + if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr); + else $rs = &$this->Execute($sql,$inputarr); + } else { + if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr); + else $rs = &$this->Execute($sql,$inputarr); + } + $ADODB_COUNTRECS = $savec; + if ($rs && !$rs->EOF) { + $rs =& $this->_rs2rs($rs,$nrows,$offset); + } + //print_r($rs); + return $rs; + } + + /** + * Create serializable recordset. Breaks rs link to connection. + * + * @param rs the recordset to serialize + */ + function SerializableRS(&$rs) + { + $rs2 =& $this->_rs2rs($rs); + $ignore = false; + $rs2->connection =& $ignore; + + return $rs2; + } + + /** + * Convert database recordset to an array recordset + * input recordset's cursor should be at beginning, and + * old $rs will be closed. + * + * @param rs the recordset to copy + * @param [nrows] number of rows to retrieve (optional) + * @param [offset] offset by number of rows (optional) + * @return the new recordset + */ + function _rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true) + { + if (! $rs) { + $false = false; + return $false; + } + $dbtype = $rs->databaseType; + if (!$dbtype) { + $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ? + return $rs; + } + if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) { + $rs->MoveFirst(); + $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ? + return $rs; + } + $flds = array(); + for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) { + $flds[] = $rs->FetchField($i); + } + + $arr =& $rs->GetArrayLimit($nrows,$offset); + //print_r($arr); + if ($close) $rs->Close(); + + $arrayClass = $this->arrayClass; + + $rs2 = new $arrayClass(); + $rs2->connection = &$this; + $rs2->sql = $rs->sql; + $rs2->dataProvider = $this->dataProvider; + $rs2->InitArrayFields($arr,$flds); + $rs2->fetchMode = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode; + return $rs2; + } + + /* + * Return all rows. Compat with PEAR DB + */ + function GetAll($sql, $inputarr=false) + { + $arr =& $this->GetArray($sql,$inputarr); + return $arr; + } + + function GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false) + { + $rs =& $this->Execute($sql, $inputarr); + if (!$rs) { + $false = false; + return $false; + } + $arr =& $rs->GetAssoc($force_array,$first2cols); + return $arr; + } + + function CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false) + { + if (!is_numeric($secs2cache)) { + $first2cols = $force_array; + $force_array = $inputarr; + } + $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr); + if (!$rs) { + $false = false; + return $false; + } + $arr =& $rs->GetAssoc($force_array,$first2cols); + return $arr; + } + + /** + * Return first element of first row of sql statement. Recordset is disposed + * for you. + * + * @param sql SQL statement + * @param [inputarr] input bind array + */ + function GetOne($sql,$inputarr=false) + { + global $ADODB_COUNTRECS; + $crecs = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + + $ret = false; + $rs = &$this->Execute($sql,$inputarr); + if ($rs) { + if (!$rs->EOF) $ret = reset($rs->fields); + $rs->Close(); + } + $ADODB_COUNTRECS = $crecs; + return $ret; + } + + function CacheGetOne($secs2cache,$sql=false,$inputarr=false) + { + $ret = false; + $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr); + if ($rs) { + if (!$rs->EOF) $ret = reset($rs->fields); + $rs->Close(); + } + + return $ret; + } + + function GetCol($sql, $inputarr = false, $trim = false) + { + $rv = false; + $rs = &$this->Execute($sql, $inputarr); + if ($rs) { + $rv = array(); + if ($trim) { + while (!$rs->EOF) { + $rv[] = trim(reset($rs->fields)); + $rs->MoveNext(); + } + } else { + while (!$rs->EOF) { + $rv[] = reset($rs->fields); + $rs->MoveNext(); + } + } + $rs->Close(); + } + return $rv; + } + + function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false) + { + $rv = false; + $rs = &$this->CacheExecute($secs, $sql, $inputarr); + if ($rs) { + if ($trim) { + while (!$rs->EOF) { + $rv[] = trim(reset($rs->fields)); + $rs->MoveNext(); + } + } else { + while (!$rs->EOF) { + $rv[] = reset($rs->fields); + $rs->MoveNext(); + } + } + $rs->Close(); + } + return $rv; + } + + /* + Calculate the offset of a date for a particular database and generate + appropriate SQL. Useful for calculating future/past dates and storing + in a database. + + If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour. + */ + function OffsetDate($dayFraction,$date=false) + { + if (!$date) $date = $this->sysDate; + return '('.$date.'+'.$dayFraction.')'; + } + + + /** + * + * @param sql SQL statement + * @param [inputarr] input bind array + */ + function GetArray($sql,$inputarr=false) + { + global $ADODB_COUNTRECS; + + $savec = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + $rs =& $this->Execute($sql,$inputarr); + $ADODB_COUNTRECS = $savec; + if (!$rs) + if (defined('ADODB_PEAR')) { + $cls = ADODB_PEAR_Error(); + return $cls; + } else { + $false = false; + return $false; + } + $arr =& $rs->GetArray(); + $rs->Close(); + return $arr; + } + + function CacheGetAll($secs2cache,$sql=false,$inputarr=false) + { + return $this->CacheGetArray($secs2cache,$sql,$inputarr); + } + + function CacheGetArray($secs2cache,$sql=false,$inputarr=false) + { + global $ADODB_COUNTRECS; + + $savec = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr); + $ADODB_COUNTRECS = $savec; + + if (!$rs) + if (defined('ADODB_PEAR')) { + $cls = ADODB_PEAR_Error(); + return $cls; + } else { + $false = false; + return $false; + } + $arr =& $rs->GetArray(); + $rs->Close(); + return $arr; + } + + + + /** + * Return one row of sql statement. Recordset is disposed for you. + * + * @param sql SQL statement + * @param [inputarr] input bind array + */ + function GetRow($sql,$inputarr=false) + { + global $ADODB_COUNTRECS; + $crecs = $ADODB_COUNTRECS; + $ADODB_COUNTRECS = false; + + $rs =& $this->Execute($sql,$inputarr); + + $ADODB_COUNTRECS = $crecs; + if ($rs) { + if (!$rs->EOF) $arr = $rs->fields; + else $arr = array(); + $rs->Close(); + return $arr; + } + + $false = false; + return $false; + } + + function CacheGetRow($secs2cache,$sql=false,$inputarr=false) + { + $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr); + if ($rs) { + $arr = false; + if (!$rs->EOF) $arr = $rs->fields; + $rs->Close(); + return $arr; + } + $false = false; + return $false; + } + + /** + * Insert or replace a single record. Note: this is not the same as MySQL's replace. + * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL. + * Also note that no table locking is done currently, so it is possible that the + * record be inserted twice by two programs... + * + * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname'); + * + * $table table name + * $fieldArray associative array of data (you must quote strings yourself). + * $keyCol the primary key field name or if compound key, array of field names + * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers + * but does not work with dates nor SQL functions. + * has_autoinc the primary key is an auto-inc field, so skip in insert. + * + * Currently blob replace not supported + * + * returns 0 = fail, 1 = update, 2 = insert + */ + + function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false) + { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php'); + + return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc); + } + + + /** + * Will select, getting rows from $offset (1-based), for $nrows. + * This simulates the MySQL "select * from table limit $offset,$nrows" , and + * the PostgreSQL "select * from table limit $nrows offset $offset". Note that + * MySQL and PostgreSQL parameter ordering is the opposite of the other. + * eg. + * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based) + * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based) + * + * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set + * + * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional + * @param sql + * @param [offset] is the row to start calculations from (1-based) + * @param [nrows] is the number of rows to get + * @param [inputarr] array of bind variables + * @return the recordset ($rs->databaseType == 'array') + */ + function CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false) + { + if (!is_numeric($secs2cache)) { + if ($sql === false) $sql = -1; + if ($offset == -1) $offset = false; + // sql, nrows, offset,inputarr + $rs =& $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs); + } else { + if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()"); + $rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + } + return $rs; + } + + + /** + * Flush cached recordsets that match a particular $sql statement. + * If $sql == false, then we purge all files in the cache. + */ + + /** + * Flush cached recordsets that match a particular $sql statement. + * If $sql == false, then we purge all files in the cache. + */ + function CacheFlush($sql=false,$inputarr=false) + { + global $ADODB_CACHE_DIR; + + if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) { + /*if (strncmp(PHP_OS,'WIN',3) === 0) + $dir = str_replace('/', '\\', $ADODB_CACHE_DIR); + else */ + $dir = $ADODB_CACHE_DIR; + + if ($this->debug) { + ADOConnection::outp( "CacheFlush: $dir
    \n", $this->_dirFlush($dir),"
    "); + } else { + $this->_dirFlush($dir); + } + return; + } + + global $ADODB_INCLUDED_CSV; + if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php'); + + $f = $this->_gencachename($sql.serialize($inputarr),false); + adodb_write_file($f,''); // is adodb_write_file needed? + if (!@unlink($f)) { + if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f"); + } + } + + /** + * Private function to erase all of the files and subdirectories in a directory. + * + * Just specify the directory, and tell it if you want to delete the directory or just clear it out. + * Note: $kill_top_level is used internally in the function to flush subdirectories. + */ + function _dirFlush($dir, $kill_top_level = false) { + if(!$dh = @opendir($dir)) return; + + while (($obj = readdir($dh))) { + if($obj=='.' || $obj=='..') + continue; + + if (!@unlink($dir.'/'.$obj)) + $this->_dirFlush($dir.'/'.$obj, true); + } + if ($kill_top_level === true) + @rmdir($dir); + return true; + } + + + function xCacheFlush($sql=false,$inputarr=false) + { + global $ADODB_CACHE_DIR; + + if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) { + if (strncmp(PHP_OS,'WIN',3) === 0) { + $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache'; + } else { + //$cmd = 'find "'.$ADODB_CACHE_DIR.'" -type f -maxdepth 1 -print0 | xargs -0 rm -f'; + $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/[0-9a-f][0-9a-f]/'; + // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`'; + } + if ($this->debug) { + ADOConnection::outp( "CacheFlush: $cmd
    \n", system($cmd),"
    "); + } else { + exec($cmd); + } + return; + } + + global $ADODB_INCLUDED_CSV; + if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php'); + + $f = $this->_gencachename($sql.serialize($inputarr),false); + adodb_write_file($f,''); // is adodb_write_file needed? + if (!@unlink($f)) { + if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f"); + } + } + + /** + * Private function to generate filename for caching. + * Filename is generated based on: + * + * - sql statement + * - database type (oci8, ibase, ifx, etc) + * - database name + * - userid + * - setFetchMode (adodb 4.23) + * + * When not in safe mode, we create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR). + * Assuming that we can have 50,000 files per directory with good performance, + * then we can scale to 12.8 million unique cached recordsets. Wow! + */ + function _gencachename($sql,$createdir) + { + global $ADODB_CACHE_DIR; + static $notSafeMode; + + if ($this->fetchMode === false) { + global $ADODB_FETCH_MODE; + $mode = $ADODB_FETCH_MODE; + } else { + $mode = $this->fetchMode; + } + $m = md5($sql.$this->databaseType.$this->database.$this->user.$mode); + + if (!isset($notSafeMode)) $notSafeMode = !ini_get('safe_mode'); + $dir = ($notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($m,0,2) : $ADODB_CACHE_DIR; + + if ($createdir && $notSafeMode && !file_exists($dir)) { + $oldu = umask(0); + if (!mkdir($dir,0771)) + if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql"); + umask($oldu); + } + return $dir.'/adodb_'.$m.'.cache'; + } + + + /** + * Execute SQL, caching recordsets. + * + * @param [secs2cache] seconds to cache data, set to 0 to force query. + * This is an optional parameter. + * @param sql SQL statement to execute + * @param [inputarr] holds the input data to bind to + * @return RecordSet or false + */ + function CacheExecute($secs2cache,$sql=false,$inputarr=false) + { + + + if (!is_numeric($secs2cache)) { + $inputarr = $sql; + $sql = $secs2cache; + $secs2cache = $this->cacheSecs; + } + + if (is_array($sql)) { + $sqlparam = $sql; + $sql = $sql[0]; + } else + $sqlparam = $sql; + + global $ADODB_INCLUDED_CSV; + if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php'); + + $md5file = $this->_gencachename($sql.serialize($inputarr),true); + $err = ''; + + if ($secs2cache > 0){ + $rs = &csv2rs($md5file,$err,$secs2cache,$this->arrayClass); + $this->numCacheHits += 1; + } else { + $err='Timeout 1'; + $rs = false; + $this->numCacheMisses += 1; + } + if (!$rs) { + // no cached rs found + if ($this->debug) { + if (get_magic_quotes_runtime()) { + ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :("); + } + if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)"); + } + + $rs = &$this->Execute($sqlparam,$inputarr); + + if ($rs) { + $eof = $rs->EOF; + $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately + $txt = _rs2serialize($rs,false,$sql); // serialize + + if (!adodb_write_file($md5file,$txt,$this->debug)) { + if ($fn = $this->raiseErrorFn) { + $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this); + } + if ($this->debug) ADOConnection::outp( " Cache write error"); + } + if ($rs->EOF && !$eof) { + $rs->MoveFirst(); + //$rs = &csv2rs($md5file,$err); + $rs->connection = &$this; // Pablo suggestion + } + + } else + @unlink($md5file); + } else { + $this->_errorMsg = ''; + $this->_errorCode = 0; + + if ($this->fnCacheExecute) { + $fn = $this->fnCacheExecute; + $fn($this, $secs2cache, $sql, $inputarr); + } + // ok, set cached object found + $rs->connection = &$this; // Pablo suggestion + if ($this->debug){ + + $inBrowser = isset($_SERVER['HTTP_USER_AGENT']); + $ttl = $rs->timeCreated + $secs2cache - time(); + $s = is_array($sql) ? $sql[0] : $sql; + if ($inBrowser) $s = ''.htmlspecialchars($s).''; + + ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]"); + } + } + return $rs; + } + + + /* + Similar to PEAR DB's autoExecute(), except that + $mode can be 'INSERT' or 'UPDATE' or DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE + If $mode == 'UPDATE', then $where is compulsory as a safety measure. + + $forceUpdate means that even if the data has not changed, perform update. + */ + function& AutoExecute($table, $fields_values, $mode = 'INSERT', $where = FALSE, $forceUpdate=true, $magicq=false) + { + $sql = 'SELECT * FROM '.$table; + if ($where!==FALSE) $sql .= ' WHERE '.$where; + else if ($mode == 'UPDATE' || $mode == 2 /* DB_AUTOQUERY_UPDATE */) { + ADOConnection::outp('AutoExecute: Illegal mode=UPDATE with empty WHERE clause'); + return false; + } + + $rs =& $this->SelectLimit($sql,1); + if (!$rs) return false; // table does not exist + $rs->tableName = $table; + + switch((string) $mode) { + case 'UPDATE': + case '2': + $sql = $this->GetUpdateSQL($rs, $fields_values, $forceUpdate, $magicq); + break; + case 'INSERT': + case '1': + $sql = $this->GetInsertSQL($rs, $fields_values, $magicq); + break; + default: + ADOConnection::outp("AutoExecute: Unknown mode=$mode"); + return false; + } + $ret = false; + if ($sql) $ret = $this->Execute($sql); + if ($ret) $ret = true; + return $ret; + } + + + /** + * Generates an Update Query based on an existing recordset. + * $arrFields is an associative array of fields with the value + * that should be assigned. + * + * Note: This function should only be used on a recordset + * that is run against a single table and sql should only + * be a simple select stmt with no groupby/orderby/limit + * + * "Jonathan Younger" + */ + function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=null) + { + global $ADODB_INCLUDED_LIB; + + //********************************************************// + //This is here to maintain compatibility + //with older adodb versions. Sets force type to force nulls if $forcenulls is set. + if (!isset($force)) { + global $ADODB_FORCE_TYPE; + $force = $ADODB_FORCE_TYPE; + } + //********************************************************// + + if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php'); + return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq,$force); + } + + + + + /** + * Generates an Insert Query based on an existing recordset. + * $arrFields is an associative array of fields with the value + * that should be assigned. + * + * Note: This function should only be used on a recordset + * that is run against a single table. + */ + function GetInsertSQL(&$rs, $arrFields,$magicq=false,$force=null) + { + global $ADODB_INCLUDED_LIB; + if (!isset($force)) { + global $ADODB_FORCE_TYPE; + $force = $ADODB_FORCE_TYPE; + + } + if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php'); + return _adodb_getinsertsql($this,$rs,$arrFields,$magicq,$force); + } + + + /** + * Update a blob column, given a where clause. There are more sophisticated + * blob handling functions that we could have implemented, but all require + * a very complex API. Instead we have chosen something that is extremely + * simple to understand and use. + * + * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course. + * + * Usage to update a $blobvalue which has a primary key blob_id=1 into a + * field blobtable.blobcolumn: + * + * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1'); + * + * Insert example: + * + * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); + * $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1'); + */ + + function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') + { + return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false; + } + + /** + * Usage: + * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1'); + * + * $blobtype supports 'BLOB' and 'CLOB' + * + * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); + * $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1'); + */ + function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') + { + $fd = fopen($path,'rb'); + if ($fd === false) return false; + $val = fread($fd,filesize($path)); + fclose($fd); + return $this->UpdateBlob($table,$column,$val,$where,$blobtype); + } + + function BlobDecode($blob) + { + return $blob; + } + + function BlobEncode($blob) + { + return $blob; + } + + function SetCharSet($charset) + { + return false; + } + + function IfNull( $field, $ifNull ) + { + return " CASE WHEN $field is null THEN $ifNull ELSE $field END "; + } + + function LogSQL($enable=true) + { + include_once(ADODB_DIR.'/adodb-perf.inc.php'); + + if ($enable) $this->fnExecute = 'adodb_log_sql'; + else $this->fnExecute = false; + + $old = $this->_logsql; + $this->_logsql = $enable; + if ($enable && !$old) $this->_affected = false; + return $old; + } + + function GetCharSet() + { + return false; + } + + /** + * Usage: + * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB'); + * + * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)'); + * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1'); + */ + function UpdateClob($table,$column,$val,$where) + { + return $this->UpdateBlob($table,$column,$val,$where,'CLOB'); + } + + // not the fastest implementation - quick and dirty - jlim + // for best performance, use the actual $rs->MetaType(). + function MetaType($t,$len=-1,$fieldobj=false) + { + + if (empty($this->_metars)) { + $rsclass = $this->rsPrefix.$this->databaseType; + $this->_metars = new $rsclass(false,$this->fetchMode); + } + + return $this->_metars->MetaType($t,$len,$fieldobj); + } + + + /** + * Change the SQL connection locale to a specified locale. + * This is used to get the date formats written depending on the client locale. + */ + function SetDateLocale($locale = 'En') + { + $this->locale = $locale; + switch (strtoupper($locale)) + { + case 'EN': + $this->fmtDate="'Y-m-d'"; + $this->fmtTimeStamp = "'Y-m-d H:i:s'"; + break; + + case 'US': + $this->fmtDate = "'m-d-Y'"; + $this->fmtTimeStamp = "'m-d-Y H:i:s'"; + break; + + case 'NL': + case 'FR': + case 'RO': + case 'IT': + $this->fmtDate="'d-m-Y'"; + $this->fmtTimeStamp = "'d-m-Y H:i:s'"; + break; + + case 'GE': + $this->fmtDate="'d.m.Y'"; + $this->fmtTimeStamp = "'d.m.Y H:i:s'"; + break; + + default: + $this->fmtDate="'Y-m-d'"; + $this->fmtTimeStamp = "'Y-m-d H:i:s'"; + break; + } + } + + + /** + * Close Connection + */ + function Close() + { + $rez = $this->_close(); + $this->_connectionID = false; + return $rez; + } + + /** + * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans(). + * + * @return true if succeeded or false if database does not support transactions + */ + function BeginTrans() {return false;} + + + /** + * If database does not support transactions, always return true as data always commited + * + * @param $ok set to false to rollback transaction, true to commit + * + * @return true/false. + */ + function CommitTrans($ok=true) + { return true;} + + + /** + * If database does not support transactions, rollbacks always fail, so return false + * + * @return true/false. + */ + function RollbackTrans() + { return false;} + + + /** + * return the databases that the driver can connect to. + * Some databases will return an empty array. + * + * @return an array of database names. + */ + function MetaDatabases() + { + global $ADODB_FETCH_MODE; + + if ($this->metaDatabasesSQL) { + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + + $arr = $this->GetCol($this->metaDatabasesSQL); + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + + return $arr; + } + + return false; + } + + /** + * @param ttype can either be 'VIEW' or 'TABLE' or false. + * If false, both views and tables are returned. + * "VIEW" returns only views + * "TABLE" returns only tables + * @param showSchema returns the schema/user with the table name, eg. USER.TABLE + * @param mask is the input mask - only supported by oci8 and postgresql + * + * @return array of tables for current database. + */ + function MetaTables($ttype=false,$showSchema=false,$mask=false) + { + global $ADODB_FETCH_MODE; + + + $false = false; + if ($mask) { + return $false; + } + if ($this->metaTablesSQL) { + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + + $rs = $this->Execute($this->metaTablesSQL); + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + + if ($rs === false) return $false; + $arr =& $rs->GetArray(); + $arr2 = array(); + + if ($hast = ($ttype && isset($arr[0][1]))) { + $showt = strncmp($ttype,'T',1); + } + + for ($i=0; $i < sizeof($arr); $i++) { + if ($hast) { + if ($showt == 0) { + if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]); + } else { + if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]); + } + } else + $arr2[] = trim($arr[$i][0]); + } + $rs->Close(); + return $arr2; + } + return $false; + } + + + function _findschema(&$table,&$schema) + { + if (!$schema && ($at = strpos($table,'.')) !== false) { + $schema = substr($table,0,$at); + $table = substr($table,$at+1); + } + } + + /** + * List columns in a database as an array of ADOFieldObjects. + * See top of file for definition of object. + * + * @param $table table name to query + * @param $normalize makes table name case-insensitive (required by some databases) + * @schema is optional database schema to use - not supported by all databases. + * + * @return array of ADOFieldObjects for current table. + */ + function MetaColumns($table,$normalize=true) + { + global $ADODB_FETCH_MODE; + + $false = false; + + if (!empty($this->metaColumnsSQL)) { + + $schema = false; + $this->_findschema($table,$schema); + + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + $rs = $this->Execute(sprintf($this->metaColumnsSQL,($normalize)?strtoupper($table):$table)); + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + if ($rs === false || $rs->EOF) return $false; + + $retarr = array(); + while (!$rs->EOF) { //print_r($rs->fields); + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[0]; + $fld->type = $rs->fields[1]; + if (isset($rs->fields[3]) && $rs->fields[3]) { + if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3]; + $fld->scale = $rs->fields[4]; + if ($fld->scale>0) $fld->max_length += 1; + } else + $fld->max_length = $rs->fields[2]; + + if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; + else $retarr[strtoupper($fld->name)] = $fld; + $rs->MoveNext(); + } + $rs->Close(); + return $retarr; + } + return $false; + } + + /** + * List indexes on a table as an array. + * @param table table name to query + * @param primary true to only show primary keys. Not actually used for most databases + * + * @return array of indexes on current table. Each element represents an index, and is itself an associative array. + + Array ( + [name_of_index] => Array + ( + [unique] => true or false + [columns] => Array + ( + [0] => firstname + [1] => lastname + ) + ) + */ + function MetaIndexes($table, $primary = false, $owner = false) + { + $false = false; + return $false; + } + + /** + * List columns names in a table as an array. + * @param table table name to query + * + * @return array of column names for current table. + */ + function MetaColumnNames($table, $numIndexes=false) + { + $objarr =& $this->MetaColumns($table); + if (!is_array($objarr)) { + $false = false; + return $false; + } + $arr = array(); + if ($numIndexes) { + $i = 0; + foreach($objarr as $v) $arr[$i++] = $v->name; + } else + foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name; + + return $arr; + } + + /** + * Different SQL databases used different methods to combine strings together. + * This function provides a wrapper. + * + * param s variable number of string parameters + * + * Usage: $db->Concat($str1,$str2); + * + * @return concatenated string + */ + function Concat() + { + $arr = func_get_args(); + return implode($this->concat_operator, $arr); + } + + + /** + * Converts a date "d" to a string that the database can understand. + * + * @param d a date in Unix date time format. + * + * @return date string in database date format + */ + function DBDate($d) + { + if (empty($d) && $d !== 0) return 'null'; + + if (is_string($d) && !is_numeric($d)) { + if ($d === 'null' || strncmp($d,"'",1) === 0) return $d; + if ($this->isoDates) return "'$d'"; + $d = ADOConnection::UnixDate($d); + } + + return adodb_date($this->fmtDate,$d); + } + + + /** + * Converts a timestamp "ts" to a string that the database can understand. + * + * @param ts a timestamp in Unix date time format. + * + * @return timestamp string in database timestamp format + */ + function DBTimeStamp($ts) + { + if (empty($ts) && $ts !== 0) return 'null'; + + # strlen(14) allows YYYYMMDDHHMMSS format + if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14)) + return adodb_date($this->fmtTimeStamp,$ts); + + if ($ts === 'null') return $ts; + if ($this->isoDates && strlen($ts) !== 14) return "'$ts'"; + + $ts = ADOConnection::UnixTimeStamp($ts); + return adodb_date($this->fmtTimeStamp,$ts); + } + + /** + * Also in ADORecordSet. + * @param $v is a date string in YYYY-MM-DD format + * + * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format + */ + function UnixDate($v) + { + if (is_object($v)) { + // odbtp support + //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 ) + return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year); + } + + if (is_numeric($v) && strlen($v) !== 8) return $v; + if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", + ($v), $rr)) return false; + + if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0; + // h-m-s-MM-DD-YY + return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); + } + + + /** + * Also in ADORecordSet. + * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format + * + * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format + */ + function UnixTimeStamp($v) + { + if (is_object($v)) { + // odbtp support + //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 ) + return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year); + } + + if (!preg_match( + "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", + ($v), $rr)) return false; + + if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0; + + // h-m-s-MM-DD-YY + if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); + return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]); + } + + /** + * Also in ADORecordSet. + * + * Format database date based on user defined format. + * + * @param v is the character date in YYYY-MM-DD format, returned by database + * @param fmt is the format to apply to it, using date() + * + * @return a date formated as user desires + */ + + function UserDate($v,$fmt='Y-m-d',$gmt=false) + { + $tt = $this->UnixDate($v); + + // $tt == -1 if pre TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) return $v; + else if ($tt == 0) return $this->emptyDate; + else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR + } + + return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt); + + } + + /** + * + * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format + * @param fmt is the format to apply to it, using date() + * + * @return a timestamp formated as user desires + */ + function UserTimeStamp($v,$fmt='Y-m-d H:i:s',$gmt=false) + { + if (!isset($v)) return $this->emptyTimeStamp; + # strlen(14) allows YYYYMMDDHHMMSS format + if (is_numeric($v) && strlen($v)<14) return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v); + $tt = $this->UnixTimeStamp($v); + // $tt == -1 if pre TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) return $v; + if ($tt == 0) return $this->emptyTimeStamp; + return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt); + } + + function escape($s,$magic_quotes=false) + { + return $this->addq($s,$magic_quotes); + } + + /** + * Quotes a string, without prefixing nor appending quotes. + */ + function addq($s,$magic_quotes=false) + { + if (!$magic_quotes) { + + if ($this->replaceQuote[0] == '\\'){ + // only since php 4.0.5 + $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s); + //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s)); + } + return str_replace("'",$this->replaceQuote,$s); + } + + // undo magic quotes for " + $s = str_replace('\\"','"',$s); + + if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything + return $s; + else {// change \' to '' for sybase/mssql + $s = str_replace('\\\\','\\',$s); + return str_replace("\\'",$this->replaceQuote,$s); + } + } + + /** + * Correctly quotes a string so that all strings are escaped. We prefix and append + * to the string single-quotes. + * An example is $db->qstr("Don't bother",magic_quotes_runtime()); + * + * @param s the string to quote + * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc(). + * This undoes the stupidity of magic quotes for GPC. + * + * @return quoted string to be sent back to database + */ + function qstr($s,$magic_quotes=false) + { + if (!$magic_quotes) { + + if ($this->replaceQuote[0] == '\\'){ + // only since php 4.0.5 + $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s); + //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s)); + } + return "'".str_replace("'",$this->replaceQuote,$s)."'"; + } + + // undo magic quotes for " + $s = str_replace('\\"','"',$s); + + if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything + return "'$s'"; + else {// change \' to '' for sybase/mssql + $s = str_replace('\\\\','\\',$s); + return "'".str_replace("\\'",$this->replaceQuote,$s)."'"; + } + } + + + /** + * Will select the supplied $page number from a recordset, given that it is paginated in pages of + * $nrows rows per page. It also saves two boolean values saying if the given page is the first + * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination. + * + * See readme.htm#ex8 for an example of usage. + * + * @param sql + * @param nrows is the number of rows per page to get + * @param page is the page number to get (1-based) + * @param [inputarr] array of bind variables + * @param [secs2cache] is a private parameter only used by jlim + * @return the recordset ($rs->databaseType == 'array') + * + * NOTE: phpLens uses a different algorithm and does not use PageExecute(). + * + */ + function PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0) + { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php'); + if ($this->pageExecuteCountRows) $rs =& _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache); + else $rs =& _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache); + return $rs; + } + + + /** + * Will select the supplied $page number from a recordset, given that it is paginated in pages of + * $nrows rows per page. It also saves two boolean values saying if the given page is the first + * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination. + * + * @param secs2cache seconds to cache data, set to 0 to force query + * @param sql + * @param nrows is the number of rows per page to get + * @param page is the page number to get (1-based) + * @param [inputarr] array of bind variables + * @return the recordset ($rs->databaseType == 'array') + */ + function CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false) + { + /*switch($this->dataProvider) { + case 'postgres': + case 'mysql': + break; + default: $secs2cache = 0; break; + }*/ + $rs =& $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache); + return $rs; + } + +} // end class ADOConnection + + + + //============================================================================================== + // CLASS ADOFetchObj + //============================================================================================== + + /** + * Internal placeholder for record objects. Used by ADORecordSet->FetchObj(). + */ + class ADOFetchObj { + }; + + //============================================================================================== + // CLASS ADORecordSet_empty + //============================================================================================== + + /** + * Lightweight recordset when there are no records to be returned + */ + class ADORecordSet_empty + { + var $dataProvider = 'empty'; + var $databaseType = false; + var $EOF = true; + var $_numOfRows = 0; + var $fields = false; + var $connection = false; + function RowCount() {return 0;} + function RecordCount() {return 0;} + function PO_RecordCount(){return 0;} + function Close(){return true;} + function FetchRow() {return false;} + function FieldCount(){ return 0;} + function Init() {} + } + + //============================================================================================== + // DATE AND TIME FUNCTIONS + //============================================================================================== + include_once(ADODB_DIR.'/adodb-time.inc.php'); + + //============================================================================================== + // CLASS ADORecordSet + //============================================================================================== + + if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php'); + else include_once(ADODB_DIR.'/adodb-iterator.inc.php'); + /** + * RecordSet class that represents the dataset returned by the database. + * To keep memory overhead low, this class holds only the current row in memory. + * No prefetching of data is done, so the RecordCount() can return -1 ( which + * means recordcount not known). + */ + class ADORecordSet extends ADODB_BASE_RS { + /* + * public variables + */ + var $dataProvider = "native"; + var $fields = false; /// holds the current row data + var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob + /// in other words, we use a text area for editing. + var $canSeek = false; /// indicates that seek is supported + var $sql; /// sql text + var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object. + + var $emptyTimeStamp = ' '; /// what to display when $time==0 + var $emptyDate = ' '; /// what to display when $time==0 + var $debug = false; + var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets + + var $bind = false; /// used by Fields() to hold array - should be private? + var $fetchMode; /// default fetch mode + var $connection = false; /// the parent connection + /* + * private variables + */ + var $_numOfRows = -1; /** number of rows, or -1 */ + var $_numOfFields = -1; /** number of fields in recordset */ + var $_queryID = -1; /** This variable keeps the result link identifier. */ + var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */ + var $_closed = false; /** has recordset been closed */ + var $_inited = false; /** Init() should only be called once */ + var $_obj; /** Used by FetchObj */ + var $_names; /** Used by FetchObj */ + + var $_currentPage = -1; /** Added by Iván Oliva to implement recordset pagination */ + var $_atFirstPage = false; /** Added by Iván Oliva to implement recordset pagination */ + var $_atLastPage = false; /** Added by Iván Oliva to implement recordset pagination */ + var $_lastPageNo = -1; + var $_maxRecordCount = 0; + var $datetime = false; + + /** + * Constructor + * + * @param queryID this is the queryID returned by ADOConnection->_query() + * + */ + function __construct($queryID) + { + $this->_queryID = $queryID; + } + + function ADORecordSet($queryID) + { + $this->_queryID = $queryID; + } + + function Init() + { + if ($this->_inited) return; + $this->_inited = true; + if ($this->_queryID) @$this->_initrs(); + else { + $this->_numOfRows = 0; + $this->_numOfFields = 0; + } + if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) { + + $this->_currentRow = 0; + if ($this->EOF = ($this->_fetch() === false)) { + $this->_numOfRows = 0; // _numOfRows could be -1 + } + } else { + $this->EOF = true; + } + } + + + /** + * Generate a SELECT tag string from a recordset, and return the string. + * If the recordset has 2 cols, we treat the 1st col as the containing + * the text to display to the user, and 2nd col as the return value. Default + * strings are compared with the FIRST column. + * + * @param name name of SELECT tag + * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox. + * @param [blank1stItem] true to leave the 1st item in list empty + * @param [multiple] true for listbox, false for popup + * @param [size] #rows to show for listbox. not used by popup + * @param [selectAttr] additional attributes to defined for SELECT tag. + * useful for holding javascript onChange='...' handlers. + & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with + * column 0 (1st col) if this is true. This is not documented. + * + * @return HTML + * + * changes by glen.davies@cce.ac.nz to support multiple hilited items + */ + function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false, + $size=0, $selectAttr='',$compareFields0=true) + { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php'); + return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple, + $size, $selectAttr,$compareFields0); + } + + + + /** + * Generate a SELECT tag string from a recordset, and return the string. + * If the recordset has 2 cols, we treat the 1st col as the containing + * the text to display to the user, and 2nd col as the return value. Default + * strings are compared with the SECOND column. + * + */ + function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='') + { + return $this->GetMenu($name,$defstr,$blank1stItem,$multiple, + $size, $selectAttr,false); + } + + /* + Grouped Menu + */ + function GetMenu3($name,$defstr='',$blank1stItem=true,$multiple=false, + $size=0, $selectAttr='') + { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php'); + return _adodb_getmenu_gp($this, $name,$defstr,$blank1stItem,$multiple, + $size, $selectAttr,false); + } + + /** + * return recordset as a 2-dimensional array. + * + * @param [nRows] is the number of rows to return. -1 means every row. + * + * @return an array indexed by the rows (0-based) from the recordset + */ + function GetArray($nRows = -1) + { + global $ADODB_EXTENSION; if ($ADODB_EXTENSION) { + $results = adodb_getall($this,$nRows); + return $results; + } + $results = array(); + $cnt = 0; + while (!$this->EOF && $nRows != $cnt) { + $results[] = $this->fields; + $this->MoveNext(); + $cnt++; + } + return $results; + } + + function GetAll($nRows = -1) + { + $arr =& $this->GetArray($nRows); + return $arr; + } + + /* + * Some databases allow multiple recordsets to be returned. This function + * will return true if there is a next recordset, or false if no more. + */ + function NextRecordSet() + { + return false; + } + + /** + * return recordset as a 2-dimensional array. + * Helper function for ADOConnection->SelectLimit() + * + * @param offset is the row to start calculations from (1-based) + * @param [nrows] is the number of rows to return + * + * @return an array indexed by the rows (0-based) from the recordset + */ + function GetArrayLimit($nrows,$offset=-1) + { + if ($offset <= 0) { + $arr =& $this->GetArray($nrows); + return $arr; + } + + $this->Move($offset); + + $results = array(); + $cnt = 0; + while (!$this->EOF && $nrows != $cnt) { + $results[$cnt++] = $this->fields; + $this->MoveNext(); + } + + return $results; + } + + + /** + * Synonym for GetArray() for compatibility with ADO. + * + * @param [nRows] is the number of rows to return. -1 means every row. + * + * @return an array indexed by the rows (0-based) from the recordset + */ + function GetRows($nRows = -1) + { + $arr =& $this->GetArray($nRows); + return $arr; + } + + /** + * return whole recordset as a 2-dimensional associative array if there are more than 2 columns. + * The first column is treated as the key and is not included in the array. + * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless + * $force_array == true. + * + * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional + * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing, + * read the source. + * + * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and + * instead of returning array[col0] => array(remaining cols), return array[col0] => col1 + * + * @return an associative array indexed by the first column of the array, + * or false if the data has less than 2 cols. + */ + function GetAssoc($force_array = false, $first2cols = false) + { + global $ADODB_EXTENSION; + + $cols = $this->_numOfFields; + if ($cols < 2) { + $false = false; + return $false; + } + $numIndex = isset($this->fields[0]); + $results = array(); + + if (!$first2cols && ($cols > 2 || $force_array)) { + if ($ADODB_EXTENSION) { + if ($numIndex) { + while (!$this->EOF) { + $results[trim($this->fields[0])] = array_slice($this->fields, 1); + adodb_movenext($this); + } + } else { + while (!$this->EOF) { + $results[trim(reset($this->fields))] = array_slice($this->fields, 1); + adodb_movenext($this); + } + } + } else { + if ($numIndex) { + while (!$this->EOF) { + $results[trim($this->fields[0])] = array_slice($this->fields, 1); + $this->MoveNext(); + } + } else { + while (!$this->EOF) { + $results[trim(reset($this->fields))] = array_slice($this->fields, 1); + $this->MoveNext(); + } + } + } + } else { + if ($ADODB_EXTENSION) { + // return scalar values + if ($numIndex) { + while (!$this->EOF) { + // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string + $results[trim(($this->fields[0]))] = $this->fields[1]; + adodb_movenext($this); + } + } else { + while (!$this->EOF) { + // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string + $v1 = trim(reset($this->fields)); + $v2 = ''.next($this->fields); + $results[$v1] = $v2; + adodb_movenext($this); + } + } + } else { + if ($numIndex) { + while (!$this->EOF) { + // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string + $results[trim(($this->fields[0]))] = $this->fields[1]; + $this->MoveNext(); + } + } else { + while (!$this->EOF) { + // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string + $v1 = trim(reset($this->fields)); + $v2 = ''.next($this->fields); + $results[$v1] = $v2; + $this->MoveNext(); + } + } + } + } + + $ref =& $results; # workaround accelerator incompat with PHP 4.4 :( + return $ref; + } + + + /** + * + * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format + * @param fmt is the format to apply to it, using date() + * + * @return a timestamp formated as user desires + */ + function UserTimeStamp($v,$fmt='Y-m-d H:i:s') + { + if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v); + $tt = $this->UnixTimeStamp($v); + // $tt == -1 if pre TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) return $v; + if ($tt === 0) return $this->emptyTimeStamp; + return adodb_date($fmt,$tt); + } + + + /** + * @param v is the character date in YYYY-MM-DD format, returned by database + * @param fmt is the format to apply to it, using date() + * + * @return a date formated as user desires + */ + function UserDate($v,$fmt='Y-m-d') + { + $tt = $this->UnixDate($v); + // $tt == -1 if pre TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) return $v; + else if ($tt == 0) return $this->emptyDate; + else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR + } + return adodb_date($fmt,$tt); + } + + + /** + * @param $v is a date string in YYYY-MM-DD format + * + * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format + */ + function UnixDate($v) + { + return ADOConnection::UnixDate($v); + } + + + /** + * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format + * + * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format + */ + function UnixTimeStamp($v) + { + return ADOConnection::UnixTimeStamp($v); + } + + + /** + * PEAR DB Compat - do not use internally + */ + function Free() + { + return $this->Close(); + } + + + /** + * PEAR DB compat, number of rows + */ + function NumRows() + { + return $this->_numOfRows; + } + + + /** + * PEAR DB compat, number of cols + */ + function NumCols() + { + return $this->_numOfFields; + } + + /** + * Fetch a row, returning false if no more rows. + * This is PEAR DB compat mode. + * + * @return false or array containing the current record + */ + function FetchRow() + { + if ($this->EOF) { + $false = false; + return $false; + } + $arr = $this->fields; + $this->_currentRow++; + if (!$this->_fetch()) $this->EOF = true; + return $arr; + } + + + /** + * Fetch a row, returning PEAR_Error if no more rows. + * This is PEAR DB compat mode. + * + * @return DB_OK or error object + */ + function FetchInto(&$arr) + { + if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false; + $arr = $this->fields; + $this->MoveNext(); + return 1; // DB_OK + } + + + /** + * Move to the first row in the recordset. Many databases do NOT support this. + * + * @return true or false + */ + function MoveFirst() + { + if ($this->_currentRow == 0) return true; + return $this->Move(0); + } + + + /** + * Move to the last row in the recordset. + * + * @return true or false + */ + function MoveLast() + { + if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1); + if ($this->EOF) return false; + while (!$this->EOF) { + $f = $this->fields; + $this->MoveNext(); + } + $this->fields = $f; + $this->EOF = false; + return true; + } + + + /** + * Move to next record in the recordset. + * + * @return true if there still rows available, or false if there are no more rows (EOF). + */ + function MoveNext() + { + if (!$this->EOF) { + $this->_currentRow++; + if ($this->_fetch()) return true; + } + $this->EOF = true; + /* -- tested error handling when scrolling cursor -- seems useless. + $conn = $this->connection; + if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) { + $fn = $conn->raiseErrorFn; + $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database); + } + */ + return false; + } + + + /** + * Random access to a specific row in the recordset. Some databases do not support + * access to previous rows in the databases (no scrolling backwards). + * + * @param rowNumber is the row to move to (0-based) + * + * @return true if there still rows available, or false if there are no more rows (EOF). + */ + function Move($rowNumber = 0) + { + $this->EOF = false; + if ($rowNumber == $this->_currentRow) return true; + if ($rowNumber >= $this->_numOfRows) + if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2; + + if ($this->canSeek) { + + if ($this->_seek($rowNumber)) { + $this->_currentRow = $rowNumber; + if ($this->_fetch()) { + return true; + } + } else { + $this->EOF = true; + return false; + } + } else { + if ($rowNumber < $this->_currentRow) return false; + global $ADODB_EXTENSION; + if ($ADODB_EXTENSION) { + while (!$this->EOF && $this->_currentRow < $rowNumber) { + adodb_movenext($this); + } + } else { + + while (! $this->EOF && $this->_currentRow < $rowNumber) { + $this->_currentRow++; + + if (!$this->_fetch()) $this->EOF = true; + } + } + return !($this->EOF); + } + + $this->fields = false; + $this->EOF = true; + return false; + } + + + /** + * Get the value of a field in the current row by column name. + * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM. + * + * @param colname is the field to access + * + * @return the value of $colname column + */ + function Fields($colname) + { + return $this->fields[$colname]; + } + + function GetAssocKeys($upper=true) + { + $this->bind = array(); + for ($i=0; $i < $this->_numOfFields; $i++) { + $o = $this->FetchField($i); + if ($upper === 2) $this->bind[$o->name] = $i; + else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i; + } + } + + /** + * Use associative array to get fields array for databases that do not support + * associative arrays. Submitted by Paolo S. Asioli paolo.asioli#libero.it + * + * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC + * before you execute your SQL statement, and access $rs->fields['col'] directly. + * + * $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField + */ + function GetRowAssoc($upper=1) + { + $record = array(); + // if (!$this->fields) return $record; + + if (!$this->bind) { + $this->GetAssocKeys($upper); + } + + foreach($this->bind as $k => $v) { + $record[$k] = $this->fields[$v]; + } + + return $record; + } + + + /** + * Clean up recordset + * + * @return true or false + */ + function Close() + { + // free connection object - this seems to globally free the object + // and not merely the reference, so don't do this... + // $this->connection = false; + if (!$this->_closed) { + $this->_closed = true; + return $this->_close(); + } else + return true; + } + + /** + * synonyms RecordCount and RowCount + * + * @return the number of rows or -1 if this is not supported + */ + function RecordCount() {return $this->_numOfRows;} + + + /* + * If we are using PageExecute(), this will return the maximum possible rows + * that can be returned when paging a recordset. + */ + function MaxRecordCount() + { + return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount(); + } + + /** + * synonyms RecordCount and RowCount + * + * @return the number of rows or -1 if this is not supported + */ + function RowCount() {return $this->_numOfRows;} + + + /** + * Portable RecordCount. Pablo Roca + * + * @return the number of records from a previous SELECT. All databases support this. + * + * But aware possible problems in multiuser environments. For better speed the table + * must be indexed by the condition. Heavy test this before deploying. + */ + function PO_RecordCount($table="", $condition="") { + + $lnumrows = $this->_numOfRows; + // the database doesn't support native recordcount, so we do a workaround + if ($lnumrows == -1 && $this->connection) { + IF ($table) { + if ($condition) $condition = " WHERE " . $condition; + $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition"); + if ($resultrows) $lnumrows = reset($resultrows->fields); + } + } + return $lnumrows; + } + + /** + * @return the current row in the recordset. If at EOF, will return the last row. 0-based. + */ + function CurrentRow() {return $this->_currentRow;} + + /** + * synonym for CurrentRow -- for ADO compat + * + * @return the current row in the recordset. If at EOF, will return the last row. 0-based. + */ + function AbsolutePosition() {return $this->_currentRow;} + + /** + * @return the number of columns in the recordset. Some databases will set this to 0 + * if no records are returned, others will return the number of columns in the query. + */ + function FieldCount() {return $this->_numOfFields;} + + + /** + * Get the ADOFieldObject of a specific column. + * + * @param fieldoffset is the column position to access(0-based). + * + * @return the ADOFieldObject for that column, or false. + */ + function FetchField($fieldoffset) + { + // must be defined by child class + } + + /** + * Get the ADOFieldObjects of all columns in an array. + * + */ + function& FieldTypesArray() + { + $arr = array(); + for ($i=0, $max=$this->_numOfFields; $i < $max; $i++) + $arr[] = $this->FetchField($i); + return $arr; + } + + /** + * Return the fields array of the current row as an object for convenience. + * The default case is lowercase field names. + * + * @return the object with the properties set to the fields of the current row + */ + function FetchObj() + { + $o =& $this->FetchObject(false); + return $o; + } + + /** + * Return the fields array of the current row as an object for convenience. + * The default case is uppercase. + * + * @param $isupper to set the object property names to uppercase + * + * @return the object with the properties set to the fields of the current row + */ + function FetchObject($isupper=true) + { + if (empty($this->_obj)) { + $this->_obj = new ADOFetchObj(); + $this->_names = array(); + for ($i=0; $i <$this->_numOfFields; $i++) { + $f = $this->FetchField($i); + $this->_names[] = $f->name; + } + } + $i = 0; + if (PHP_VERSION >= 5) $o = clone($this->_obj); + else $o = $this->_obj; + + for ($i=0; $i <$this->_numOfFields; $i++) { + $name = $this->_names[$i]; + if ($isupper) $n = strtoupper($name); + else $n = $name; + + $o->$n = $this->Fields($name); + } + return $o; + } + + /** + * Return the fields array of the current row as an object for convenience. + * The default is lower-case field names. + * + * @return the object with the properties set to the fields of the current row, + * or false if EOF + * + * Fixed bug reported by tim@orotech.net + */ + function FetchNextObj() + { + $o =& $this->FetchNextObject(false); + return $o; + } + + + /** + * Return the fields array of the current row as an object for convenience. + * The default is upper case field names. + * + * @param $isupper to set the object property names to uppercase + * + * @return the object with the properties set to the fields of the current row, + * or false if EOF + * + * Fixed bug reported by tim@orotech.net + */ + function FetchNextObject($isupper=true) + { + $o = false; + if ($this->_numOfRows != 0 && !$this->EOF) { + $o = $this->FetchObject($isupper); + $this->_currentRow++; + if ($this->_fetch()) return $o; + } + $this->EOF = true; + return $o; + } + + /** + * Get the metatype of the column. This is used for formatting. This is because + * many databases use different names for the same type, so we transform the original + * type to our standardised version which uses 1 character codes: + * + * @param t is the type passed in. Normally is ADOFieldObject->type. + * @param len is the maximum length of that field. This is because we treat character + * fields bigger than a certain size as a 'B' (blob). + * @param fieldobj is the field object returned by the database driver. Can hold + * additional info (eg. primary_key for mysql). + * + * @return the general type of the data: + * C for character < 250 chars + * X for teXt (>= 250 chars) + * B for Binary + * N for numeric or floating point + * D for date + * T for timestamp + * L for logical/Boolean + * I for integer + * R for autoincrement counter/integer + * + * + */ + function MetaType($t,$len=-1,$fieldobj=false) + { + if (is_object($t)) { + $fieldobj = $t; + $t = $fieldobj->type; + $len = $fieldobj->max_length; + } + // changed in 2.32 to hashing instead of switch stmt for speed... + static $typeMap = array( + 'VARCHAR' => 'C', + 'VARCHAR2' => 'C', + 'CHAR' => 'C', + 'C' => 'C', + 'STRING' => 'C', + 'NCHAR' => 'C', + 'NVARCHAR' => 'C', + 'VARYING' => 'C', + 'BPCHAR' => 'C', + 'CHARACTER' => 'C', + 'INTERVAL' => 'C', # Postgres + ## + 'LONGCHAR' => 'X', + 'TEXT' => 'X', + 'NTEXT' => 'X', + 'M' => 'X', + 'X' => 'X', + 'CLOB' => 'X', + 'NCLOB' => 'X', + 'LVARCHAR' => 'X', + ## + 'BLOB' => 'B', + 'IMAGE' => 'B', + 'BINARY' => 'B', + 'VARBINARY' => 'B', + 'LONGBINARY' => 'B', + 'B' => 'B', + ## + 'YEAR' => 'D', // mysql + 'DATE' => 'D', + 'D' => 'D', + ## + 'TIME' => 'T', + 'TIMESTAMP' => 'T', + 'DATETIME' => 'T', + 'TIMESTAMPTZ' => 'T', + 'T' => 'T', + ## + 'BOOL' => 'L', + 'BOOLEAN' => 'L', + 'BIT' => 'L', + 'L' => 'L', + ## + 'COUNTER' => 'R', + 'R' => 'R', + 'SERIAL' => 'R', // ifx + 'INT IDENTITY' => 'R', + ## + 'INT' => 'I', + 'INT2' => 'I', + 'INT4' => 'I', + 'INT8' => 'I', + 'INTEGER' => 'I', + 'INTEGER UNSIGNED' => 'I', + 'SHORT' => 'I', + 'TINYINT' => 'I', + 'SMALLINT' => 'I', + 'I' => 'I', + ## + 'LONG' => 'N', // interbase is numeric, oci8 is blob + 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers + 'DECIMAL' => 'N', + 'DEC' => 'N', + 'REAL' => 'N', + 'DOUBLE' => 'N', + 'DOUBLE PRECISION' => 'N', + 'SMALLFLOAT' => 'N', + 'FLOAT' => 'N', + 'NUMBER' => 'N', + 'NUM' => 'N', + 'NUMERIC' => 'N', + 'MONEY' => 'N', + + ## informix 9.2 + 'SQLINT' => 'I', + 'SQLSERIAL' => 'I', + 'SQLSMINT' => 'I', + 'SQLSMFLOAT' => 'N', + 'SQLFLOAT' => 'N', + 'SQLMONEY' => 'N', + 'SQLDECIMAL' => 'N', + 'SQLDATE' => 'D', + 'SQLVCHAR' => 'C', + 'SQLCHAR' => 'C', + 'SQLDTIME' => 'T', + 'SQLINTERVAL' => 'N', + 'SQLBYTES' => 'B', + 'SQLTEXT' => 'X' + ); + + $tmap = false; + $t = strtoupper($t); + $tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N'; + switch ($tmap) { + case 'C': + + // is the char field is too long, return as text field... + if ($this->blobSize >= 0) { + if ($len > $this->blobSize) return 'X'; + } else if ($len > 250) { + return 'X'; + } + return 'C'; + + case 'I': + if (!empty($fieldobj->primary_key)) return 'R'; + return 'I'; + + case false: + return 'N'; + + case 'B': + if (isset($fieldobj->binary)) + return ($fieldobj->binary) ? 'B' : 'X'; + return 'B'; + + case 'D': + if (!empty($this->connection) && !empty($this->connection->datetime)) return 'T'; + return 'D'; + + default: + if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B'; + return $tmap; + } + } + + function _close() {} + + /** + * set/returns the current recordset page when paginating + */ + function AbsolutePage($page=-1) + { + if ($page != -1) $this->_currentPage = $page; + return $this->_currentPage; + } + + /** + * set/returns the status of the atFirstPage flag when paginating + */ + function AtFirstPage($status=false) + { + if ($status != false) $this->_atFirstPage = $status; + return $this->_atFirstPage; + } + + function LastPageNo($page = false) + { + if ($page != false) $this->_lastPageNo = $page; + return $this->_lastPageNo; + } + + /** + * set/returns the status of the atLastPage flag when paginating + */ + function AtLastPage($status=false) + { + if ($status != false) $this->_atLastPage = $status; + return $this->_atLastPage; + } + +} // end class ADORecordSet + + //============================================================================================== + // CLASS ADORecordSet_array + //============================================================================================== + + /** + * This class encapsulates the concept of a recordset created in memory + * as an array. This is useful for the creation of cached recordsets. + * + * Note that the constructor is different from the standard ADORecordSet + */ + + class ADORecordSet_array extends ADORecordSet + { + var $databaseType = 'array'; + + var $_array; // holds the 2-dimensional data array + var $_types; // the array of types of each column (C B I L M) + var $_colnames; // names of each column in array + var $_skiprow1; // skip 1st row because it holds column names + var $_fieldarr; // holds array of field objects + var $canSeek = true; + var $affectedrows = false; + var $insertid = false; + var $sql = ''; + var $compat = false; + /** + * Constructor + * + */ + function __construct($fakeid=1) + { + global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH; + + // fetch() on EOF does not delete $this->fields + $this->compat = !empty($ADODB_COMPAT_FETCH); + $this->ADORecordSet($fakeid); // fake queryID + $this->fetchMode = $ADODB_FETCH_MODE; + } + + + /** + * Setup the array. + * + * @param array is a 2-dimensional array holding the data. + * The first row should hold the column names + * unless paramter $colnames is used. + * @param typearr holds an array of types. These are the same types + * used in MetaTypes (C,B,L,I,N). + * @param [colnames] array of column names. If set, then the first row of + * $array should not hold the column names. + */ + function InitArray($array,$typearr,$colnames=false) + { + $this->_array = $array; + $this->_types = $typearr; + if ($colnames) { + $this->_skiprow1 = false; + $this->_colnames = $colnames; + } else { + $this->_skiprow1 = true; + $this->_colnames = $array[0]; + } + $this->Init(); + } + /** + * Setup the Array and datatype file objects + * + * @param array is a 2-dimensional array holding the data. + * The first row should hold the column names + * unless paramter $colnames is used. + * @param fieldarr holds an array of ADOFieldObject's. + */ + function InitArrayFields(&$array,&$fieldarr) + { + $this->_array =& $array; + $this->_skiprow1= false; + if ($fieldarr) { + $this->_fieldobjects =& $fieldarr; + } + $this->Init(); + } + + function GetArray($nRows=-1) + { + if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) { + return $this->_array; + } else { + $arr =& ADORecordSet::GetArray($nRows); + return $arr; + } + } + + function _initrs() + { + $this->_numOfRows = sizeof($this->_array); + if ($this->_skiprow1) $this->_numOfRows -= 1; + + $this->_numOfFields =(isset($this->_fieldobjects)) ? + sizeof($this->_fieldobjects):sizeof($this->_types); + } + + /* Use associative array to get fields array */ + function Fields($colname) + { + $mode = isset($this->adodbFetchMode) ? $this->adodbFetchMode : $this->fetchMode; + + if ($mode & ADODB_FETCH_ASSOC) { + if (!isset($this->fields[$colname])) $colname = strtolower($colname); + return $this->fields[$colname]; + } + if (!$this->bind) { + $this->bind = array(); + for ($i=0; $i < $this->_numOfFields; $i++) { + $o = $this->FetchField($i); + $this->bind[strtoupper($o->name)] = $i; + } + } + return $this->fields[$this->bind[strtoupper($colname)]]; + } + + function FetchField($fieldOffset = -1) + { + if (isset($this->_fieldobjects)) { + return $this->_fieldobjects[$fieldOffset]; + } + $o = new ADOFieldObject(); + $o->name = $this->_colnames[$fieldOffset]; + $o->type = $this->_types[$fieldOffset]; + $o->max_length = -1; // length not known + + return $o; + } + + function _seek($row) + { + if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) { + $this->_currentRow = $row; + if ($this->_skiprow1) $row += 1; + $this->fields = $this->_array[$row]; + return true; + } + return false; + } + + function MoveNext() + { + if (!$this->EOF) { + $this->_currentRow++; + + $pos = $this->_currentRow; + + if ($this->_numOfRows <= $pos) { + if (!$this->compat) $this->fields = false; + } else { + if ($this->_skiprow1) $pos += 1; + $this->fields = $this->_array[$pos]; + return true; + } + $this->EOF = true; + } + + return false; + } + + function _fetch() + { + $pos = $this->_currentRow; + + if ($this->_numOfRows <= $pos) { + if (!$this->compat) $this->fields = false; + return false; + } + if ($this->_skiprow1) $pos += 1; + $this->fields = $this->_array[$pos]; + return true; + } + + function _close() + { + return true; + } + + } // ADORecordSet_array + + //============================================================================================== + // HELPER FUNCTIONS + //============================================================================================== + + /** + * Synonym for ADOLoadCode. Private function. Do not use. + * + * @deprecated + */ + function ADOLoadDB($dbType) + { + return ADOLoadCode($dbType); + } + + /** + * Load the code for a specific database driver. Private function. Do not use. + */ + function ADOLoadCode($dbType) + { + global $ADODB_LASTDB; + + if (!$dbType) return false; + $db = strtolower($dbType); + switch ($db) { + case 'ado': + if (PHP_VERSION >= 5) $db = 'ado5'; + $class = 'ado'; + break; + case 'ifx': + case 'maxsql': $class = $db = 'mysqlt'; break; + case 'postgres': + case 'postgres8': + case 'pgsql': $class = $db = 'postgres7'; break; + default: + $class = $db; break; + } + + $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php"; + @include_once($file); + $ADODB_LASTDB = $class; + if (class_exists("ADODB_" . $class)) return $class; + + //ADOConnection::outp(adodb_pr(get_declared_classes(),true)); + if (!file_exists($file)) ADOConnection::outp("Missing file: $file"); + else ADOConnection::outp("Syntax error in file: $file"); + return false; + } + + /** + * synonym for ADONewConnection for people like me who cannot remember the correct name + */ + function NewADOConnection($db='') + { + $tmp =& ADONewConnection($db); + return $tmp; + } + + /** + * Instantiate a new Connection class for a specific database driver. + * + * @param [db] is the database Connection object to create. If undefined, + * use the last database driver that was loaded by ADOLoadCode(). + * + * @return the freshly created instance of the Connection class. + */ + function ADONewConnection($db='') + { + GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB; + + if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2); + $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false; + $false = false; + if ($at = strpos($db,'://')) { + $origdsn = $db; + if (PHP_VERSION < 5) $dsna = @parse_url($db); + else { + $fakedsn = 'fake'.substr($db,$at); + $dsna = @parse_url($fakedsn); + $dsna['scheme'] = substr($db,0,$at); + + if (strncmp($db,'pdo',3) == 0) { + $sch = explode('_',$dsna['scheme']); + if (sizeof($sch)>1) { + $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : ''; + $dsna['host'] = rawurlencode($sch[1].':host='.rawurldecode($dsna['host'])); + $dsna['scheme'] = 'pdo'; + } + } + } + + if (!$dsna) { + // special handling of oracle, which might not have host + $db = str_replace('@/','@adodb-fakehost/',$db); + $dsna = parse_url($db); + if (!$dsna) return $false; + $dsna['host'] = ''; + } + $db = @$dsna['scheme']; + if (!$db) return $false; + $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : ''; + $dsna['user'] = isset($dsna['user']) ? rawurldecode($dsna['user']) : ''; + $dsna['pass'] = isset($dsna['pass']) ? rawurldecode($dsna['pass']) : ''; + $dsna['path'] = isset($dsna['path']) ? rawurldecode(substr($dsna['path'],1)) : ''; # strip off initial / + + if (isset($dsna['query'])) { + $opt1 = explode('&',$dsna['query']); + foreach($opt1 as $k => $v) { + $arr = explode('=',$v); + $opt[$arr[0]] = isset($arr[1]) ? rawurldecode($arr[1]) : 1; + } + } else $opt = array(); + } + + /* + * phptype: Database backend used in PHP (mysql, odbc etc.) + * dbsyntax: Database used with regards to SQL syntax etc. + * protocol: Communication protocol to use (tcp, unix etc.) + * hostspec: Host specification (hostname[:port]) + * database: Database to use on the DBMS server + * username: User name for login + * password: Password for login + */ + if (!empty($ADODB_NEWCONNECTION)) { + $obj = $ADODB_NEWCONNECTION($db); + + } else { + + if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = ''; + if (empty($db)) $db = $ADODB_LASTDB; + + if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db); + + if (!$db) { + if (isset($origdsn)) $db = $origdsn; + if ($errorfn) { + // raise an error + $ignore = false; + $errorfn('ADONewConnection', 'ADONewConnection', -998, + "could not load the database driver for '$db'", + $db,false,$ignore); + } else + ADOConnection::outp( "

    ADONewConnection: Unable to load database driver '$db'

    ",false); + + return $false; + } + + $cls = 'ADODB_'.$db; + if (!class_exists($cls)) { + adodb_backtrace(); + return $false; + } + + $obj = new $cls(); + } + + # constructor should not fail + if ($obj) { + if ($errorfn) $obj->raiseErrorFn = $errorfn; + if (isset($dsna)) { + if (isset($dsna['port'])) $obj->port = $dsna['port']; + foreach($opt as $k => $v) { + switch(strtolower($k)) { + case 'persist': + case 'persistent': $persist = $v; break; + case 'debug': $obj->debug = (integer) $v; break; + #ibase + case 'role': $obj->role = $v; break; + case 'dialect': $obj->dialect = (integer) $v; break; + case 'charset': $obj->charset = $v; $obj->charSet=$v; break; + case 'buffers': $obj->buffers = $v; break; + case 'fetchmode': $obj->SetFetchMode($v); break; + #ado + case 'charpage': $obj->charPage = $v; break; + #mysql, mysqli + case 'clientflags': $obj->clientFlags = $v; break; + #mysql, mysqli, postgres + case 'port': $obj->port = $v; break; + #mysqli + case 'socket': $obj->socket = $v; break; + #oci8 + case 'nls_date_format': $obj->NLS_DATE_FORMAT = $v; break; + } + } + if (empty($persist)) + $ok = $obj->Connect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']); + else + $ok = $obj->PConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']); + + if (!$ok) return $false; + } + } + return $obj; + } + + + + // $perf == true means called by NewPerfMonitor(), otherwise for data dictionary + function _adodb_getdriver($provider,$drivername,$perf=false) + { + switch ($provider) { + case 'odbtp': if (strncmp('odbtp_',$drivername,6)==0) return substr($drivername,6); + case 'odbc' : if (strncmp('odbc_',$drivername,5)==0) return substr($drivername,5); + case 'ado' : if (strncmp('ado_',$drivername,4)==0) return substr($drivername,4); + case 'native': break; + default: + return $provider; + } + + switch($drivername) { + case 'mysqlt': + case 'mysqli': + $drivername='mysql'; + break; + case 'postgres7': + case 'postgres8': + $drivername = 'postgres'; + break; + case 'firebird15': $drivername = 'firebird'; break; + case 'oracle': $drivername = 'oci8'; break; + case 'access': if ($perf) $drivername = ''; break; + case 'db2' : break; + case 'sapdb' : break; + default: + $drivername = 'generic'; + break; + } + return $drivername; + } + + function NewPerfMonitor(&$conn) + { + $false = false; + $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true); + if (!$drivername || $drivername == 'generic') return $false; + include_once(ADODB_DIR.'/adodb-perf.inc.php'); + @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php"); + $class = "Perf_$drivername"; + if (!class_exists($class)) return $false; + $perf = new $class($conn); + + return $perf; + } + + function NewDataDictionary(&$conn,$drivername=false) + { + $false = false; + if (!$drivername) $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType); + + include_once(ADODB_DIR.'/adodb-lib.inc.php'); + include_once(ADODB_DIR.'/adodb-datadict.inc.php'); + $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php"; + + if (!file_exists($path)) { + ADOConnection::outp("Database driver '$path' not available"); + return $false; + } + include_once($path); + $class = "ADODB2_$drivername"; + $dict = new $class(); + $dict->dataProvider = $conn->dataProvider; + $dict->connection = &$conn; + $dict->upperName = strtoupper($drivername); + $dict->quote = $conn->nameQuote; + if (!empty($conn->_connectionID)) + $dict->serverInfo = $conn->ServerInfo(); + + return $dict; + } + + + + /* + Perform a print_r, with pre tags for better formatting. + */ + function adodb_pr($var,$as_string=false) + { + if ($as_string) ob_start(); + + if (isset($_SERVER['HTTP_USER_AGENT'])) { + echo "
    \n";print_r($var);echo "
    \n"; + } else + print_r($var); + + if ($as_string) { + $s = ob_get_contents(); + ob_end_clean(); + return $s; + } + } + + /* + Perform a stack-crawl and pretty print it. + + @param printOrArr Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then). + @param levels Number of levels to display + */ + function adodb_backtrace($printOrArr=true,$levels=9999) + { + global $ADODB_INCLUDED_LIB; + if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php'); + return _adodb_backtrace($printOrArr,$levels); + } + + +} +?> diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/contrib/toxmlrpc.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/contrib/toxmlrpc.inc.php new file mode 100644 index 0000000..8d7b220 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/contrib/toxmlrpc.inc.php @@ -0,0 +1,183 @@ +GetArray()) would work with: + * - ADODB_FETCH_BOTH + * - null values + */ + + /** + * Include the main libraries + */ + require_once('xmlrpc.inc'); + if (!defined('ADODB_DIR')) require_once('adodb.inc.php'); + + /** + * Builds an xmlrpc struct value out of an AdoDB recordset + */ + function rs2xmlrpcval(&$adodbrs) { + + $header =& rs2xmlrpcval_header($adodbrs); + $body =& rs2xmlrpcval_body($adodbrs); + + // put it all together and build final xmlrpc struct + $xmlrpcrs = new xmlrpcval ( array( + "header" => $header, + "body" => $body, + ), "struct"); + + return $xmlrpcrs; + + } + + /** + * Builds an xmlrpc struct value describing an AdoDB recordset + */ + function rs2xmlrpcval_header($adodbrs) + { + $numfields = $adodbrs->FieldCount(); + $numrecords = $adodbrs->RecordCount(); + + // build structure holding recordset information + $fieldstruct = array(); + for ($i = 0; $i < $numfields; $i++) { + $fld = $adodbrs->FetchField($i); + $fieldarray = array(); + if (isset($fld->name)) + $fieldarray["name"] = new xmlrpcval ($fld->name); + if (isset($fld->type)) + $fieldarray["type"] = new xmlrpcval ($fld->type); + if (isset($fld->max_length)) + $fieldarray["max_length"] = new xmlrpcval ($fld->max_length, "int"); + if (isset($fld->not_null)) + $fieldarray["not_null"] = new xmlrpcval ($fld->not_null, "boolean"); + if (isset($fld->has_default)) + $fieldarray["has_default"] = new xmlrpcval ($fld->has_default, "boolean"); + if (isset($fld->default_value)) + $fieldarray["default_value"] = new xmlrpcval ($fld->default_value); + $fieldstruct[$i] = new xmlrpcval ($fieldarray, "struct"); + } + $fieldcount = new xmlrpcval ($numfields, "int"); + $recordcount = new xmlrpcval ($numrecords, "int"); + $sql = new xmlrpcval ($adodbrs->sql); + $fieldinfo = new xmlrpcval ($fieldstruct, "array"); + + $header = new xmlrpcval ( array( + "fieldcount" => $fieldcount, + "recordcount" => $recordcount, + "sql" => $sql, + "fieldinfo" => $fieldinfo + ), "struct"); + + return $header; + } + + /** + * Builds an xmlrpc struct value out of an AdoDB recordset + * (data values only, no data definition) + */ + function rs2xmlrpcval_body($adodbrs) + { + $numfields = $adodbrs->FieldCount(); + + // build structure containing recordset data + $adodbrs->MoveFirst(); + $rows = array(); + while (!$adodbrs->EOF) { + $columns = array(); + // This should work on all cases of fetch mode: assoc, num, both or default + if ($adodbrs->fetchMode == 'ADODB_FETCH_BOTH' || count($adodbrs->fields) == 2 * $adodbrs->FieldCount()) + for ($i = 0; $i < $numfields; $i++) + if ($adodbrs->fields[$i] === null) + $columns[$i] = new xmlrpcval (''); + else + $columns[$i] =& xmlrpc_encode ($adodbrs->fields[$i]); + else + foreach ($adodbrs->fields as $val) + if ($val === null) + $columns[] = new xmlrpcval (''); + else + $columns[] =& xmlrpc_encode ($val); + + $rows[] = new xmlrpcval ($columns, "array"); + + $adodbrs->MoveNext(); + } + $body = new xmlrpcval ($rows, "array"); + + return $body; + } + + /** + * Returns an xmlrpc struct value as string out of an AdoDB recordset + */ + function rs2xmlrpcstring (&$adodbrs) { + $xmlrpc = rs2xmlrpcval ($adodbrs); + if ($xmlrpc) + return $xmlrpc->serialize(); + else + return null; + } + + /** + * Given a well-formed xmlrpc struct object returns an AdoDB object + * + * @todo add some error checking on the input value + */ + function xmlrpcval2rs (&$xmlrpcval) { + + $fields_array = array(); + $data_array = array(); + + // rebuild column information + $header =& $xmlrpcval->structmem('header'); + + $numfields = $header->structmem('fieldcount'); + $numfields = $numfields->scalarval(); + $numrecords = $header->structmem('recordcount'); + $numrecords = $numrecords->scalarval(); + $sqlstring = $header->structmem('sql'); + $sqlstring = $sqlstring->scalarval(); + + $fieldinfo =& $header->structmem('fieldinfo'); + for ($i = 0; $i < $numfields; $i++) { + $temp =& $fieldinfo->arraymem($i); + $fld = new ADOFieldObject(); + while (list($key,$value) = $temp->structeach()) { + if ($key == "name") $fld->name = $value->scalarval(); + if ($key == "type") $fld->type = $value->scalarval(); + if ($key == "max_length") $fld->max_length = $value->scalarval(); + if ($key == "not_null") $fld->not_null = $value->scalarval(); + if ($key == "has_default") $fld->has_default = $value->scalarval(); + if ($key == "default_value") $fld->default_value = $value->scalarval(); + } // while + $fields_array[] = $fld; + } // for + + // fetch recordset information into php array + $body =& $xmlrpcval->structmem('body'); + for ($i = 0; $i < $numrecords; $i++) { + $data_array[$i]= array(); + $xmlrpcrs_row =& $body->arraymem($i); + for ($j = 0; $j < $numfields; $j++) { + $temp =& $xmlrpcrs_row->arraymem($j); + $data_array[$i][$j] = $temp->scalarval(); + } // for j + } // for i + + // finally build in-memory recordset object and return it + $rs = new ADORecordSet_array(); + $rs->InitArrayFields($data_array,$fields_array); + return $rs; + + } + +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/cute_icons_for_site/adodb.gif b/seed/galette/manual/image/postinstall/galette/includes/adodb/cute_icons_for_site/adodb.gif new file mode 100644 index 0000000..c5e8dfc Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/includes/adodb/cute_icons_for_site/adodb.gif differ diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/cute_icons_for_site/adodb2.gif b/seed/galette/manual/image/postinstall/galette/includes/adodb/cute_icons_for_site/adodb2.gif new file mode 100644 index 0000000..f12ae20 Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/includes/adodb/cute_icons_for_site/adodb2.gif differ diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-mysqli.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-mysqli.inc.php new file mode 100644 index 0000000..b78f268 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-mysqli.inc.php @@ -0,0 +1,986 @@ +_connectionID = @mysqli_init(); + + if (is_null($this->_connectionID)) { + // mysqli_init only fails if insufficient memory + if ($this->debug) + ADOConnection::outp("mysqli_init() failed : " . $this->ErrorMsg()); + return false; + } + /* + I suggest a simple fix which would enable adodb and mysqli driver to + read connection options from the standard mysql configuration file + /etc/my.cnf - "Bastien Duclaux" + */ + foreach($this->optionFlags as $arr) { + mysqli_options($this->_connectionID,$arr[0],$arr[1]); + } + + #if (!empty($this->port)) $argHostname .= ":".$this->port; + $ok = mysqli_real_connect($this->_connectionID, + $argHostname, + $argUsername, + $argPassword, + $argDatabasename, + $this->port, + $this->socket, + $this->clientFlags); + + if ($ok) { + if ($argDatabasename) return $this->SelectDB($argDatabasename); + return true; + } else { + if ($this->debug) + ADOConnection::outp("Could't connect : " . $this->ErrorMsg()); + return false; + } + } + + // returns true or false + // How to force a persistent connection + function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename, true); + + } + + // When is this used? Close old connection first? + // In _connect(), check $this->forceNewConnect? + function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename) + { + $this->forceNewConnect = true; + return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename); + } + + function IfNull( $field, $ifNull ) + { + return " IFNULL($field, $ifNull) "; // if MySQL + } + + function ServerInfo() + { + $arr['description'] = $this->GetOne("select version()"); + $arr['version'] = ADOConnection::_findvers($arr['description']); + return $arr; + } + + + function BeginTrans() + { + if ($this->transOff) return true; + $this->transCnt += 1; + $this->Execute('SET AUTOCOMMIT=0'); + $this->Execute('BEGIN'); + return true; + } + + function CommitTrans($ok=true) + { + if ($this->transOff) return true; + if (!$ok) return $this->RollbackTrans(); + + if ($this->transCnt) $this->transCnt -= 1; + $this->Execute('COMMIT'); + $this->Execute('SET AUTOCOMMIT=1'); + return true; + } + + function RollbackTrans() + { + if ($this->transOff) return true; + if ($this->transCnt) $this->transCnt -= 1; + $this->Execute('ROLLBACK'); + $this->Execute('SET AUTOCOMMIT=1'); + return true; + } + + function RowLock($tables,$where='',$flds='1 as adodb_ignore') + { + if ($this->transCnt==0) $this->BeginTrans(); + if ($where) $where = ' where '.$where; + $rs =& $this->Execute("select $flds from $tables $where for update"); + return !empty($rs); + } + + // if magic quotes disabled, use mysql_real_escape_string() + // From readme.htm: + // Quotes a string to be sent to the database. The $magic_quotes_enabled + // parameter may look funny, but the idea is if you are quoting a + // string extracted from a POST/GET variable, then + // pass get_magic_quotes_gpc() as the second parameter. This will + // ensure that the variable is not quoted twice, once by qstr and once + // by the magic_quotes_gpc. + // + //Eg. $s = $db->qstr(_GET['name'],get_magic_quotes_gpc()); + function qstr($s, $magic_quotes = false) + { + if (!$magic_quotes) { + if (PHP_VERSION >= 5) + return "'" . mysqli_real_escape_string($this->_connectionID, $s) . "'"; + + if ($this->replaceQuote[0] == '\\') + $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s); + return "'".str_replace("'",$this->replaceQuote,$s)."'"; + } + // undo magic quotes for " + $s = str_replace('\\"','"',$s); + return "'$s'"; + } + + function _insertid() + { + $result = @mysqli_insert_id($this->_connectionID); + if ($result == -1){ + if ($this->debug) ADOConnection::outp("mysqli_insert_id() failed : " . $this->ErrorMsg()); + } + return $result; + } + + // Only works for INSERT, UPDATE and DELETE query's + function _affectedrows() + { + $result = @mysqli_affected_rows($this->_connectionID); + if ($result == -1) { + if ($this->debug) ADOConnection::outp("mysqli_affected_rows() failed : " . $this->ErrorMsg()); + } + return $result; + } + + // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html + // Reference on Last_Insert_ID on the recommended way to simulate sequences + var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);"; + var $_genSeqSQL = "create table %s (id int not null)"; + var $_genSeq2SQL = "insert into %s values (%s)"; + var $_dropSeqSQL = "drop table %s"; + + function CreateSequence($seqname='adodbseq',$startID=1) + { + if (empty($this->_genSeqSQL)) return false; + $u = strtoupper($seqname); + + $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname)); + if (!$ok) return false; + return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1)); + } + + function GenID($seqname='adodbseq',$startID=1) + { + // post-nuke sets hasGenID to false + if (!$this->hasGenID) return false; + + $getnext = sprintf($this->_genIDSQL,$seqname); + $holdtransOK = $this->_transOK; // save the current status + $rs = @$this->Execute($getnext); + if (!$rs) { + if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset + $u = strtoupper($seqname); + $this->Execute(sprintf($this->_genSeqSQL,$seqname)); + $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1)); + $rs = $this->Execute($getnext); + } + $this->genID = mysqli_insert_id($this->_connectionID); + + if ($rs) $rs->Close(); + + return $this->genID; + } + + function MetaDatabases() + { + $query = "SHOW DATABASES"; + $ret =& $this->Execute($query); + if ($ret && is_object($ret)){ + $arr = array(); + while (!$ret->EOF){ + $db = $ret->Fields('Database'); + if ($db != 'mysql') $arr[] = $db; + $ret->MoveNext(); + } + return $arr; + } + return $ret; + } + + + function MetaIndexes ($table, $primary = FALSE, $owner = false) + { + // save old fetch mode + global $ADODB_FETCH_MODE; + + $false = false; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== FALSE) { + $savem = $this->SetFetchMode(FALSE); + } + + // get index details + $rs = $this->Execute(sprintf('SHOW INDEXES FROM %s',$table)); + + // restore fetchmode + if (isset($savem)) { + $this->SetFetchMode($savem); + } + $ADODB_FETCH_MODE = $save; + + if (!is_object($rs)) { + return $false; + } + + $indexes = array (); + + // parse index data into array + while ($row = $rs->FetchRow()) { + if ($primary == FALSE AND $row[2] == 'PRIMARY') { + continue; + } + + if (!isset($indexes[$row[2]])) { + $indexes[$row[2]] = array( + 'unique' => ($row[1] == 0), + 'columns' => array() + ); + } + + $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4]; + } + + // sort columns by order in the index + foreach ( array_keys ($indexes) as $index ) + { + ksort ($indexes[$index]['columns']); + } + + return $indexes; + } + + + // Format date column in sql string given an input format that understands Y M D + function SQLDate($fmt, $col=false) + { + if (!$col) $col = $this->sysTimeStamp; + $s = 'DATE_FORMAT('.$col.",'"; + $concat = false; + $len = strlen($fmt); + for ($i=0; $i < $len; $i++) { + $ch = $fmt[$i]; + switch($ch) { + case 'Y': + case 'y': + $s .= '%Y'; + break; + case 'Q': + case 'q': + $s .= "'),Quarter($col)"; + + if ($len > $i+1) $s .= ",DATE_FORMAT($col,'"; + else $s .= ",('"; + $concat = true; + break; + case 'M': + $s .= '%b'; + break; + + case 'm': + $s .= '%m'; + break; + case 'D': + case 'd': + $s .= '%d'; + break; + + case 'H': + $s .= '%H'; + break; + + case 'h': + $s .= '%I'; + break; + + case 'i': + $s .= '%i'; + break; + + case 's': + $s .= '%s'; + break; + + case 'a': + case 'A': + $s .= '%p'; + break; + + case 'w': + $s .= '%w'; + break; + + case 'l': + $s .= '%W'; + break; + + default: + + if ($ch == '\\') { + $i++; + $ch = substr($fmt,$i,1); + } + $s .= $ch; + break; + } + } + $s.="')"; + if ($concat) $s = "CONCAT($s)"; + return $s; + } + + // returns concatenated string + // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator + function Concat() + { + $s = ""; + $arr = func_get_args(); + + // suggestion by andrew005@mnogo.ru + $s = implode(',',$arr); + if (strlen($s) > 0) return "CONCAT($s)"; + else return ''; + } + + // dayFraction is a day in floating point + function OffsetDate($dayFraction,$date=false) + { + if (!$date) + $date = $this->sysDate; + return "from_unixtime(unix_timestamp($date)+($dayFraction)*24*3600)"; + } + + function MetaTables($ttype=false,$showSchema=false,$mask=false) + { + $save = $this->metaTablesSQL; + if ($showSchema && is_string($showSchema)) { + $this->metaTablesSQL .= " from $showSchema"; + } + + if ($mask) { + $mask = $this->qstr($mask); + $this->metaTablesSQL .= " like $mask"; + } + $ret =& ADOConnection::MetaTables($ttype,$showSchema); + + $this->metaTablesSQL = $save; + return $ret; + } + + // "Innox - Juan Carlos Gonzalez" + function MetaForeignKeys( $table, $owner = FALSE, $upper = FALSE, $associative = FALSE ) + { + if ( !empty($owner) ) { + $table = "$owner.$table"; + } + $a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table)); + if ($associative) $create_sql = $a_create_table["Create Table"]; + else $create_sql = $a_create_table[1]; + + $matches = array(); + + if (!preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches)) return false; + $foreign_keys = array(); + $num_keys = count($matches[0]); + for ( $i = 0; $i < $num_keys; $i ++ ) { + $my_field = explode('`, `', $matches[1][$i]); + $ref_table = $matches[2][$i]; + $ref_field = explode('`, `', $matches[3][$i]); + + if ( $upper ) { + $ref_table = strtoupper($ref_table); + } + + $foreign_keys[$ref_table] = array(); + $num_fields = count($my_field); + for ( $j = 0; $j < $num_fields; $j ++ ) { + if ( $associative ) { + $foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j]; + } else { + $foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}"; + } + } + } + + return $foreign_keys; + } + + function MetaColumns($table, $normalize = true) + { + $false = false; + if (!$this->metaColumnsSQL) + return $false; + + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== false) + $savem = $this->SetFetchMode(false); + $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table)); + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + if (!is_object($rs)) + return $false; + + $retarr = array(); + while (!$rs->EOF) { + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[0]; + $type = $rs->fields[1]; + + // split type into type(length): + $fld->scale = null; + if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; + $fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1; + } elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; + } elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = max(array_map("strlen",explode(",",$query_array[2]))) - 2; // PHP >= 4.0.6 + $fld->max_length = ($fld->max_length == 0 ? 1 : $fld->max_length); + } else { + $fld->type = $type; + $fld->max_length = -1; + } + $fld->not_null = ($rs->fields[2] != 'YES'); + $fld->primary_key = ($rs->fields[3] == 'PRI'); + $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false); + $fld->binary = (strpos($type,'blob') !== false); + $fld->unsigned = (strpos($type,'unsigned') !== false); + + if (!$fld->binary) { + $d = $rs->fields[4]; + if ($d != '' && $d != 'NULL') { + $fld->has_default = true; + $fld->default_value = $d; + } else { + $fld->has_default = false; + } + } + + if ($save == ADODB_FETCH_NUM) { + $retarr[] = $fld; + } else { + $retarr[strtoupper($fld->name)] = $fld; + } + $rs->MoveNext(); + } + + $rs->Close(); + return $retarr; + } + + // returns true or false + function SelectDB($dbName) + { +// $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID); + $this->database = $dbName; + $this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions + + if ($this->_connectionID) { + $result = @mysqli_select_db($this->_connectionID, $dbName); + if (!$result) { + ADOConnection::outp("Select of database " . $dbName . " failed. " . $this->ErrorMsg()); + } + return $result; + } + return false; + } + + // parameters use PostgreSQL convention, not MySQL + function SelectLimit($sql, + $nrows = -1, + $offset = -1, + $inputarr = false, + $arg3 = false, + $secs = 0) + { + $offsetStr = ($offset >= 0) ? "$offset," : ''; + if ($nrows < 0) $nrows = '18446744073709551615'; + + if ($secs) + $rs = $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3); + else + $rs = $this->Execute($sql . " LIMIT $offsetStr$nrows" , $inputarr , $arg3); + + return $rs; + } + + + function Prepare($sql) + { + return $sql; + + $stmt = $this->_connectionID->prepare($sql); + if (!$stmt) { + echo $this->ErrorMsg(); + return $sql; + } + return array($sql,$stmt); + } + + + // returns queryID or false + function _query($sql, $inputarr) + { + global $ADODB_COUNTRECS; + + if (is_array($sql)) { + $stmt = $sql[1]; + $a = ''; + foreach($inputarr as $k => $v) { + if (is_string($v)) $a .= 's'; + else if (is_integer($v)) $a .= 'i'; + else $a .= 'd'; + } + + $fnarr = array_merge( array($stmt,$a) , $inputarr); + $ret = call_user_func_array('mysqli_stmt_bind_param',$fnarr); + + $ret = mysqli_stmt_execute($stmt); + return $ret; + } + if (!$mysql_res = mysqli_query($this->_connectionID, $sql, ($ADODB_COUNTRECS) ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT)) { + if ($this->debug) ADOConnection::outp("Query: " . $sql . " failed. " . $this->ErrorMsg()); + return false; + } + + return $mysql_res; + } + + /* Returns: the last error message from previous database operation */ + function ErrorMsg() + { + if (empty($this->_connectionID)) + $this->_errorMsg = @mysqli_connect_error(); + else + $this->_errorMsg = @mysqli_error($this->_connectionID); + return $this->_errorMsg; + } + + /* Returns: the last error number from previous database operation */ + function ErrorNo() + { + if (empty($this->_connectionID)) + return @mysqli_connect_errno(); + else + return @mysqli_errno($this->_connectionID); + } + + // returns true or false + function _close() + { + @mysqli_close($this->_connectionID); + $this->_connectionID = false; + } + + /* + * Maximum size of C field + */ + function CharMax() + { + return 255; + } + + /* + * Maximum size of X field + */ + function TextMax() + { + return 4294967295; + } + + + + // this is a set of functions for managing client encoding - very important if the encodings + // of your database and your output target (i.e. HTML) don't match + // for instance, you may have UTF8 database and server it on-site as latin1 etc. + // GetCharSet - get the name of the character set the client is using now + // Under Windows, the functions should work with MySQL 4.1.11 and above, the set of charsets supported + // depends on compile flags of mysql distribution + + function GetCharSet() + { + //we will use ADO's builtin property charSet + if (!is_callable($this->_connectionID,'character_set_name')) + return false; + + $this->charSet = @$this->_connectionID->character_set_name(); + if (!$this->charSet) { + return false; + } else { + return $this->charSet; + } + } + + // SetCharSet - switch the client encoding + function SetCharSet($charset_name) + { + if (!is_callable($this->_connectionID,'set_charset')) + return false; + + if ($this->charSet !== $charset_name) { + $if = @$this->_connectionID->set_charset($charset_name); + if ($if == "0" & $this->GetCharSet() == $charset_name) { + return true; + } else return false; + } else return true; + } + + + + +} + +/*-------------------------------------------------------------------------------------- + Class Name: Recordset +--------------------------------------------------------------------------------------*/ + +class ADORecordSet_mysqli extends ADORecordSet{ + + var $databaseType = "mysqli"; + var $canSeek = true; + + function __construct($queryID, $mode = false) + { + if ($mode === false) + { + global $ADODB_FETCH_MODE; + $mode = $ADODB_FETCH_MODE; + } + + switch ($mode) + { + case ADODB_FETCH_NUM: + $this->fetchMode = MYSQLI_NUM; + break; + case ADODB_FETCH_ASSOC: + $this->fetchMode = MYSQLI_ASSOC; + break; + case ADODB_FETCH_DEFAULT: + case ADODB_FETCH_BOTH: + default: + $this->fetchMode = MYSQLI_BOTH; + break; + } + $this->adodbFetchMode = $mode; + $this->ADORecordSet($queryID); + } + + function _initrs() + { + global $ADODB_COUNTRECS; + + $this->_numOfRows = $ADODB_COUNTRECS ? @mysqli_num_rows($this->_queryID) : -1; + $this->_numOfFields = @mysqli_num_fields($this->_queryID); + } + +/* +1 = MYSQLI_NOT_NULL_FLAG +2 = MYSQLI_PRI_KEY_FLAG +4 = MYSQLI_UNIQUE_KEY_FLAG +8 = MYSQLI_MULTIPLE_KEY_FLAG +16 = MYSQLI_BLOB_FLAG +32 = MYSQLI_UNSIGNED_FLAG +64 = MYSQLI_ZEROFILL_FLAG +128 = MYSQLI_BINARY_FLAG +256 = MYSQLI_ENUM_FLAG +512 = MYSQLI_AUTO_INCREMENT_FLAG +1024 = MYSQLI_TIMESTAMP_FLAG +2048 = MYSQLI_SET_FLAG +32768 = MYSQLI_NUM_FLAG +16384 = MYSQLI_PART_KEY_FLAG +32768 = MYSQLI_GROUP_FLAG +65536 = MYSQLI_UNIQUE_FLAG +131072 = MYSQLI_BINCMP_FLAG +*/ + + function FetchField($fieldOffset = -1) + { + $fieldnr = $fieldOffset; + if ($fieldOffset != -1) { + $fieldOffset = mysqli_field_seek($this->_queryID, $fieldnr); + } + $o = mysqli_fetch_field($this->_queryID); + /* Properties of an ADOFieldObject as set by MetaColumns */ + $o->primary_key = $o->flags & MYSQLI_PRI_KEY_FLAG; + $o->not_null = $o->flags & MYSQLI_NOT_NULL_FLAG; + $o->auto_increment = $o->flags & MYSQLI_AUTO_INCREMENT_FLAG; + $o->binary = $o->flags & MYSQLI_BINARY_FLAG; + // $o->blob = $o->flags & MYSQLI_BLOB_FLAG; /* not returned by MetaColumns */ + $o->unsigned = $o->flags & MYSQLI_UNSIGNED_FLAG; + + return $o; + } + + function GetRowAssoc($upper = true) + { + if ($this->fetchMode == MYSQLI_ASSOC && !$upper) + return $this->fields; + $row =& ADORecordSet::GetRowAssoc($upper); + return $row; + } + + /* Use associative array to get fields array */ + function Fields($colname) + { + if ($this->fetchMode != MYSQLI_NUM) + return @$this->fields[$colname]; + + if (!$this->bind) { + $this->bind = array(); + for ($i = 0; $i < $this->_numOfFields; $i++) { + $o = $this->FetchField($i); + $this->bind[strtoupper($o->name)] = $i; + } + } + return $this->fields[$this->bind[strtoupper($colname)]]; + } + + function _seek($row) + { + if ($this->_numOfRows == 0) + return false; + + if ($row < 0) + return false; + + mysqli_data_seek($this->_queryID, $row); + $this->EOF = false; + return true; + } + + // 10% speedup to move MoveNext to child class + // This is the only implementation that works now (23-10-2003). + // Other functions return no or the wrong results. + function MoveNext() + { + if ($this->EOF) return false; + $this->_currentRow++; + $this->fields = @mysqli_fetch_array($this->_queryID,$this->fetchMode); + + if (is_array($this->fields)) return true; + $this->EOF = true; + return false; + } + + function _fetch() + { + $this->fields = mysqli_fetch_array($this->_queryID,$this->fetchMode); + return is_array($this->fields); + } + + function _close() + { + mysqli_free_result($this->_queryID); + $this->_queryID = false; + } + +/* + +0 = MYSQLI_TYPE_DECIMAL +1 = MYSQLI_TYPE_CHAR +1 = MYSQLI_TYPE_TINY +2 = MYSQLI_TYPE_SHORT +3 = MYSQLI_TYPE_LONG +4 = MYSQLI_TYPE_FLOAT +5 = MYSQLI_TYPE_DOUBLE +6 = MYSQLI_TYPE_NULL +7 = MYSQLI_TYPE_TIMESTAMP +8 = MYSQLI_TYPE_LONGLONG +9 = MYSQLI_TYPE_INT24 +10 = MYSQLI_TYPE_DATE +11 = MYSQLI_TYPE_TIME +12 = MYSQLI_TYPE_DATETIME +13 = MYSQLI_TYPE_YEAR +14 = MYSQLI_TYPE_NEWDATE +247 = MYSQLI_TYPE_ENUM +248 = MYSQLI_TYPE_SET +249 = MYSQLI_TYPE_TINY_BLOB +250 = MYSQLI_TYPE_MEDIUM_BLOB +251 = MYSQLI_TYPE_LONG_BLOB +252 = MYSQLI_TYPE_BLOB +253 = MYSQLI_TYPE_VAR_STRING +254 = MYSQLI_TYPE_STRING +255 = MYSQLI_TYPE_GEOMETRY +*/ + + function MetaType($t, $len = -1, $fieldobj = false) + { + if (is_object($t)) { + $fieldobj = $t; + $t = $fieldobj->type; + $len = $fieldobj->max_length; + } + + + $len = -1; // mysql max_length is not accurate + switch (strtoupper($t)) { + case 'STRING': + case 'CHAR': + case 'VARCHAR': + case 'TINYBLOB': + case 'TINYTEXT': + case 'ENUM': + case 'SET': + + case MYSQLI_TYPE_TINY_BLOB : + case MYSQLI_TYPE_CHAR : + case MYSQLI_TYPE_STRING : + case MYSQLI_TYPE_ENUM : + case MYSQLI_TYPE_SET : + case 253 : + if ($len <= $this->blobSize) return 'C'; + + case 'TEXT': + case 'LONGTEXT': + case 'MEDIUMTEXT': + return 'X'; + + + // php_mysql extension always returns 'blob' even if 'text' + // so we have to check whether binary... + case 'IMAGE': + case 'LONGBLOB': + case 'BLOB': + case 'MEDIUMBLOB': + + case MYSQLI_TYPE_BLOB : + case MYSQLI_TYPE_LONG_BLOB : + case MYSQLI_TYPE_MEDIUM_BLOB : + + return !empty($fieldobj->binary) ? 'B' : 'X'; + case 'YEAR': + case 'DATE': + case MYSQLI_TYPE_DATE : + case MYSQLI_TYPE_YEAR : + + return 'D'; + + case 'TIME': + case 'DATETIME': + case 'TIMESTAMP': + + case MYSQLI_TYPE_DATETIME : + case MYSQLI_TYPE_NEWDATE : + case MYSQLI_TYPE_TIME : + case MYSQLI_TYPE_TIMESTAMP : + + return 'T'; + + case 'INT': + case 'INTEGER': + case 'BIGINT': + case 'TINYINT': + case 'MEDIUMINT': + case 'SMALLINT': + + case MYSQLI_TYPE_INT24 : + case MYSQLI_TYPE_LONG : + case MYSQLI_TYPE_LONGLONG : + case MYSQLI_TYPE_SHORT : + case MYSQLI_TYPE_TINY : + + if (!empty($fieldobj->primary_key)) return 'R'; + + return 'I'; + + + // Added floating-point types + // Maybe not necessery. + case 'FLOAT': + case 'DOUBLE': + // case 'DOUBLE PRECISION': + case 'DECIMAL': + case 'DEC': + case 'FIXED': + default: + //if (!is_numeric($t)) echo "

    --- Error in type matching $t -----

    "; + return 'N'; + } + } // function + + +} // rs class + +} + +?> diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-mysqlt.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-mysqlt.inc.php new file mode 100644 index 0000000..4e5ad64 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-mysqlt.inc.php @@ -0,0 +1,138 @@ + + + Requires mysql client. Works on Windows and Unix. +*/ + +// security - hide paths +if (!defined('ADODB_DIR')) die(); + +include_once(ADODB_DIR."/drivers/adodb-mysql.inc.php"); + + +class ADODB_mysqlt extends ADODB_mysql { + var $databaseType = 'mysqlt'; + var $ansiOuter = true; // for Version 3.23.17 or later + var $hasTransactions = true; + var $autoRollback = true; // apparently mysql does not autorollback properly + + function ADODB_mysqlt() + { + global $ADODB_EXTENSION; if ($ADODB_EXTENSION) $this->rsPrefix .= 'ext_'; + } + + function BeginTrans() + { + if ($this->transOff) return true; + $this->transCnt += 1; + $this->Execute('SET AUTOCOMMIT=0'); + $this->Execute('BEGIN'); + return true; + } + + function CommitTrans($ok=true) + { + if ($this->transOff) return true; + if (!$ok) return $this->RollbackTrans(); + + if ($this->transCnt) $this->transCnt -= 1; + $this->Execute('COMMIT'); + $this->Execute('SET AUTOCOMMIT=1'); + return true; + } + + function RollbackTrans() + { + if ($this->transOff) return true; + if ($this->transCnt) $this->transCnt -= 1; + $this->Execute('ROLLBACK'); + $this->Execute('SET AUTOCOMMIT=1'); + return true; + } + + function RowLock($tables,$where='',$flds='1 as adodb_ignore') + { + if ($this->transCnt==0) $this->BeginTrans(); + if ($where) $where = ' where '.$where; + $rs =& $this->Execute("select $flds from $tables $where for update"); + return !empty($rs); + } + +} + +class ADORecordSet_mysqlt extends ADORecordSet_mysql{ + var $databaseType = "mysqlt"; + + function ADORecordSet_mysqlt($queryID,$mode=false) + { + if ($mode === false) { + global $ADODB_FETCH_MODE; + $mode = $ADODB_FETCH_MODE; + } + + switch ($mode) + { + case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break; + case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break; + + case ADODB_FETCH_DEFAULT: + case ADODB_FETCH_BOTH: + default: $this->fetchMode = MYSQL_BOTH; break; + } + + $this->adodbFetchMode = $mode; + $this->ADORecordSet($queryID); + } + + function MoveNext() + { + if (@$this->fields = mysql_fetch_array($this->_queryID,$this->fetchMode)) { + $this->_currentRow += 1; + return true; + } + if (!$this->EOF) { + $this->_currentRow += 1; + $this->EOF = true; + } + return false; + } +} + +class ADORecordSet_ext_mysqlt extends ADORecordSet_mysqlt { + + function ADORecordSet_ext_mysqlt($queryID,$mode=false) + { + if ($mode === false) { + global $ADODB_FETCH_MODE; + $mode = $ADODB_FETCH_MODE; + } + switch ($mode) + { + case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break; + case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break; + + case ADODB_FETCH_DEFAULT: + case ADODB_FETCH_BOTH: + default: + $this->fetchMode = MYSQL_BOTH; break; + } + $this->adodbFetchMode = $mode; + $this->ADORecordSet($queryID); + } + + function MoveNext() + { + return adodb_movenext($this); + } +} + +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-odbtp.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-odbtp.inc.php new file mode 100644 index 0000000..cd4d5b6 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-odbtp.inc.php @@ -0,0 +1,732 @@ + + +// security - hide paths +if (!defined('ADODB_DIR')) die(); + +define("_ADODB_ODBTP_LAYER", 2 ); + +class ADODB_odbtp extends ADOConnection{ + var $databaseType = "odbtp"; + var $dataProvider = "odbtp"; + var $fmtDate = "'Y-m-d'"; + var $fmtTimeStamp = "'Y-m-d, h:i:sA'"; + var $replaceQuote = "''"; // string to use to replace quotes + var $odbc_driver = 0; + var $hasAffectedRows = true; + var $hasInsertID = false; + var $hasGenID = true; + var $hasMoveFirst = true; + + var $_genSeqSQL = "create table %s (seq_name char(30) not null unique , seq_value integer not null)"; + var $_dropSeqSQL = "delete from adodb_seq where seq_name = '%s'"; + var $_bindInputArray = false; + var $_useUnicodeSQL = false; + var $_canPrepareSP = false; + var $_dontPoolDBC = true; + + function ADODB_odbtp() + { + } + + function ServerInfo() + { + return array('description' => @odbtp_get_attr( ODB_ATTR_DBMSNAME, $this->_connectionID), + 'version' => @odbtp_get_attr( ODB_ATTR_DBMSVER, $this->_connectionID)); + } + + function ErrorMsg() + { + if (empty($this->_connectionID)) return @odbtp_last_error(); + return @odbtp_last_error($this->_connectionID); + } + + function ErrorNo() + { + if (empty($this->_connectionID)) return @odbtp_last_error_state(); + return @odbtp_last_error_state($this->_connectionID); + } + + function _insertid() + { + // SCOPE_IDENTITY() + // Returns the last IDENTITY value inserted into an IDENTITY column in + // the same scope. A scope is a module -- a stored procedure, trigger, + // function, or batch. Thus, two statements are in the same scope if + // they are in the same stored procedure, function, or batch. + return $this->GetOne($this->identitySQL); + } + + function _affectedrows() + { + if ($this->_queryID) { + return @odbtp_affected_rows ($this->_queryID); + } else + return 0; + } + + function CreateSequence($seqname='adodbseq',$start=1) + { + //verify existence + $num = $this->GetOne("select seq_value from adodb_seq"); + $seqtab='adodb_seq'; + if( $this->odbc_driver == ODB_DRIVER_FOXPRO ) { + $path = @odbtp_get_attr( ODB_ATTR_DATABASENAME, $this->_connectionID ); + //if using vfp dbc file + if( !strcasecmp(strrchr($path, '.'), '.dbc') ) + $path = substr($path,0,strrpos($path,'\/')); + $seqtab = $path . '/' . $seqtab; + } + if($num == false) { + if (empty($this->_genSeqSQL)) return false; + $ok = $this->Execute(sprintf($this->_genSeqSQL ,$seqtab)); + } + $num = $this->GetOne("select seq_value from adodb_seq where seq_name='$seqname'"); + if ($num) { + return false; + } + $start -= 1; + return $this->Execute("insert into adodb_seq values('$seqname',$start)"); + } + + function DropSequence($seqname) + { + if (empty($this->_dropSeqSQL)) return false; + return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); + } + + function GenID($seq='adodbseq',$start=1) + { + $seqtab='adodb_seq'; + if( $this->odbc_driver == ODB_DRIVER_FOXPRO) { + $path = @odbtp_get_attr( ODB_ATTR_DATABASENAME, $this->_connectionID ); + //if using vfp dbc file + if( !strcasecmp(strrchr($path, '.'), '.dbc') ) + $path = substr($path,0,strrpos($path,'\/')); + $seqtab = $path . '/' . $seqtab; + } + $MAXLOOPS = 100; + while (--$MAXLOOPS>=0) { + $num = $this->GetOne("select seq_value from adodb_seq where seq_name='$seq'"); + if ($num === false) { + //verify if abodb_seq table exist + $ok = $this->GetOne("select seq_value from adodb_seq "); + if(!$ok) { + //creating the sequence table adodb_seq + $this->Execute(sprintf($this->_genSeqSQL ,$seqtab)); + } + $start -= 1; + $num = '0'; + $ok = $this->Execute("insert into adodb_seq values('$seq',$start)"); + if (!$ok) return false; + } + $ok = $this->Execute("update adodb_seq set seq_value=seq_value+1 where seq_name='$seq'"); + if($ok) { + $num += 1; + $this->genID = $num; + return $num; + } + } + if ($fn = $this->raiseErrorFn) { + $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num); + } + return false; + } + + //example for $UserOrDSN + //for visual fox : DRIVER={Microsoft Visual FoxPro Driver};SOURCETYPE=DBF;SOURCEDB=c:\YourDbfFileDir;EXCLUSIVE=NO; + //for visual fox dbc: DRIVER={Microsoft Visual FoxPro Driver};SOURCETYPE=DBC;SOURCEDB=c:\YourDbcFileDir\mydb.dbc;EXCLUSIVE=NO; + //for access : DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\path_to_access_db\base_test.mdb;UID=root;PWD=; + //for mssql : DRIVER={SQL Server};SERVER=myserver;UID=myuid;PWD=mypwd;DATABASE=OdbtpTest; + //if uid & pwd can be separate + function _connect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='') + { + $this->_connectionID = @odbtp_connect($HostOrInterface,$UserOrDSN,$argPassword,$argDatabase); + if ($this->_connectionID === false) { + $this->_errorMsg = $this->ErrorMsg() ; + return false; + } + if ($this->_dontPoolDBC) { + if (function_exists('odbtp_dont_pool_dbc')) + @odbtp_dont_pool_dbc($this->_connectionID); + } + else { + $this->_dontPoolDBC = true; + } + $this->odbc_driver = @odbtp_get_attr(ODB_ATTR_DRIVER, $this->_connectionID); + $dbms = strtolower(@odbtp_get_attr(ODB_ATTR_DBMSNAME, $this->_connectionID)); + $this->odbc_name = $dbms; + + // Account for inconsistent DBMS names + if( $this->odbc_driver == ODB_DRIVER_ORACLE ) + $dbms = 'oracle'; + else if( $this->odbc_driver == ODB_DRIVER_SYBASE ) + $dbms = 'sybase'; + + // Set DBMS specific attributes + switch( $dbms ) { + case 'microsoft sql server': + $this->databaseType = 'odbtp_mssql'; + $this->fmtDate = "'Y-m-d'"; + $this->fmtTimeStamp = "'Y-m-d h:i:sA'"; + $this->sysDate = 'convert(datetime,convert(char,GetDate(),102),102)'; + $this->sysTimeStamp = 'GetDate()'; + $this->ansiOuter = true; + $this->leftOuter = '*='; + $this->rightOuter = '=*'; + $this->hasTop = 'top'; + $this->hasInsertID = true; + $this->hasTransactions = true; + $this->_bindInputArray = true; + $this->_canSelectDb = true; + $this->substr = "substring"; + $this->length = 'len'; + $this->identitySQL = 'select @@IDENTITY'; + $this->metaDatabasesSQL = "select name from master..sysdatabases where name <> 'master'"; + $this->_canPrepareSP = true; + break; + case 'access': + $this->databaseType = 'odbtp_access'; + $this->fmtDate = "#Y-m-d#"; + $this->fmtTimeStamp = "#Y-m-d h:i:sA#"; + $this->sysDate = "FORMAT(NOW,'yyyy-mm-dd')"; + $this->sysTimeStamp = 'NOW'; + $this->hasTop = 'top'; + $this->hasTransactions = false; + $this->_canPrepareSP = true; // For MS Access only. + break; + case 'visual foxpro': + $this->databaseType = 'odbtp_vfp'; + $this->fmtDate = "{^Y-m-d}"; + $this->fmtTimeStamp = "{^Y-m-d, h:i:sA}"; + $this->sysDate = 'date()'; + $this->sysTimeStamp = 'datetime()'; + $this->ansiOuter = true; + $this->hasTop = 'top'; + $this->hasTransactions = false; + $this->replaceQuote = "'+chr(39)+'"; + $this->true = '.T.'; + $this->false = '.F.'; + break; + case 'oracle': + $this->databaseType = 'odbtp_oci8'; + $this->fmtDate = "'Y-m-d 00:00:00'"; + $this->fmtTimeStamp = "'Y-m-d h:i:sA'"; + $this->sysDate = 'TRUNC(SYSDATE)'; + $this->sysTimeStamp = 'SYSDATE'; + $this->hasTransactions = true; + $this->_bindInputArray = true; + $this->concat_operator = '||'; + break; + case 'sybase': + $this->databaseType = 'odbtp_sybase'; + $this->fmtDate = "'Y-m-d'"; + $this->fmtTimeStamp = "'Y-m-d H:i:s'"; + $this->sysDate = 'GetDate()'; + $this->sysTimeStamp = 'GetDate()'; + $this->leftOuter = '*='; + $this->rightOuter = '=*'; + $this->hasInsertID = true; + $this->hasTransactions = true; + $this->identitySQL = 'select @@IDENTITY'; + break; + default: + $this->databaseType = 'odbtp'; + if( @odbtp_get_attr(ODB_ATTR_TXNCAPABLE, $this->_connectionID) ) + $this->hasTransactions = true; + else + $this->hasTransactions = false; + } + @odbtp_set_attr(ODB_ATTR_FULLCOLINFO, TRUE, $this->_connectionID ); + + if ($this->_useUnicodeSQL ) + @odbtp_set_attr(ODB_ATTR_UNICODESQL, TRUE, $this->_connectionID); + + return true; + } + + function _pconnect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='') + { + $this->_dontPoolDBC = false; + return $this->_connect($HostOrInterface, $UserOrDSN, $argPassword, $argDatabase); + } + + function SelectDB($dbName) + { + if (!@odbtp_select_db($dbName, $this->_connectionID)) { + return false; + } + $this->database = $dbName; + $this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions + return true; + } + + function MetaTables($ttype='',$showSchema=false,$mask=false) + { + global $ADODB_FETCH_MODE; + + $savem = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== false) $savefm = $this->SetFetchMode(false); + + $arr =& $this->GetArray("||SQLTables||||$ttype"); + + if (isset($savefm)) $this->SetFetchMode($savefm); + $ADODB_FETCH_MODE = $savem; + + $arr2 = array(); + for ($i=0; $i < sizeof($arr); $i++) { + if ($arr[$i][3] == 'SYSTEM TABLE' ) continue; + if ($arr[$i][2]) + $arr2[] = $showSchema ? $arr[$i][1].'.'.$arr[$i][2] : $arr[$i][2]; + } + return $arr2; + } + + function MetaColumns($table,$upper=true) + { + global $ADODB_FETCH_MODE; + + $schema = false; + $this->_findschema($table,$schema); + if ($upper) $table = strtoupper($table); + + $savem = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== false) $savefm = $this->SetFetchMode(false); + + $rs = $this->Execute( "||SQLColumns||$schema|$table" ); + + if (isset($savefm)) $this->SetFetchMode($savefm); + $ADODB_FETCH_MODE = $savem; + + if (!$rs || $rs->EOF) { + $false = false; + return $false; + } + $retarr = array(); + while (!$rs->EOF) { + //print_r($rs->fields); + if (strtoupper($rs->fields[2]) == $table) { + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[3]; + $fld->type = $rs->fields[5]; + $fld->max_length = $rs->fields[6]; + $fld->not_null = !empty($rs->fields[9]); + $fld->scale = $rs->fields[7]; + if (!is_null($rs->fields[12])) { + $fld->has_default = true; + $fld->default_value = $rs->fields[12]; + } + $retarr[strtoupper($fld->name)] = $fld; + } else if (!empty($retarr)) + break; + $rs->MoveNext(); + } + $rs->Close(); + + return $retarr; + } + + function MetaPrimaryKeys($table, $owner='') + { + global $ADODB_FETCH_MODE; + + $savem = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + $arr =& $this->GetArray("||SQLPrimaryKeys||$owner|$table"); + $ADODB_FETCH_MODE = $savem; + + //print_r($arr); + $arr2 = array(); + for ($i=0; $i < sizeof($arr); $i++) { + if ($arr[$i][3]) $arr2[] = $arr[$i][3]; + } + return $arr2; + } + + function MetaForeignKeys($table, $owner='', $upper=false) + { + global $ADODB_FETCH_MODE; + + $savem = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + $constraints =& $this->GetArray("||SQLForeignKeys|||||$owner|$table"); + $ADODB_FETCH_MODE = $savem; + + $arr = false; + foreach($constraints as $constr) { + //print_r($constr); + $arr[$constr[11]][$constr[2]][] = $constr[7].'='.$constr[3]; + } + if (!$arr) { + $false = false; + return $false; + } + + $arr2 = array(); + + foreach($arr as $k => $v) { + foreach($v as $a => $b) { + if ($upper) $a = strtoupper($a); + $arr2[$a] = $b; + } + } + return $arr2; + } + + function BeginTrans() + { + if (!$this->hasTransactions) return false; + if ($this->transOff) return true; + $this->transCnt += 1; + $this->autoCommit = false; + if (defined('ODB_TXN_DEFAULT')) + $txn = ODB_TXN_DEFAULT; + else + $txn = ODB_TXN_READUNCOMMITTED; + $rs = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS,$txn,$this->_connectionID); + if(!$rs) return false; + return true; + } + + function CommitTrans($ok=true) + { + if ($this->transOff) return true; + if (!$ok) return $this->RollbackTrans(); + if ($this->transCnt) $this->transCnt -= 1; + $this->autoCommit = true; + if( ($ret = @odbtp_commit($this->_connectionID)) ) + $ret = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_NONE, $this->_connectionID);//set transaction off + return $ret; + } + + function RollbackTrans() + { + if ($this->transOff) return true; + if ($this->transCnt) $this->transCnt -= 1; + $this->autoCommit = true; + if( ($ret = @odbtp_rollback($this->_connectionID)) ) + $ret = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_NONE, $this->_connectionID);//set transaction off + return $ret; + } + + function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) + { + // TOP requires ORDER BY for Visual FoxPro + if( $this->odbc_driver == ODB_DRIVER_FOXPRO ) { + if (!preg_match('/ORDER[ \t\r\n]+BY/is',$sql)) $sql .= ' ORDER BY 1'; + } + $ret =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); + return $ret; + } + + function Prepare($sql) + { + if (! $this->_bindInputArray) return $sql; // no binding + $stmt = @odbtp_prepare($sql,$this->_connectionID); + if (!$stmt) { + // print "Prepare Error for ($sql) ".$this->ErrorMsg()."
    "; + return $sql; + } + return array($sql,$stmt,false); + } + + function PrepareSP($sql) + { + if (!$this->_canPrepareSP) return $sql; // Can't prepare procedures + + $stmt = @odbtp_prepare_proc($sql,$this->_connectionID); + if (!$stmt) return false; + return array($sql,$stmt); + } + + /* + Usage: + $stmt = $db->PrepareSP('SP_RUNSOMETHING'); -- takes 2 params, @myid and @group + + # note that the parameter does not have @ in front! + $db->Parameter($stmt,$id,'myid'); + $db->Parameter($stmt,$group,'group',false,64); + $db->Parameter($stmt,$group,'photo',false,100000,ODB_BINARY); + $db->Execute($stmt); + + @param $stmt Statement returned by Prepare() or PrepareSP(). + @param $var PHP variable to bind to. Can set to null (for isNull support). + @param $name Name of stored procedure variable name to bind to. + @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in odbtp. + @param [$maxLen] Holds an maximum length of the variable. + @param [$type] The data type of $var. Legal values depend on driver. + + See odbtp_attach_param documentation at http://odbtp.sourceforge.net. + */ + function Parameter(&$stmt, &$var, $name, $isOutput=false, $maxLen=0, $type=0) + { + if ( $this->odbc_driver == ODB_DRIVER_JET ) { + $name = '['.$name.']'; + if( !$type && $this->_useUnicodeSQL + && @odbtp_param_bindtype($stmt[1], $name) == ODB_CHAR ) + { + $type = ODB_WCHAR; + } + } + else { + $name = '@'.$name; + } + return @odbtp_attach_param($stmt[1], $name, $var, $type, $maxLen); + } + + /* + Insert a null into the blob field of the table first. + Then use UpdateBlob to store the blob. + + Usage: + + $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)'); + $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1'); + */ + + function UpdateBlob($table,$column,$val,$where,$blobtype='image') + { + $sql = "UPDATE $table SET $column = ? WHERE $where"; + if( !($stmt = @odbtp_prepare($sql, $this->_connectionID)) ) + return false; + if( !@odbtp_input( $stmt, 1, ODB_BINARY, 1000000, $blobtype ) ) + return false; + if( !@odbtp_set( $stmt, 1, $val ) ) + return false; + return @odbtp_execute( $stmt ) != false; + } + + function IfNull( $field, $ifNull ) + { + switch( $this->odbc_driver ) { + case ODB_DRIVER_MSSQL: + return " ISNULL($field, $ifNull) "; + case ODB_DRIVER_JET: + return " IIF(IsNull($field), $ifNull, $field) "; + } + return " CASE WHEN $field is null THEN $ifNull ELSE $field END "; + } + + function _query($sql,$inputarr=false) + { + global $php_errormsg; + + if ($inputarr) { + if (is_array($sql)) { + $stmtid = $sql[1]; + } else { + $stmtid = @odbtp_prepare($sql,$this->_connectionID); + if ($stmtid == false) { + $this->_errorMsg = $php_errormsg; + return false; + } + } + $num_params = @odbtp_num_params( $stmtid ); + for( $param = 1; $param <= $num_params; $param++ ) { + @odbtp_input( $stmtid, $param ); + @odbtp_set( $stmtid, $param, $inputarr[$param-1] ); + } + if (!@odbtp_execute($stmtid) ) { + return false; + } + } else if (is_array($sql)) { + $stmtid = $sql[1]; + if (!@odbtp_execute($stmtid)) { + return false; + } + } else { + $stmtid = @odbtp_query($sql,$this->_connectionID); + } + $this->_lastAffectedRows = 0; + if ($stmtid) { + $this->_lastAffectedRows = @odbtp_affected_rows($stmtid); + } + return $stmtid; + } + + function _close() + { + $ret = @odbtp_close($this->_connectionID); + $this->_connectionID = false; + return $ret; + } +} + +class ADORecordSet_odbtp extends ADORecordSet { + + var $databaseType = 'odbtp'; + var $canSeek = true; + + function ADORecordSet_odbtp($queryID,$mode=false) + { + if ($mode === false) { + global $ADODB_FETCH_MODE; + $mode = $ADODB_FETCH_MODE; + } + $this->fetchMode = $mode; + $this->ADORecordSet($queryID); + } + + function _initrs() + { + $this->_numOfFields = @odbtp_num_fields($this->_queryID); + if (!($this->_numOfRows = @odbtp_num_rows($this->_queryID))) + $this->_numOfRows = -1; + + if (!$this->connection->_useUnicodeSQL) return; + + if ($this->connection->odbc_driver == ODB_DRIVER_JET) { + if (!@odbtp_get_attr(ODB_ATTR_MAPCHARTOWCHAR, + $this->connection->_connectionID)) + { + for ($f = 0; $f < $this->_numOfFields; $f++) { + if (@odbtp_field_bindtype($this->_queryID, $f) == ODB_CHAR) + @odbtp_bind_field($this->_queryID, $f, ODB_WCHAR); + } + } + } + } + + function FetchField($fieldOffset = 0) + { + $off=$fieldOffset; // offsets begin at 0 + $o= new ADOFieldObject(); + $o->name = @odbtp_field_name($this->_queryID,$off); + $o->type = @odbtp_field_type($this->_queryID,$off); + $o->max_length = @odbtp_field_length($this->_queryID,$off); + if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name); + else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name); + return $o; + } + + function _seek($row) + { + return @odbtp_data_seek($this->_queryID, $row); + } + + function fields($colname) + { + if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname]; + + if (!$this->bind) { + $this->bind = array(); + for ($i=0; $i < $this->_numOfFields; $i++) { + $name = @odbtp_field_name( $this->_queryID, $i ); + $this->bind[strtoupper($name)] = $i; + } + } + return $this->fields[$this->bind[strtoupper($colname)]]; + } + + function _fetch_odbtp($type=0) + { + switch ($this->fetchMode) { + case ADODB_FETCH_NUM: + $this->fields = @odbtp_fetch_row($this->_queryID, $type); + break; + case ADODB_FETCH_ASSOC: + $this->fields = @odbtp_fetch_assoc($this->_queryID, $type); + break; + default: + $this->fields = @odbtp_fetch_array($this->_queryID, $type); + } + return is_array($this->fields); + } + + function _fetch() + { + return $this->_fetch_odbtp(); + } + + function MoveFirst() + { + if (!$this->_fetch_odbtp(ODB_FETCH_FIRST)) return false; + $this->EOF = false; + $this->_currentRow = 0; + return true; + } + + function MoveLast() + { + if (!$this->_fetch_odbtp(ODB_FETCH_LAST)) return false; + $this->EOF = false; + $this->_currentRow = $this->_numOfRows - 1; + return true; + } + + function NextRecordSet() + { + if (!@odbtp_next_result($this->_queryID)) return false; + $this->_inited = false; + $this->bind = false; + $this->_currentRow = -1; + $this->Init(); + return true; + } + + function _close() + { + return @odbtp_free_query($this->_queryID); + } +} + +class ADORecordSet_odbtp_mssql extends ADORecordSet_odbtp { + + var $databaseType = 'odbtp_mssql'; + + function ADORecordSet_odbtp_mssql($id,$mode=false) + { + return $this->ADORecordSet_odbtp($id,$mode); + } +} + +class ADORecordSet_odbtp_access extends ADORecordSet_odbtp { + + var $databaseType = 'odbtp_access'; + + function ADORecordSet_odbtp_access($id,$mode=false) + { + return $this->ADORecordSet_odbtp($id,$mode); + } +} + +class ADORecordSet_odbtp_vfp extends ADORecordSet_odbtp { + + var $databaseType = 'odbtp_vfp'; + + function ADORecordSet_odbtp_vfp($id,$mode=false) + { + return $this->ADORecordSet_odbtp($id,$mode); + } +} + +class ADORecordSet_odbtp_oci8 extends ADORecordSet_odbtp { + + var $databaseType = 'odbtp_oci8'; + + function ADORecordSet_odbtp_oci8($id,$mode=false) + { + return $this->ADORecordSet_odbtp($id,$mode); + } +} + +class ADORecordSet_odbtp_sybase extends ADORecordSet_odbtp { + + var $databaseType = 'odbtp_sybase'; + + function ADORecordSet_odbtp_sybase($id,$mode=false) + { + return $this->ADORecordSet_odbtp($id,$mode); + } +} +?> diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-odbtp_unicode.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-odbtp_unicode.inc.php new file mode 100644 index 0000000..acc3393 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-odbtp_unicode.inc.php @@ -0,0 +1,39 @@ + + +// security - hide paths +if (!defined('ADODB_DIR')) die(); + +/* + Because the ODBTP server sends and reads UNICODE text data using UTF-8 + encoding, the following HTML meta tag must be included within the HTML + head section of every HTML form and script page: + + + + Also, all SQL query strings must be submitted as UTF-8 encoded text. +*/ + +if (!defined('_ADODB_ODBTP_LAYER')) { + include(ADODB_DIR."/drivers/adodb-odbtp.inc.php"); +} + +class ADODB_odbtp_unicode extends ADODB_odbtp { + var $databaseType = 'odbtp'; + var $_useUnicodeSQL = true; + + function ADODB_odbtp_unicode() + { + $this->ADODB_odbtp(); + } +} +?> diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-pdo_mysql.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-pdo_mysql.inc.php new file mode 100644 index 0000000..b078c22 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-pdo_mysql.inc.php @@ -0,0 +1,146 @@ +hasTransactions = false; + $parentDriver->_bindInputArray = true; + $parentDriver->hasInsertID = true; + $parentDriver->_connectionID->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true); + } + + function ServerInfo() + { + $arr['description'] = ADOConnection::GetOne("select version()"); + $arr['version'] = ADOConnection::_findvers($arr['description']); + return $arr; + } + + function MetaTables($ttype=false,$showSchema=false,$mask=false) + { + $save = $this->metaTablesSQL; + if ($showSchema && is_string($showSchema)) { + $this->metaTablesSQL .= " from $showSchema"; + } + + if ($mask) { + $mask = $this->qstr($mask); + $this->metaTablesSQL .= " like $mask"; + } + $ret =& ADOConnection::MetaTables($ttype,$showSchema); + + $this->metaTablesSQL = $save; + return $ret; + } + + function MetaColumns($table) + { + $this->_findschema($table,$schema); + if ($schema) { + $dbName = $this->database; + $this->SelectDB($schema); + } + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table)); + + if ($schema) { + $this->SelectDB($dbName); + } + + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + if (!is_object($rs)) { + $false = false; + return $false; + } + + $retarr = array(); + while (!$rs->EOF){ + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[0]; + $type = $rs->fields[1]; + + // split type into type(length): + $fld->scale = null; + if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; + $fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1; + } elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) { + $fld->type = $query_array[1]; + $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; + } elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) { + $fld->type = $query_array[1]; + $arr = explode(",",$query_array[2]); + $fld->enums = $arr; + $zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6 + $fld->max_length = ($zlen > 0) ? $zlen : 1; + } else { + $fld->type = $type; + $fld->max_length = -1; + } + $fld->not_null = ($rs->fields[2] != 'YES'); + $fld->primary_key = ($rs->fields[3] == 'PRI'); + $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false); + $fld->binary = (strpos($type,'blob') !== false); + $fld->unsigned = (strpos($type,'unsigned') !== false); + + if (!$fld->binary) { + $d = $rs->fields[4]; + if ($d != '' && $d != 'NULL') { + $fld->has_default = true; + $fld->default_value = $d; + } else { + $fld->has_default = false; + } + } + + if ($save == ADODB_FETCH_NUM) { + $retarr[] = $fld; + } else { + $retarr[strtoupper($fld->name)] = $fld; + } + $rs->MoveNext(); + } + + $rs->Close(); + return $retarr; + } + + + // parameters use PostgreSQL convention, not MySQL + function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0) + { + $offsetStr =($offset>=0) ? "$offset," : ''; + // jason judge, see http://phplens.com/lens/lensforum/msgs.php?id=9220 + if ($nrows < 0) $nrows = '18446744073709551615'; + + if ($secs) + $rs =& $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr); + else + $rs =& $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr); + return $rs; + } +} +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-pdo_oci.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-pdo_oci.inc.php new file mode 100644 index 0000000..ff80152 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/drivers/adodb-pdo_oci.inc.php @@ -0,0 +1,93 @@ +_bindInputArray = true; + + if ($this->_initdate) { + $parentDriver->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'"); + } + } + + function MetaTables($ttype=false,$showSchema=false,$mask=false) + { + if ($mask) { + $save = $this->metaTablesSQL; + $mask = $this->qstr(strtoupper($mask)); + $this->metaTablesSQL .= " AND table_name like $mask"; + } + $ret =& ADOConnection::MetaTables($ttype,$showSchema); + + if ($mask) { + $this->metaTablesSQL = $save; + } + return $ret; + } + + function MetaColumns($table) + { + global $ADODB_FETCH_MODE; + + $false = false; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + + $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table))); + + if (isset($savem)) $this->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + if (!$rs) { + return $false; + } + $retarr = array(); + while (!$rs->EOF) { //print_r($rs->fields); + $fld = new ADOFieldObject(); + $fld->name = $rs->fields[0]; + $fld->type = $rs->fields[1]; + $fld->max_length = $rs->fields[2]; + $fld->scale = $rs->fields[3]; + if ($rs->fields[1] == 'NUMBER' && $rs->fields[3] == 0) { + $fld->type ='INT'; + $fld->max_length = $rs->fields[4]; + } + $fld->not_null = (strncmp($rs->fields[5], 'NOT',3) === 0); + $fld->binary = (strpos($fld->type,'BLOB') !== false); + $fld->default_value = $rs->fields[6]; + + if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; + else $retarr[strtoupper($fld->name)] = $fld; + $rs->MoveNext(); + } + $rs->Close(); + if (empty($retarr)) + return $false; + else + return $retarr; + } +} + +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/lang/adodb-fr.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/lang/adodb-fr.inc.php new file mode 100644 index 0000000..066a2a5 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/lang/adodb-fr.inc.php @@ -0,0 +1,33 @@ + 'fr', + DB_ERROR => 'erreur inconnue', + DB_ERROR_ALREADY_EXISTS => 'existe déjà', + DB_ERROR_CANNOT_CREATE => 'crétion impossible', + DB_ERROR_CANNOT_DELETE => 'effacement impossible', + DB_ERROR_CANNOT_DROP => 'suppression impossible', + DB_ERROR_CONSTRAINT => 'violation de contrainte', + DB_ERROR_DIVZERO => 'division par zéro', + DB_ERROR_INVALID => 'invalide', + DB_ERROR_INVALID_DATE => 'date ou heure invalide', + DB_ERROR_INVALID_NUMBER => 'nombre invalide', + DB_ERROR_MISMATCH => 'erreur de concordance', + DB_ERROR_NODBSELECTED => 'pas de base de donnéessélectionnée', + DB_ERROR_NOSUCHFIELD => 'nom de colonne invalide', + DB_ERROR_NOSUCHTABLE => 'table ou vue inexistante', + DB_ERROR_NOT_CAPABLE => 'fonction optionnelle non installée', + DB_ERROR_NOT_FOUND => 'pas trouvé', + DB_ERROR_NOT_LOCKED => 'non verrouillé', + DB_ERROR_SYNTAX => 'erreur de syntaxe', + DB_ERROR_UNSUPPORTED => 'non supporté', + DB_ERROR_VALUE_COUNT_ON_ROW => 'valeur insérée trop grande pour colonne', + DB_ERROR_INVALID_DSN => 'DSN invalide', + DB_ERROR_CONNECT_FAILED => 'échec à la connexion', + 0 => "pas d'erreur", // DB_OK + DB_ERROR_NEED_MORE_DATA => 'données fournies insuffisantes', + DB_ERROR_EXTENSION_NOT_FOUND=> 'extension non trouvée', + DB_ERROR_NOSUCHDB => 'base de données inconnue', + DB_ERROR_ACCESS_VIOLATION => 'droits insuffisants' +); +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/license.txt b/seed/galette/manual/image/postinstall/galette/includes/adodb/license.txt new file mode 100644 index 0000000..2353871 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/license.txt @@ -0,0 +1,182 @@ +ADOdb is dual licensed using BSD and LGPL. + +In plain English, you do not need to distribute your application in source code form, nor do you need to distribute ADOdb source code, provided you follow the rest of terms of the BSD license. + +For more info about ADOdb, visit http://adodb.sourceforge.net/ + +BSD Style-License +================= + +Copyright (c) 2000, 2001, 2002, 2003, 2004 John Lim +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list +of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright notice, this list +of conditions and the following disclaimer in the documentation and/or other materials +provided with the distribution. + +Neither the name of the John Lim nor the names of its contributors may be used to +endorse or promote products derived from this software without specific prior written +permission. + +DISCLAIMER: +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL +JOHN LIM OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +========================================================== +GNU LESSER GENERAL PUBLIC LICENSE +Version 2.1, February 1999 + +Copyright (C) 1991, 1999 Free Software Foundation, Inc. +59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + +Preamble +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. + +When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. + +We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. + + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION +0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + +a) The modified work must itself be a software library. +b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. +c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. +d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. +(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: + + +a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) +b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. +c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. +d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. +e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. +For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: + + +a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. +b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. +8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/pear/Auth/Container/ADOdb.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/pear/Auth/Container/ADOdb.php new file mode 100644 index 0000000..4122d1e --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/pear/Auth/Container/ADOdb.php @@ -0,0 +1,413 @@ + +// | Richard Tango-Lowy | +// +----------------------------------------------------------------------+ +// +// $Id: ADOdb.php,v 1.3 2005/05/18 06:58:47 jlim Exp $ +// + +require_once 'Auth/Container.php'; +require_once 'adodb.inc.php'; +require_once 'adodb-pear.inc.php'; +require_once 'adodb-errorpear.inc.php'; + +/** + * Storage driver for fetching login data from a database using ADOdb-PHP. + * + * This storage driver can use all databases which are supported + * by the ADBdb DB abstraction layer to fetch login data. + * See http://php.weblogs.com/adodb for information on ADOdb. + * NOTE: The ADOdb directory MUST be in your PHP include_path! + * + * @author Richard Tango-Lowy + * @package Auth + * @version $Revision: 1.3 $ + */ +class Auth_Container_ADOdb extends Auth_Container +{ + + /** + * Additional options for the storage container + * @var array + */ + var $options = array(); + + /** + * DB object + * @var object + */ + var $db = null; + var $dsn = ''; + + /** + * User that is currently selected from the DB. + * @var string + */ + var $activeUser = ''; + + // {{{ Constructor + + /** + * Constructor of the container class + * + * Initate connection to the database via PEAR::ADOdb + * + * @param string Connection data or DB object + * @return object Returns an error object if something went wrong + */ + function Auth_Container_ADOdb($dsn) + { + $this->_setDefaults(); + + if (is_array($dsn)) { + $this->_parseOptions($dsn); + + if (empty($this->options['dsn'])) { + PEAR::raiseError('No connection parameters specified!'); + } + } else { + // Extract db_type from dsn string. + $this->options['dsn'] = $dsn; + } + } + + // }}} + // {{{ _connect() + + /** + * Connect to database by using the given DSN string + * + * @access private + * @param string DSN string + * @return mixed Object on error, otherwise bool + */ + function _connect($dsn) + { + if (is_string($dsn) || is_array($dsn)) { + if(!$this->db) { + $this->db = &ADONewConnection($dsn); + if( $err = ADODB_Pear_error() ) { + return PEAR::raiseError($err); + } + } + + } else { + return PEAR::raiseError('The given dsn was not valid in file ' . __FILE__ . ' at line ' . __LINE__, + 41, + PEAR_ERROR_RETURN, + null, + null + ); + } + + if(!$this->db) { + return PEAR::raiseError(ADODB_Pear_error()); + } else { + return true; + } + } + + // }}} + // {{{ _prepare() + + /** + * Prepare database connection + * + * This function checks if we have already opened a connection to + * the database. If that's not the case, a new connection is opened. + * + * @access private + * @return mixed True or a DB error object. + */ + function _prepare() + { + if(!$this->db) { + $res = $this->_connect($this->options['dsn']); + } + return true; + } + + // }}} + // {{{ query() + + /** + * Prepare query to the database + * + * This function checks if we have already opened a connection to + * the database. If that's not the case, a new connection is opened. + * After that the query is passed to the database. + * + * @access public + * @param string Query string + * @return mixed a DB_result object or DB_OK on success, a DB + * or PEAR error on failure + */ + function query($query) + { + $err = $this->_prepare(); + if ($err !== true) { + return $err; + } + return $this->db->query($query); + } + + // }}} + // {{{ _setDefaults() + + /** + * Set some default options + * + * @access private + * @return void + */ + function _setDefaults() + { + $this->options['db_type'] = 'mysql'; + $this->options['table'] = 'auth'; + $this->options['usernamecol'] = 'username'; + $this->options['passwordcol'] = 'password'; + $this->options['dsn'] = ''; + $this->options['db_fields'] = ''; + $this->options['cryptType'] = 'md5'; + } + + // }}} + // {{{ _parseOptions() + + /** + * Parse options passed to the container class + * + * @access private + * @param array + */ + function _parseOptions($array) + { + foreach ($array as $key => $value) { + if (isset($this->options[$key])) { + $this->options[$key] = $value; + } + } + + /* Include additional fields if they exist */ + if(!empty($this->options['db_fields'])){ + if(is_array($this->options['db_fields'])){ + $this->options['db_fields'] = join($this->options['db_fields'], ', '); + } + $this->options['db_fields'] = ', '.$this->options['db_fields']; + } + } + + // }}} + // {{{ fetchData() + + /** + * Get user information from database + * + * This function uses the given username to fetch + * the corresponding login data from the database + * table. If an account that matches the passed username + * and password is found, the function returns true. + * Otherwise it returns false. + * + * @param string Username + * @param string Password + * @return mixed Error object or boolean + */ + function fetchData($username, $password) + { + // Prepare for a database query + $err = $this->_prepare(); + if ($err !== true) { + return PEAR::raiseError($err->getMessage(), $err->getCode()); + } + + // Find if db_fields contains a *, i so assume all col are selected + if(strstr($this->options['db_fields'], '*')){ + $sql_from = "*"; + } + else{ + $sql_from = $this->options['usernamecol'] . ", ".$this->options['passwordcol'].$this->options['db_fields']; + } + + $query = "SELECT ".$sql_from. + " FROM ".$this->options['table']. + " WHERE ".$this->options['usernamecol']." = " . $this->db->Quote($username); + + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + $rset = $this->db->Execute( $query ); + $res = $rset->fetchRow(); + + if (DB::isError($res)) { + return PEAR::raiseError($res->getMessage(), $res->getCode()); + } + if (!is_array($res)) { + $this->activeUser = ''; + return false; + } + if ($this->verifyPassword(trim($password, "\r\n"), + trim($res[$this->options['passwordcol']], "\r\n"), + $this->options['cryptType'])) { + // Store additional field values in the session + foreach ($res as $key => $value) { + if ($key == $this->options['passwordcol'] || + $key == $this->options['usernamecol']) { + continue; + } + // Use reference to the auth object if exists + // This is because the auth session variable can change so a static call to setAuthData does not make sence + if(is_object($this->_auth_obj)){ + $this->_auth_obj->setAuthData($key, $value); + } else { + Auth::setAuthData($key, $value); + } + } + + return true; + } + + $this->activeUser = $res[$this->options['usernamecol']]; + return false; + } + + // }}} + // {{{ listUsers() + + function listUsers() + { + $err = $this->_prepare(); + if ($err !== true) { + return PEAR::raiseError($err->getMessage(), $err->getCode()); + } + + $retVal = array(); + + // Find if db_fileds contains a *, i so assume all col are selected + if(strstr($this->options['db_fields'], '*')){ + $sql_from = "*"; + } + else{ + $sql_from = $this->options['usernamecol'] . ", ".$this->options['passwordcol'].$this->options['db_fields']; + } + + $query = sprintf("SELECT %s FROM %s", + $sql_from, + $this->options['table'] + ); + $res = $this->db->getAll($query, null, DB_FETCHMODE_ASSOC); + + if (DB::isError($res)) { + return PEAR::raiseError($res->getMessage(), $res->getCode()); + } else { + foreach ($res as $user) { + $user['username'] = $user[$this->options['usernamecol']]; + $retVal[] = $user; + } + } + return $retVal; + } + + // }}} + // {{{ addUser() + + /** + * Add user to the storage container + * + * @access public + * @param string Username + * @param string Password + * @param mixed Additional information that are stored in the DB + * + * @return mixed True on success, otherwise error object + */ + function addUser($username, $password, $additional = "") + { + if (function_exists($this->options['cryptType'])) { + $cryptFunction = $this->options['cryptType']; + } else { + $cryptFunction = 'md5'; + } + + $additional_key = ''; + $additional_value = ''; + + if (is_array($additional)) { + foreach ($additional as $key => $value) { + $additional_key .= ', ' . $key; + $additional_value .= ", '" . $value . "'"; + } + } + + $query = sprintf("INSERT INTO %s (%s, %s%s) VALUES ('%s', '%s'%s)", + $this->options['table'], + $this->options['usernamecol'], + $this->options['passwordcol'], + $additional_key, + $username, + $cryptFunction($password), + $additional_value + ); + + $res = $this->query($query); + + if (DB::isError($res)) { + return PEAR::raiseError($res->getMessage(), $res->getCode()); + } else { + return true; + } + } + + // }}} + // {{{ removeUser() + + /** + * Remove user from the storage container + * + * @access public + * @param string Username + * + * @return mixed True on success, otherwise error object + */ + function removeUser($username) + { + $query = sprintf("DELETE FROM %s WHERE %s = '%s'", + $this->options['table'], + $this->options['usernamecol'], + $username + ); + + $res = $this->query($query); + + if (DB::isError($res)) { + return PEAR::raiseError($res->getMessage(), $res->getCode()); + } else { + return true; + } + } + + // }}} +} + +function showDbg( $string ) { + print " +-- $string

    "; +} +function dump( $var, $str, $vardump = false ) { + print "

    $str

    ";
    +	( !$vardump ) ? ( print_r( $var )) : ( var_dump( $var ));
    +	print "
    "; +} +?> diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/pear/readme.Auth.txt b/seed/galette/manual/image/postinstall/galette/includes/adodb/pear/readme.Auth.txt new file mode 100644 index 0000000..db28319 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/pear/readme.Auth.txt @@ -0,0 +1,20 @@ +From: Rich Tango-Lowy (richtl#arscognita.com) +Date: Sat, May 29, 2004 11:20 am + +OK, I hacked out an ADOdb container for PEAR-Auth. The error handling's +a bit of a mess, but all the methods work. + +Copy ADOdb.php to your pear/Auth/Container/ directory. + +Use the ADOdb container exactly as you would the DB +container, but specify 'ADOdb' instead of 'DB': + +$dsn = "mysql://myuser:mypass@localhost/authdb"; +$a = new Auth("ADOdb", $dsn, "loginFunction"); + + +------------------- + +John Lim adds: + +See http://pear.php.net/manual/en/package.authentication.php diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/perf/perf-mysql.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/perf/perf-mysql.inc.php new file mode 100644 index 0000000..b4cf53e --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/perf/perf-mysql.inc.php @@ -0,0 +1,315 @@ + array('RATIO', + '=GetKeyHitRatio', + '=WarnCacheRatio'), + 'InnoDB cache hit ratio' => array('RATIO', + '=GetInnoDBHitRatio', + '=WarnCacheRatio'), + 'data cache hit ratio' => array('HIDE', # only if called + '=FindDBHitRatio', + '=WarnCacheRatio'), + 'sql cache hit ratio' => array('RATIO', + '=GetQHitRatio', + ''), + 'IO', + 'data reads' => array('IO', + '=GetReads', + 'Number of selects (Key_reads is not accurate)'), + 'data writes' => array('IO', + '=GetWrites', + 'Number of inserts/updates/deletes * coef (Key_writes is not accurate)'), + + 'Data Cache', + 'MyISAM data cache size' => array('DATAC', + array("show variables", 'key_buffer_size'), + '' ), + 'BDB data cache size' => array('DATAC', + array("show variables", 'bdb_cache_size'), + '' ), + 'InnoDB data cache size' => array('DATAC', + array("show variables", 'innodb_buffer_pool_size'), + '' ), + 'Memory Usage', + 'read buffer size' => array('CACHE', + array("show variables", 'read_buffer_size'), + '(per session)'), + 'sort buffer size' => array('CACHE', + array("show variables", 'sort_buffer_size'), + 'Size of sort buffer (per session)' ), + 'table cache' => array('CACHE', + array("show variables", 'table_cache'), + 'Number of tables to keep open'), + 'Connections', + 'current connections' => array('SESS', + array('show status','Threads_connected'), + ''), + 'max connections' => array( 'SESS', + array("show variables",'max_connections'), + ''), + + false + ); + + function perf_mysql(&$conn) + { + $this->conn =& $conn; + } + + function Explain($sql,$partial=false) + { + + if (strtoupper(substr(trim($sql),0,6)) !== 'SELECT') return '

    Unable to EXPLAIN non-select statement

    '; + $save = $this->conn->LogSQL(false); + if ($partial) { + $sqlq = $this->conn->qstr($sql.'%'); + $arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq"); + if ($arr) { + foreach($arr as $row) { + $sql = reset($row); + if (crc32($sql) == $partial) break; + } + } + } + $sql = str_replace('?',"''",$sql); + + if ($partial) { + $sqlq = $this->conn->qstr($sql.'%'); + $sql = $this->conn->GetOne("select sql1 from adodb_logsql where sql1 like $sqlq"); + } + + $s = '

    Explain: '.htmlspecialchars($sql).'

    '; + $rs = $this->conn->Execute('EXPLAIN '.$sql); + $s .= rs2html($rs,false,false,false,false); + $this->conn->LogSQL($save); + $s .= $this->Tracer($sql); + return $s; + } + + function Tables() + { + if (!$this->tablesSQL) return false; + + $rs = $this->conn->Execute($this->tablesSQL); + if (!$rs) return false; + + $html = rs2html($rs,false,false,false,false); + return $html; + } + + function GetReads() + { + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false); + + $rs = $this->conn->Execute('show status'); + + if (isset($savem)) $this->conn->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + + if (!$rs) return 0; + $val = 0; + while (!$rs->EOF) { + switch($rs->fields[0]) { + case 'Com_select': + $val = $rs->fields[1]; + $rs->Close(); + return $val; + } + $rs->MoveNext(); + } + + $rs->Close(); + + return $val; + } + + function GetWrites() + { + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false); + + $rs = $this->conn->Execute('show status'); + + if (isset($savem)) $this->conn->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + + if (!$rs) return 0; + $val = 0.0; + while (!$rs->EOF) { + switch($rs->fields[0]) { + case 'Com_insert': + $val += $rs->fields[1]; break; + case 'Com_delete': + $val += $rs->fields[1]; break; + case 'Com_update': + $val += $rs->fields[1]/2; + $rs->Close(); + return $val; + } + $rs->MoveNext(); + } + + $rs->Close(); + + return $val; + } + + function FindDBHitRatio() + { + // first find out type of table + //$this->conn->debug=1; + + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false); + + $rs = $this->conn->Execute('show table status'); + + if (isset($savem)) $this->conn->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + + if (!$rs) return ''; + $type = strtoupper($rs->fields[1]); + $rs->Close(); + switch($type){ + case 'MYISAM': + case 'ISAM': + return $this->DBParameter('MyISAM cache hit ratio').' (MyISAM)'; + case 'INNODB': + return $this->DBParameter('InnoDB cache hit ratio').' (InnoDB)'; + default: + return $type.' not supported'; + } + + } + + function GetQHitRatio() + { + //Total number of queries = Qcache_inserts + Qcache_hits + Qcache_not_cached + $hits = $this->_DBParameter(array("show status","Qcache_hits")); + $total = $this->_DBParameter(array("show status","Qcache_inserts")); + $total += $this->_DBParameter(array("show status","Qcache_not_cached")); + + $total += $hits; + if ($total) return round(($hits*100)/$total,2); + return 0; + } + + /* + Use session variable to store Hit percentage, because MySQL + does not remember last value of SHOW INNODB STATUS hit ratio + + # 1st query to SHOW INNODB STATUS + 0.00 reads/s, 0.00 creates/s, 0.00 writes/s + Buffer pool hit rate 1000 / 1000 + + # 2nd query to SHOW INNODB STATUS + 0.00 reads/s, 0.00 creates/s, 0.00 writes/s + No buffer pool activity since the last printout + */ + function GetInnoDBHitRatio() + { + global $ADODB_FETCH_MODE; + + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false); + + $rs = $this->conn->Execute('show innodb status'); + + if (isset($savem)) $this->conn->SetFetchMode($savem); + $ADODB_FETCH_MODE = $save; + + if (!$rs || $rs->EOF) return 0; + $stat = $rs->fields[0]; + $rs->Close(); + $at = strpos($stat,'Buffer pool hit rate'); + $stat = substr($stat,$at,200); + if (preg_match('!Buffer pool hit rate\s*([0-9]*) / ([0-9]*)!',$stat,$arr)) { + $val = 100*$arr[1]/$arr[2]; + $_SESSION['INNODB_HIT_PCT'] = $val; + return round($val,2); + } else { + if (isset($_SESSION['INNODB_HIT_PCT'])) return $_SESSION['INNODB_HIT_PCT']; + return 0; + } + return 0; + } + + function GetKeyHitRatio() + { + $hits = $this->_DBParameter(array("show status","Key_read_requests")); + $reqs = $this->_DBParameter(array("show status","Key_reads")); + if ($reqs == 0) return 0; + + return round(($hits/($reqs+$hits))*100,2); + } + + // start hack + var $optimizeTableLow = 'CHECK TABLE %s FAST QUICK'; + var $optimizeTableHigh = 'OPTIMIZE TABLE %s'; + + /** + * @see adodb_perf#optimizeTable + */ + function optimizeTable( $table, $mode = ADODB_OPT_LOW) + { + if ( !is_string( $table)) return false; + + $conn = $this->conn; + if ( !$conn) return false; + + $sql = ''; + switch( $mode) { + case ADODB_OPT_LOW : $sql = $this->optimizeTableLow; break; + case ADODB_OPT_HIGH : $sql = $this->optimizeTableHigh; break; + default : + { + // May dont use __FUNCTION__ constant for BC (__FUNCTION__ Added in PHP 4.3.0) + ADOConnection::outp( sprintf( "

    %s: '%s' using of undefined mode '%s'

    ", __CLASS__, __FUNCTION__, $mode)); + return false; + } + } + $sql = sprintf( $sql, $table); + + return $conn->Execute( $sql) !== false; + } + // end hack +} +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/pivottable.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/pivottable.inc.php new file mode 100644 index 0000000..65b5972 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/pivottable.inc.php @@ -0,0 +1,185 @@ +databaseType,'access') !== false; + // note - vfp still doesn' work even with IIF enabled || $db->databaseType == 'vfp'; + + //$hidecnt = false; + + if ($where) $where = "\nWHERE $where"; + if (!is_array($colfield)) $colarr = $db->GetCol("select distinct $colfield from $tables $where order by 1"); + if (!$aggfield) $hidecnt = false; + + $sel = "$rowfields, "; + if (is_array($colfield)) { + foreach ($colfield as $k => $v) { + $k = trim($k); + if (!$hidecnt) { + $sel .= $iif ? + "\n\t$aggfn(IIF($v,1,0)) AS \"$k\", " + : + "\n\t$aggfn(CASE WHEN $v THEN 1 ELSE 0 END) AS \"$k\", "; + } + if ($aggfield) { + $sel .= $iif ? + "\n\t$aggfn(IIF($v,$aggfield,0)) AS \"$sumlabel$k\", " + : + "\n\t$aggfn(CASE WHEN $v THEN $aggfield ELSE 0 END) AS \"$sumlabel$k\", "; + } + } + } else { + foreach ($colarr as $v) { + if (!is_numeric($v)) $vq = $db->qstr($v); + else $vq = $v; + $v = trim($v); + if (strlen($v) == 0 ) $v = 'null'; + if (!$hidecnt) { + $sel .= $iif ? + "\n\t$aggfn(IIF($colfield=$vq,1,0)) AS \"$v\", " + : + "\n\t$aggfn(CASE WHEN $colfield=$vq THEN 1 ELSE 0 END) AS \"$v\", "; + } + if ($aggfield) { + if ($hidecnt) $label = $v; + else $label = "{$v}_$aggfield"; + $sel .= $iif ? + "\n\t$aggfn(IIF($colfield=$vq,$aggfield,0)) AS \"$label\", " + : + "\n\t$aggfn(CASE WHEN $colfield=$vq THEN $aggfield ELSE 0 END) AS \"$label\", "; + } + } + } + if ($aggfield && $aggfield != '1'){ + $agg = "$aggfn($aggfield)"; + $sel .= "\n\t$agg as \"$sumlabel$aggfield\", "; + } + + if ($showcount) + $sel .= "\n\tSUM(1) as Total"; + else + $sel = substr($sel,0,strlen($sel)-2); + + $sql = "SELECT $sel \nFROM $tables $where \nGROUP BY $rowfields"; + return $sql; + } + +/* EXAMPLES USING MS NORTHWIND DATABASE */ +if (0) { + +# example1 +# +# Query the main "product" table +# Set the rows to CompanyName and QuantityPerUnit +# and the columns to the Categories +# and define the joins to link to lookup tables +# "categories" and "suppliers" +# + + $sql = PivotTableSQL( + $gDB, # adodb connection + 'products p ,categories c ,suppliers s', # tables + 'CompanyName,QuantityPerUnit', # row fields + 'CategoryName', # column fields + 'p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID' # joins/where +); + print "
    $sql";
    + $rs = $gDB->Execute($sql);
    + rs2html($rs);
    + 
    +/*
    +Generated SQL:
    +
    +SELECT CompanyName,QuantityPerUnit, 
    +	SUM(CASE WHEN CategoryName='Beverages' THEN 1 ELSE 0 END) AS "Beverages", 
    +	SUM(CASE WHEN CategoryName='Condiments' THEN 1 ELSE 0 END) AS "Condiments", 
    +	SUM(CASE WHEN CategoryName='Confections' THEN 1 ELSE 0 END) AS "Confections", 
    +	SUM(CASE WHEN CategoryName='Dairy Products' THEN 1 ELSE 0 END) AS "Dairy Products", 
    +	SUM(CASE WHEN CategoryName='Grains/Cereals' THEN 1 ELSE 0 END) AS "Grains/Cereals", 
    +	SUM(CASE WHEN CategoryName='Meat/Poultry' THEN 1 ELSE 0 END) AS "Meat/Poultry", 
    +	SUM(CASE WHEN CategoryName='Produce' THEN 1 ELSE 0 END) AS "Produce", 
    +	SUM(CASE WHEN CategoryName='Seafood' THEN 1 ELSE 0 END) AS "Seafood", 
    +	SUM(1) as Total 
    +FROM products p ,categories c ,suppliers s  WHERE p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID 
    +GROUP BY CompanyName,QuantityPerUnit
    +*/
    +//=====================================================================
    +
    +# example2
    +#
    +# Query the main "product" table
    +# Set the rows to CompanyName and QuantityPerUnit
    +# and the columns to the UnitsInStock for diiferent ranges
    +# and define the joins to link to lookup tables 
    +# "categories" and "suppliers"
    +#
    + $sql = PivotTableSQL(
    + 	$gDB,										# adodb connection
    + 	'products p ,categories c ,suppliers s',	# tables
    +	'CompanyName,QuantityPerUnit',				# row fields
    +												# column ranges
    +array(										
    +' 0 ' => 'UnitsInStock <= 0',
    +"1 to 5" => '0 < UnitsInStock and UnitsInStock <= 5',
    +"6 to 10" => '5 < UnitsInStock and UnitsInStock <= 10',
    +"11 to 15"  => '10 < UnitsInStock and UnitsInStock <= 15',
    +"16+" =>'15 < UnitsInStock'
    +),
    +	' p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID', # joins/where
    +	'UnitsInStock', 							# sum this field
    +	'Sum'										# sum label prefix
    +);
    + print "
    $sql";
    + $rs = $gDB->Execute($sql);
    + rs2html($rs);
    + /*
    + Generated SQL:
    + 
    +SELECT CompanyName,QuantityPerUnit, 
    +	SUM(CASE WHEN UnitsInStock <= 0 THEN UnitsInStock ELSE 0 END) AS "Sum  0 ", 
    +	SUM(CASE WHEN 0 < UnitsInStock and UnitsInStock <= 5 THEN UnitsInStock ELSE 0 END) AS "Sum 1 to 5", 
    +	SUM(CASE WHEN 5 < UnitsInStock and UnitsInStock <= 10 THEN UnitsInStock ELSE 0 END) AS "Sum 6 to 10", 
    +	SUM(CASE WHEN 10 < UnitsInStock and UnitsInStock <= 15 THEN UnitsInStock ELSE 0 END) AS "Sum 11 to 15", 
    +	SUM(CASE WHEN 15 < UnitsInStock THEN UnitsInStock ELSE 0 END) AS "Sum 16+",
    +	SUM(UnitsInStock) AS "Sum UnitsInStock", 
    +	SUM(1) as Total 
    +FROM products p ,categories c ,suppliers s  WHERE  p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID 
    +GROUP BY CompanyName,QuantityPerUnit
    + */
    +}
    +?>
    \ No newline at end of file
    diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/readme.txt b/seed/galette/manual/image/postinstall/galette/includes/adodb/readme.txt
    new file mode 100644
    index 0000000..97bdd9e
    --- /dev/null
    +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/readme.txt
    @@ -0,0 +1,62 @@
    +>> ADODB Library for PHP4
    +
    +(c) 2000-2004 John Lim (jlim@natsoft.com.my)
    +
    +Released under both BSD and GNU Lesser GPL library license. 
    +This means you can use it in proprietary products.
    + 
    + 
    +>> Introduction
    +
    +PHP's database access functions are not standardised. This creates a 
    +need for a database class library to hide the differences between the 
    +different databases (encapsulate the differences) so we can easily 
    +switch databases.
    +
    +We currently support MySQL, Interbase, Sybase, PostgreSQL, Oracle, 
    +Microsoft SQL server,  Foxpro ODBC, Access ODBC, Informix, DB2,
    +Sybase SQL Anywhere, generic ODBC and Microsoft's ADO. 
    +
    +We hope more people will contribute drivers to support other databases.
    +
    +
    +>> Documentation and Examples
    +
    +Refer to the adodb/docs directory for full documentation and examples. 
    +There is also a  tutorial tute.htm that contrasts ADODB code with 
    +mysql code.
    +
    +
    +>>> Files
    +Adodb.inc.php is the main file. You need to include only this file.
    +
    +Adodb-*.inc.php are the database specific driver code.
    +
    +Test.php contains a list of test commands to exercise the class library.
    +
    +Adodb-session.php is the PHP4 session handling code.
    +
    +Testdatabases.inc.php contains the list of databases to apply the tests on.
    +
    +Benchmark.php is a simple benchmark to test the throughput of a simple SELECT 
    +statement for databases described in testdatabases.inc.php. The benchmark
    +tables are created in test.php.
    +
    +readme.htm is the main documentation.
    +
    +tute.htm is the tutorial.
    +
    +
    +>> More Info
    +
    +For more information, including installation see readme.htm
    +or visit
    +           http://adodb.sourceforge.net/
    +
    +
    +>> Feature Requests and Bug Reports
    +
    +Email to jlim@natsoft.com.my 
    +
    +
    + 
    \ No newline at end of file
    diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/rsfilter.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/rsfilter.inc.php
    new file mode 100644
    index 0000000..6b2809c
    --- /dev/null
    +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/rsfilter.inc.php
    @@ -0,0 +1,61 @@
    + $v) {
    +			$arr[$k] = ucwords($v);
    +		}
    +	}
    +	$rs = RSFilter($rs,'do_ucwords');
    + */
    +function RSFilter($rs,$fn)
    +{
    +	if ($rs->databaseType != 'array') {
    +		if (!$rs->connection) return false;
    +		
    +		$rs = &$rs->connection->_rs2rs($rs);
    +	}
    +	$rows = $rs->RecordCount();
    +	for ($i=0; $i < $rows; $i++) {
    +		if (is_array ($fn)) {
    +        	$obj = $fn[0];
    +        	$method = $fn[1];
    +        	$obj->$method ($rs->_array[$i],$rs);
    +      } else {
    +			$fn($rs->_array[$i],$rs);
    +      }
    +	  
    +	}
    +	if (!$rs->EOF) {
    +		$rs->_currentRow = 0;
    +		$rs->fields = $rs->_array[0];
    +	}
    +	
    +	return $rs;
    +}
    +?>
    \ No newline at end of file
    diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/server.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/server.php
    new file mode 100644
    index 0000000..0255c3d
    --- /dev/null
    +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/server.php
    @@ -0,0 +1,100 @@
    +Connect($host,$uid,$pwd,$database)) err($conn->ErrorNo(). $sep . $conn->ErrorMsg());
    +$sql = undomq($_REQUEST['sql']);
    +
    +if (isset($_REQUEST['fetch']))
    +	$ADODB_FETCH_MODE = $_REQUEST['fetch'];
    +	
    +if (isset($_REQUEST['nrows'])) {
    +	$nrows = $_REQUEST['nrows'];
    +	$offset = isset($_REQUEST['offset']) ? $_REQUEST['offset'] : -1;
    +	$rs = $conn->SelectLimit($sql,$nrows,$offset);
    +} else 
    +	$rs = $conn->Execute($sql);
    +if ($rs){ 
    +	//$rs->timeToLive = 1;
    +	echo _rs2serialize($rs,$conn,$sql);
    +	$rs->Close();
    +} else
    +	err($conn->ErrorNo(). $sep .$conn->ErrorMsg());
    +
    +?>
    \ No newline at end of file
    diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-compress-bzip2.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-compress-bzip2.php
    new file mode 100644
    index 0000000..230993c
    --- /dev/null
    +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-compress-bzip2.php
    @@ -0,0 +1,118 @@
    +_block_size;
    +	}
    +
    +	/**
    +	 */
    +	function setBlockSize($block_size) {
    +		assert('$block_size >= 1');
    +		assert('$block_size <= 9');
    +		$this->_block_size = (int) $block_size;
    +	}
    +
    +	/**
    +	 */
    +	function getWorkLevel() {
    +		return $this->_work_level;
    +	}
    +
    +	/**
    +	 */
    +	function setWorkLevel($work_level) {
    +		assert('$work_level >= 0');
    +		assert('$work_level <= 250');
    +		$this->_work_level = (int) $work_level;
    +	}
    +
    +	/**
    +	 */
    +	function getMinLength() {
    +		return $this->_min_length;
    +	}
    +
    +	/**
    +	 */
    +	function setMinLength($min_length) {
    +		assert('$min_length >= 0');
    +		$this->_min_length = (int) $min_length;
    +	}
    +
    +	/**
    +	 */
    +	function ADODB_Compress_Bzip2($block_size = null, $work_level = null, $min_length = null) {
    +		if (!is_null($block_size)) {
    +			$this->setBlockSize($block_size);
    +		}
    +
    +		if (!is_null($work_level)) {
    +			$this->setWorkLevel($work_level);
    +		}
    +
    +		if (!is_null($min_length)) {
    +			$this->setMinLength($min_length);
    +		}
    +	}
    +
    +	/**
    +	 */
    +	function write($data, $key) {
    +		if (strlen($data) < $this->_min_length) {
    +			return $data;
    +		}
    +
    +		if (!is_null($this->_block_size)) {
    +			if (!is_null($this->_work_level)) {
    +				return bzcompress($data, $this->_block_size, $this->_work_level);
    +			} else {
    +				return bzcompress($data, $this->_block_size);
    +			}
    +		}
    +
    +		return bzcompress($data);
    +	}
    +
    +	/**
    +	 */
    +	function read($data, $key) {
    +		return $data ? bzdecompress($data) : $data;
    +	}
    +
    +}
    +
    +return 1;
    +
    +?>
    diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-compress-gzip.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-compress-gzip.php
    new file mode 100644
    index 0000000..1fc877d
    --- /dev/null
    +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-compress-gzip.php
    @@ -0,0 +1,93 @@
    +_level;
    +	}
    +
    +	/**
    +	 */
    +	function setLevel($level) {
    +		assert('$level >= 0');
    +		assert('$level <= 9');
    +		$this->_level = (int) $level;
    +	}
    +
    +	/**
    +	 */
    +	function getMinLength() {
    +		return $this->_min_length;
    +	}
    +
    +	/**
    +	 */
    +	function setMinLength($min_length) {
    +		assert('$min_length >= 0');
    +		$this->_min_length = (int) $min_length;
    +	}
    +
    +	/**
    +	 */
    +	function ADODB_Compress_Gzip($level = null, $min_length = null) {
    +		if (!is_null($level)) {
    +			$this->setLevel($level);
    +		}
    +
    +		if (!is_null($min_length)) {
    +			$this->setMinLength($min_length);
    +		}
    +	}
    +
    +	/**
    +	 */
    +	function write($data, $key) {
    +		if (strlen($data) < $this->_min_length) {
    +			return $data;
    +		}
    +
    +		if (!is_null($this->_level)) {
    +			return gzcompress($data, $this->_level);
    +		} else {
    +			return gzcompress($data);
    +		}
    +	}
    +
    +	/**
    +	 */
    +	function read($data, $key) {
    +		return $data ? gzuncompress($data) : $data;
    +	}
    +
    +}
    +
    +return 1;
    +
    +?>
    \ No newline at end of file
    diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-cryptsession.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-cryptsession.php
    new file mode 100644
    index 0000000..8ecbc25
    --- /dev/null
    +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-cryptsession.php
    @@ -0,0 +1,24 @@
    +
    \ No newline at end of file
    diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-encrypt-mcrypt.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-encrypt-mcrypt.php
    new file mode 100644
    index 0000000..12d2e7d
    --- /dev/null
    +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-encrypt-mcrypt.php
    @@ -0,0 +1,109 @@
    +_cipher;
    +	}
    +
    +	/**
    +	 */
    +	function setCipher($cipher) {
    +		$this->_cipher = $cipher;
    +	}
    +
    +	/**
    +	 */
    +	function getMode() {
    +		return $this->_mode;
    +	}
    +
    +	/**
    +	 */
    +	function setMode($mode) {
    +		$this->_mode = $mode;
    +	}
    +
    +	/**
    +	 */
    +	function getSource() {
    +		return $this->_source;
    +	}
    +
    +	/**
    +	 */
    +	function setSource($source) {
    +		$this->_source = $source;
    +	}
    +
    +	/**
    +	 */
    +	function ADODB_Encrypt_MCrypt($cipher = null, $mode = null, $source = null) {
    +		if (!$cipher) {
    +			$cipher = MCRYPT_RIJNDAEL_256;
    +		}
    +		if (!$mode) {
    +			$mode = MCRYPT_MODE_ECB;
    +		}
    +		if (!$source) {
    +			$source = MCRYPT_RAND;
    +		}
    +
    +		$this->_cipher = $cipher;
    +		$this->_mode = $mode;
    +		$this->_source = $source;
    +	}
    +
    +	/**
    +	 */
    +	function write($data, $key) {
    +		$iv_size = mcrypt_get_iv_size($this->_cipher, $this->_mode);
    +		$iv = mcrypt_create_iv($iv_size, $this->_source);
    +		return mcrypt_encrypt($this->_cipher, $key, $data, $this->_mode, $iv);
    +	}
    +
    +	/**
    +	 */
    +	function read($data, $key) {
    +		$iv_size = mcrypt_get_iv_size($this->_cipher, $this->_mode);
    +		$iv = mcrypt_create_iv($iv_size, $this->_source);
    +		$rv = mcrypt_decrypt($this->_cipher, $key, $data, $this->_mode, $iv);
    +		return rtrim($rv, "\0");
    +	}
    +
    +}
    +
    +return 1;
    +
    +?>
    diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-encrypt-md5.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-encrypt-md5.php
    new file mode 100644
    index 0000000..baa917a
    --- /dev/null
    +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-encrypt-md5.php
    @@ -0,0 +1,39 @@
    +encrypt($data, $key);
    +	}
    +
    +	/**
    +	 */
    +	function read($data, $key) {
    +		$md5crypt = new MD5Crypt();
    +		return $md5crypt->decrypt($data, $key);
    +	}
    +
    +}
    +
    +return 1;
    +
    +?>
    \ No newline at end of file
    diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-encrypt-secret.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-encrypt-secret.php
    new file mode 100644
    index 0000000..13deb82
    --- /dev/null
    +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-encrypt-secret.php
    @@ -0,0 +1,48 @@
    +
    diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-encrypt-sha1.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-encrypt-sha1.php
    new file mode 100644
    index 0000000..0884af6
    --- /dev/null
    +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-encrypt-sha1.php
    @@ -0,0 +1,32 @@
    +encrypt($data, $key);
    +
    +	}
    +
    +
    +	function read($data, $key) 
    +	{
    +		$sha1crypt = new SHA1Crypt();
    +		return $sha1crypt->decrypt($data, $key);
    +
    +	}
    +}
    +
    +
    +
    +return 1;
    +?>
    \ No newline at end of file
    diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-sess.txt b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-sess.txt
    new file mode 100644
    index 0000000..d23dac4
    --- /dev/null
    +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-sess.txt
    @@ -0,0 +1,131 @@
    +John,
    +
    +I have been an extremely satisfied ADODB user for several years now.
    +
    +To give you something back for all your hard work, I've spent the last 3
    +days rewriting the adodb-session.php code.
    +
    +----------
    +What's New
    +----------
    +
    +Here's a list of the new code's benefits:
    +
    +* Combines the functionality of the three files:
    +
    +adodb-session.php
    +adodb-session-clob.php
    +adodb-cryptsession.php
    +
    +each with very similar functionality, into a single file adodb-session.php.
    +This will ease maintenance and support issues.
    +
    +* Supports multiple encryption and compression schemes.
    +  Currently, we support:
    +
    +  MD5Crypt (crypt.inc.php)
    +  MCrypt
    +  Secure (Horde's emulation of MCrypt, if MCrypt module is not available.)
    +  GZip
    +  BZip2
    +
    +These can be stacked, so if you want to compress and then encrypt your
    +session data, it's easy.
    +Also, the built-in MCrypt functions will be *much* faster, and more secure,
    +than the MD5Crypt code.
    +
    +* adodb-session.php contains a single class ADODB_Session that encapsulates
    +all functionality.
    +  This eliminates the use of global vars and defines (though they are
    +supported for backwards compatibility).
    +
    +* All user defined parameters are now static functions in the ADODB_Session
    +class.
    +
    +New parameters include:
    +
    +* encryptionKey(): Define the encryption key used to encrypt the session.
    +Originally, it was a hard coded string.
    +
    +* persist(): Define if the database will be opened in persistent mode.
    +Originally, the user had to call adodb_sess_open().
    +
    +* dataFieldName(): Define the field name used to store the session data, as
    +'DATA' appears to be a reserved word in the following cases:
    +	ANSI SQL
    +	IBM DB2
    +	MS SQL Server
    +	Postgres
    +	SAP
    +
    +* filter(): Used to support multiple, simulataneous encryption/compression
    +schemes.
    +
    +* Debug support is improved thru _rsdump() function, which is called after
    +every database call.
    +
    +------------
    +What's Fixed
    +------------
    +
    +The new code includes several bug fixes and enhancements:
    +
    +* sesskey is compared in BINARY mode for MySQL, to avoid problems with
    +session keys that differ only by case.
    +  Of course, the user should define the sesskey field as BINARY, to
    +correctly fix this problem, otherwise performance will suffer.
    +
    +* In ADODB_Session::gc(), if $expire_notify is true, the multiple DELETES in
    +the original code have been optimized to a single DELETE.
    +
    +* In ADODB_Session::destroy(), since "SELECT expireref, sesskey FROM $table
    +WHERE sesskey = $qkey" will only return a single value, we don't loop on the
    +result, we simply process the row, if any.
    +
    +* We close $rs after every use.
    +
    +---------------
    +What's the Same
    +---------------
    +
    +I know backwards compatibility is *very* important to you.  Therefore, the
    +new code is 100% backwards compatible.
    +
    +If you like my code, but don't "trust" it's backwards compatible, maybe we
    +offer it as beta code, in a new directory for a release or two?
    +
    +------------
    +What's To Do
    +------------
    +
    +I've vascillated over whether to use a single function to get/set
    +parameters:
    +
    +$user = ADODB_Session::user(); 	// get
    +ADODB_Session::user($user);		// set
    +
    +or to use separate functions (which is the PEAR/Java way):
    +
    +$user = ADODB_Session::getUser();
    +ADODB_Session::setUser($user);
    +
    +I've chosen the former as it's makes for a simpler API, and reduces the
    +amount of code, but I'd be happy to change it to the latter.
    +
    +Also, do you think the class should be a singleton class, versus a static
    +class?
    +
    +Let me know if you find this code useful, and will be including it in the
    +next release of ADODB.
    +
    +If so, I will modify the current documentation to detail the new
    +functionality.  To that end, what file(s) contain the documentation?  Please
    +send them to me if they are not publically available.
    +
    +Also, if there is *anything* in the code that you like to see changed, let
    +me know.
    +
    +Thanks,
    +
    +Ross
    +
    diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-session-clob.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-session-clob.php
    new file mode 100644
    index 0000000..488dcad
    --- /dev/null
    +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-session-clob.php
    @@ -0,0 +1,23 @@
    +
    \ No newline at end of file
    diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-session.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-session.php
    new file mode 100644
    index 0000000..d740a4e
    --- /dev/null
    +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-session.php
    @@ -0,0 +1,917 @@
    +Execute('UPDATE '. ADODB_Session::table(). ' SET sesskey='. $conn->qstr($new_id). ' WHERE sesskey='.$conn->qstr($old_id));
    +	
    +	/* it is possible that the update statement fails due to a collision */
    +	if (!$ok) {
    +		session_id($old_id);
    +		if (empty($ck)) $ck = session_get_cookie_params();
    +		setcookie(session_name(), session_id(), false, $ck['path'], $ck['domain'], $ck['secure']);
    +		return false;
    +	}
    +	
    +	return true;
    +}
    +
    +/*
    +    Generate database table for session data
    +    @see http://phplens.com/lens/lensforum/msgs.php?id=12280
    +    @return 0 if failure, 1 if errors, 2 if successful.
    +	@author Markus Staab http://www.public-4u.de
    +*/
    +function adodb_session_create_table($schemaFile=null,$conn = null)
    +{
    +    // set default values
    +    if ($schemaFile===null) $schemaFile = ADODB_SESSION . '/session_schema.xml';
    +    if ($conn===null) $conn =& ADODB_Session::_conn();
    +
    +	if (!$conn) return 0;
    +
    +    $schema = new adoSchema($conn);
    +    $schema->ParseSchema($schemaFile);
    +    return $schema->ExecuteSchema();
    +}
    +
    +/*!
    +	\static
    +*/
    +class ADODB_Session {
    +	/////////////////////
    +	// getter/setter methods
    +	/////////////////////
    +	
    +	/*
    +	
    +	function Lock($lock=null)
    +	{
    +	static $_lock = false;
    +	
    +		if (!is_null($lock)) $_lock = $lock;
    +		return $lock;
    +	}
    +	*/
    +	/*!
    +	*/
    +	function driver($driver = null) {
    +		static $_driver = 'mysql';
    +		static $set = false;
    +
    +		if (!is_null($driver)) {
    +			$_driver = trim($driver);
    +			$set = true;
    +		} elseif (!$set) {
    +			// backwards compatibility
    +			if (isset($GLOBALS['ADODB_SESSION_DRIVER'])) {
    +				return $GLOBALS['ADODB_SESSION_DRIVER'];
    +			}
    +		}
    +
    +		return $_driver;
    +	}
    +
    +	/*!
    +	*/
    +	function host($host = null) {
    +		static $_host = 'localhost';
    +		static $set = false;
    +
    +		if (!is_null($host)) {
    +			$_host = trim($host);
    +			$set = true;
    +		} elseif (!$set) {
    +			// backwards compatibility
    +			if (isset($GLOBALS['ADODB_SESSION_CONNECT'])) {
    +				return $GLOBALS['ADODB_SESSION_CONNECT'];
    +			}
    +		}
    +
    +		return $_host;
    +	}
    +
    +	/*!
    +	*/
    +	function user($user = null) {
    +		static $_user = 'root';
    +		static $set = false;
    +
    +		if (!is_null($user)) {
    +			$_user = trim($user);
    +			$set = true;
    +		} elseif (!$set) {
    +			// backwards compatibility
    +			if (isset($GLOBALS['ADODB_SESSION_USER'])) {
    +				return $GLOBALS['ADODB_SESSION_USER'];
    +			}
    +		}
    +
    +		return $_user;
    +	}
    +
    +	/*!
    +	*/
    +	function password($password = null) {
    +		static $_password = '';
    +		static $set = false;
    +
    +		if (!is_null($password)) {
    +			$_password = $password;
    +			$set = true;
    +		} elseif (!$set) {
    +			// backwards compatibility
    +			if (isset($GLOBALS['ADODB_SESSION_PWD'])) {
    +				return $GLOBALS['ADODB_SESSION_PWD'];
    +			}
    +		}
    +
    +		return $_password;
    +	}
    +
    +	/*!
    +	*/
    +	function database($database = null) {
    +		static $_database = 'xphplens_2';
    +		static $set = false;
    +
    +		if (!is_null($database)) {
    +			$_database = trim($database);
    +			$set = true;
    +		} elseif (!$set) {
    +			// backwards compatibility
    +			if (isset($GLOBALS['ADODB_SESSION_DB'])) {
    +				return $GLOBALS['ADODB_SESSION_DB'];
    +			}
    +		}
    +
    +		return $_database;
    +	}
    +
    +	/*!
    +	*/
    +	function persist($persist = null) 
    +	{
    +		static $_persist = true;
    +
    +		if (!is_null($persist)) {
    +			$_persist = trim($persist);
    +		}
    +
    +		return $_persist;
    +	}
    +
    +	/*!
    +	*/
    +	function lifetime($lifetime = null) {
    +		static $_lifetime;
    +		static $set = false;
    +
    +		if (!is_null($lifetime)) {
    +			$_lifetime = (int) $lifetime;
    +			$set = true;
    +		} elseif (!$set) {
    +			// backwards compatibility
    +			if (isset($GLOBALS['ADODB_SESS_LIFE'])) {
    +				return $GLOBALS['ADODB_SESS_LIFE'];
    +			}
    +		}
    +		if (!$_lifetime) {
    +			$_lifetime = ini_get('session.gc_maxlifetime');
    +			if ($_lifetime <= 1) {
    +				// bug in PHP 4.0.3 pl 1  -- how about other versions?
    +				//print "

    Session Error: PHP.INI setting session.gc_maxlifetimenot set: $lifetime

    "; + $_lifetime = 1440; + } + } + + return $_lifetime; + } + + /*! + */ + function debug($debug = null) { + static $_debug = false; + static $set = false; + + if (!is_null($debug)) { + $_debug = (bool) $debug; + + $conn = ADODB_Session::_conn(); + if ($conn) { + $conn->debug = $_debug; + } + $set = true; + } elseif (!$set) { + // backwards compatibility + if (isset($GLOBALS['ADODB_SESS_DEBUG'])) { + return $GLOBALS['ADODB_SESS_DEBUG']; + } + } + + return $_debug; + } + + /*! + */ + function expireNotify($expire_notify = null) { + static $_expire_notify; + static $set = false; + + if (!is_null($expire_notify)) { + $_expire_notify = $expire_notify; + $set = true; + } elseif (!$set) { + // backwards compatibility + if (isset($GLOBALS['ADODB_SESSION_EXPIRE_NOTIFY'])) { + return $GLOBALS['ADODB_SESSION_EXPIRE_NOTIFY']; + } + } + + return $_expire_notify; + } + + /*! + */ + function table($table = null) { + static $_table = 'sessions'; + static $set = false; + + if (!is_null($table)) { + $_table = trim($table); + $set = true; + } elseif (!$set) { + // backwards compatibility + if (isset($GLOBALS['ADODB_SESSION_TBL'])) { + return $GLOBALS['ADODB_SESSION_TBL']; + } + } + + return $_table; + } + + /*! + */ + function optimize($optimize = null) { + static $_optimize = false; + static $set = false; + + if (!is_null($optimize)) { + $_optimize = (bool) $optimize; + $set = true; + } elseif (!$set) { + // backwards compatibility + if (defined('ADODB_SESSION_OPTIMIZE')) { + return true; + } + } + + return $_optimize; + } + + /*! + */ + function syncSeconds($sync_seconds = null) { + static $_sync_seconds = 60; + static $set = false; + + if (!is_null($sync_seconds)) { + $_sync_seconds = (int) $sync_seconds; + $set = true; + } elseif (!$set) { + // backwards compatibility + if (defined('ADODB_SESSION_SYNCH_SECS')) { + return ADODB_SESSION_SYNCH_SECS; + } + } + + return $_sync_seconds; + } + + /*! + */ + function clob($clob = null) { + static $_clob = false; + static $set = false; + + if (!is_null($clob)) { + $_clob = strtolower(trim($clob)); + $set = true; + } elseif (!$set) { + // backwards compatibility + if (isset($GLOBALS['ADODB_SESSION_USE_LOBS'])) { + return $GLOBALS['ADODB_SESSION_USE_LOBS']; + } + } + + return $_clob; + } + + /*! + */ + function dataFieldName($data_field_name = null) { + static $_data_field_name = 'data'; + + if (!is_null($data_field_name)) { + $_data_field_name = trim($data_field_name); + } + + return $_data_field_name; + } + + /*! + */ + function filter($filter = null) { + static $_filter = array(); + + if (!is_null($filter)) { + if (!is_array($filter)) { + $filter = array($filter); + } + $_filter = $filter; + } + + return $_filter; + } + + /*! + */ + function encryptionKey($encryption_key = null) { + static $_encryption_key = 'CRYPTED ADODB SESSIONS ROCK!'; + + if (!is_null($encryption_key)) { + $_encryption_key = $encryption_key; + } + + return $_encryption_key; + } + + ///////////////////// + // private methods + ///////////////////// + + /*! + */ + function _conn($conn=null) { + return $GLOBALS['ADODB_SESS_CONN']; + } + + /*! + */ + function _crc($crc = null) { + static $_crc = false; + + if (!is_null($crc)) { + $_crc = $crc; + } + + return $_crc; + } + + /*! + */ + function _init() { + session_module_name('user'); + session_set_save_handler( + array('ADODB_Session', 'open'), + array('ADODB_Session', 'close'), + array('ADODB_Session', 'read'), + array('ADODB_Session', 'write'), + array('ADODB_Session', 'destroy'), + array('ADODB_Session', 'gc') + ); + } + + + /*! + */ + function _sessionKey() { + // use this function to create the encryption key for crypted sessions + // crypt the used key, ADODB_Session::encryptionKey() as key and session_id() as salt + return crypt(ADODB_Session::encryptionKey(), session_id()); + } + + /*! + */ + function _dumprs($rs) { + $conn =& ADODB_Session::_conn(); + $debug = ADODB_Session::debug(); + + if (!$conn) { + return; + } + + if (!$debug) { + return; + } + + if (!$rs) { + echo "
    \$rs is null or false
    \n"; + return; + } + + //echo "
    \nAffected_Rows=",$conn->Affected_Rows(),"
    \n"; + + if (!is_object($rs)) { + return; + } + + require_once ADODB_SESSION.'/../tohtml.inc.php'; + rs2html($rs); + } + + ///////////////////// + // public methods + ///////////////////// + + /*! + Create the connection to the database. + + If $conn already exists, reuse that connection + */ + function open($save_path, $session_name, $persist = null) { + $conn =& ADODB_Session::_conn(); + + if ($conn) { + return true; + } + + $database = ADODB_Session::database(); + $debug = ADODB_Session::debug(); + $driver = ADODB_Session::driver(); + $host = ADODB_Session::host(); + $password = ADODB_Session::password(); + $user = ADODB_Session::user(); + + if (!is_null($persist)) { + ADODB_Session::persist($persist); + } else { + $persist = ADODB_Session::persist(); + } + +# these can all be defaulted to in php.ini +# assert('$database'); +# assert('$driver'); +# assert('$host'); + + // cannot use =& below - do not know why... + $conn =& ADONewConnection($driver); + + if ($debug) { + $conn->debug = true; +// ADOConnection::outp( " driver=$driver user=$user pwd=$password db=$database "); + } + + if ($persist) { + switch($persist) { + default: + case 'P': $ok = $conn->PConnect($host, $user, $password, $database); break; + case 'C': $ok = $conn->Connect($host, $user, $password, $database); break; + case 'N': $ok = $conn->NConnect($host, $user, $password, $database); break; + } + } else { + $ok = $conn->Connect($host, $user, $password, $database); + } + + if ($ok) $GLOBALS['ADODB_SESS_CONN'] =& $conn; + else + ADOConnection::outp('

    Session: connection failed

    ', false); + + + return $ok; + } + + /*! + Close the connection + */ + function close() { +/* + $conn =& ADODB_Session::_conn(); + if ($conn) $conn->Close(); +*/ + return true; + } + + /* + Slurp in the session variables and return the serialized string + */ + function read($key) { + $conn =& ADODB_Session::_conn(); + $data = ADODB_Session::dataFieldName(); + $filter = ADODB_Session::filter(); + $table = ADODB_Session::table(); + + if (!$conn) { + return ''; + } + + assert('$table'); + + $qkey = $conn->quote($key); + $binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : ''; + + $sql = "SELECT $data FROM $table WHERE sesskey = $binary $qkey AND expiry >= " . time(); + /* Lock code does not work as it needs to hold transaction within whole page, and we don't know if + developer has commited elsewhere... :( + */ + #if (ADODB_Session::Lock()) + # $rs =& $conn->RowLock($table, "$binary sesskey = $qkey AND expiry >= " . time(), $data); + #else + + $rs =& $conn->Execute($sql); + //ADODB_Session::_dumprs($rs); + if ($rs) { + if ($rs->EOF) { + $v = ''; + } else { + $v = reset($rs->fields); + $filter = array_reverse($filter); + foreach ($filter as $f) { + if (is_object($f)) { + $v = $f->read($v, ADODB_Session::_sessionKey()); + } + } + $v = rawurldecode($v); + } + + $rs->Close(); + + ADODB_Session::_crc(strlen($v) . crc32($v)); + return $v; + } + + return ''; + } + + /*! + Write the serialized data to a database. + + If the data has not been modified since the last read(), we do not write. + */ + function write($key, $val) { + $clob = ADODB_Session::clob(); + $conn =& ADODB_Session::_conn(); + $crc = ADODB_Session::_crc(); + $data = ADODB_Session::dataFieldName(); + $debug = ADODB_Session::debug(); + $driver = ADODB_Session::driver(); + $expire_notify = ADODB_Session::expireNotify(); + $filter = ADODB_Session::filter(); + $lifetime = ADODB_Session::lifetime(); + $table = ADODB_Session::table(); + + if (!$conn) { + return false; + } + $qkey = $conn->qstr($key); + + assert('$table'); + + $expiry = time() + $lifetime; + + $binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : ''; + + // crc32 optimization since adodb 2.1 + // now we only update expiry date, thx to sebastian thom in adodb 2.32 + if ($crc !== false && $crc == (strlen($val) . crc32($val))) { + if ($debug) { + echo '

    Session: Only updating date - crc32 not changed

    '; + } + $sql = "UPDATE $table SET expiry = ".$conn->Param('0')." WHERE $binary sesskey = ".$conn->Param('1')." AND expiry >= ".$conn->Param('2'); + $rs =& $conn->Execute($sql,array($expiry,$key,time())); + ADODB_Session::_dumprs($rs); + if ($rs) { + $rs->Close(); + } + return true; + } + $val = rawurlencode($val); + foreach ($filter as $f) { + if (is_object($f)) { + $val = $f->write($val, ADODB_Session::_sessionKey()); + } + } + + $arr = array('sesskey' => $key, 'expiry' => $expiry, $data => $val, 'expireref' => ''); + if ($expire_notify) { + $var = reset($expire_notify); + global $$var; + if (isset($$var)) { + $arr['expireref'] = $$var; + } + } + + if (!$clob) { // no lobs, simply use replace() + $arr[$data] = $conn->qstr($val); + $rs = $conn->Replace($table, $arr, 'sesskey', $autoQuote = true); + ADODB_Session::_dumprs($rs); + } else { + // what value shall we insert/update for lob row? + switch ($driver) { + // empty_clob or empty_lob for oracle dbs + case 'oracle': + case 'oci8': + case 'oci8po': + case 'oci805': + $lob_value = sprintf('empty_%s()', strtolower($clob)); + break; + + // null for all other + default: + $lob_value = 'null'; + break; + } + + // do we insert or update? => as for sesskey + $rs =& $conn->Execute("SELECT COUNT(*) AS cnt FROM $table WHERE $binary sesskey = $qkey"); + ADODB_Session::_dumprs($rs); + if ($rs && reset($rs->fields) > 0) { + $sql = "UPDATE $table SET expiry = $expiry, $data = $lob_value WHERE sesskey = $qkey"; + } else { + $sql = "INSERT INTO $table (expiry, $data, sesskey) VALUES ($expiry, $lob_value, $qkey)"; + } + if ($rs) { + $rs->Close(); + } + + $err = ''; + $rs1 =& $conn->Execute($sql); + ADODB_Session::_dumprs($rs1); + if (!$rs1) { + $err = $conn->ErrorMsg()."\n"; + } + $rs2 =& $conn->UpdateBlob($table, $data, $val, " sesskey=$qkey", strtoupper($clob)); + ADODB_Session::_dumprs($rs2); + if (!$rs2) { + $err .= $conn->ErrorMsg()."\n"; + } + $rs = ($rs && $rs2) ? true : false; + if ($rs1) { + $rs1->Close(); + } + if (is_object($rs2)) { + $rs2->Close(); + } + } + + if (!$rs) { + ADOConnection::outp('

    Session Replace: ' . $conn->ErrorMsg() . '

    ', false); + return false; + } else { + // bug in access driver (could be odbc?) means that info is not committed + // properly unless select statement executed in Win2000 + if ($conn->databaseType == 'access') { + $sql = "SELECT sesskey FROM $table WHERE $binary sesskey = $qkey"; + $rs =& $conn->Execute($sql); + ADODB_Session::_dumprs($rs); + if ($rs) { + $rs->Close(); + } + } + }/* + if (ADODB_Session::Lock()) { + $conn->CommitTrans(); + }*/ + return $rs ? true : false; + } + + /*! + */ + function destroy($key) { + $conn =& ADODB_Session::_conn(); + $table = ADODB_Session::table(); + $expire_notify = ADODB_Session::expireNotify(); + + if (!$conn) { + return false; + } + + assert('$table'); + + $qkey = $conn->quote($key); + $binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : ''; + + if ($expire_notify) { + reset($expire_notify); + $fn = next($expire_notify); + $savem = $conn->SetFetchMode(ADODB_FETCH_NUM); + $sql = "SELECT expireref, sesskey FROM $table WHERE $binary sesskey = $qkey"; + $rs =& $conn->Execute($sql); + ADODB_Session::_dumprs($rs); + $conn->SetFetchMode($savem); + if (!$rs) { + return false; + } + if (!$rs->EOF) { + $ref = $rs->fields[0]; + $key = $rs->fields[1]; + //assert('$ref'); + //assert('$key'); + $fn($ref, $key); + } + $rs->Close(); + } + + $sql = "DELETE FROM $table WHERE $binary sesskey = $qkey"; + $rs =& $conn->Execute($sql); + ADODB_Session::_dumprs($rs); + if ($rs) { + $rs->Close(); + } + + return $rs ? true : false; + } + + /*! + */ + function gc($maxlifetime) { + $conn =& ADODB_Session::_conn(); + $debug = ADODB_Session::debug(); + $expire_notify = ADODB_Session::expireNotify(); + $optimize = ADODB_Session::optimize(); + $sync_seconds = ADODB_Session::syncSeconds(); + $table = ADODB_Session::table(); + + if (!$conn) { + return false; + } + + assert('$table'); + + $time = time(); + + $binary = $conn->dataProvider === 'mysql' ? '/*! BINARY */' : ''; + + if ($expire_notify) { + reset($expire_notify); + $fn = next($expire_notify); + $savem = $conn->SetFetchMode(ADODB_FETCH_NUM); + $sql = "SELECT expireref, sesskey FROM $table WHERE expiry < $time"; + $rs =& $conn->Execute($sql); + ADODB_Session::_dumprs($rs); + $conn->SetFetchMode($savem); + if ($rs) { + $conn->BeginTrans(); + $keys = array(); + while (!$rs->EOF) { + $ref = $rs->fields[0]; + $key = $rs->fields[1]; + $fn($ref, $key); + $del = $conn->Execute("DELETE FROM $table WHERE sesskey='$key'"); + $rs->MoveNext(); + } + $rs->Close(); + + $conn->CommitTrans(); + } + } else { + + if (1) { + $sql = "SELECT sesskey FROM $table WHERE expiry < $time"; + $arr =& $conn->GetAll($sql); + foreach ($arr as $row) { + $sql2 = "DELETE FROM $table WHERE sesskey='$row[0]'"; + $conn->Execute($sql2); + } + } else { + $sql = "DELETE FROM $table WHERE expiry < $time"; + $rs =& $conn->Execute($sql); + ADODB_Session::_dumprs($rs); + if ($rs) $rs->Close(); + } + if ($debug) { + ADOConnection::outp("

    Garbage Collection: $sql

    "); + } + } + + // suggested by Cameron, "GaM3R" + if ($optimize) { + $driver = ADODB_Session::driver(); + + if (preg_match('/mysql/i', $driver)) { + $sql = "OPTIMIZE TABLE $table"; + } + if (preg_match('/postgres/i', $driver)) { + $sql = "VACUUM $table"; + } + if (!empty($sql)) { + $conn->Execute($sql); + } + } + + if ($sync_seconds) { + $sql = 'SELECT '; + if ($conn->dataProvider === 'oci8') { + $sql .= "TO_CHAR({$conn->sysTimeStamp}, 'RRRR-MM-DD HH24:MI:SS')"; + } else { + $sql .= $conn->sysTimeStamp; + } + $sql .= " FROM $table"; + + $rs =& $conn->SelectLimit($sql, 1); + if ($rs && !$rs->EOF) { + $dbts = reset($rs->fields); + $rs->Close(); + $dbt = $conn->UnixTimeStamp($dbts); + $t = time(); + + if (abs($dbt - $t) >= $sync_seconds) { + $msg = __FILE__ . + ": Server time for webserver {$_SERVER['HTTP_HOST']} not in synch with database: " . + " database=$dbt ($dbts), webserver=$t (diff=". (abs($dbt - $t) / 60) . ' minutes)'; + error_log($msg); + if ($debug) { + ADOConnection::outp("

    $msg

    "); + } + } + } + } + + return true; + } +} + +ADODB_Session::_init(); +register_shutdown_function('session_write_close'); + +// for backwards compatability only +function adodb_sess_open($save_path, $session_name, $persist = true) { + return ADODB_Session::open($save_path, $session_name, $persist); +} + +// for backwards compatability only +function adodb_sess_gc($t) +{ + return ADODB_Session::gc($t); +} + +?> diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-sessions.mysql.sql b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-sessions.mysql.sql new file mode 100644 index 0000000..f90de44 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-sessions.mysql.sql @@ -0,0 +1,16 @@ +-- $CVSHeader$ + +CREATE DATABASE /*! IF NOT EXISTS */ adodb_sessions; + +USE adodb_sessions; + +DROP TABLE /*! IF EXISTS */ sessions; + +CREATE TABLE /*! IF NOT EXISTS */ sessions ( + sesskey CHAR(32) /*! BINARY */ NOT NULL DEFAULT '', + expiry INT(11) /*! UNSIGNED */ NOT NULL DEFAULT 0, + expireref VARCHAR(64) DEFAULT '', + data LONGTEXT DEFAULT '', + PRIMARY KEY (sesskey), + INDEX expiry (expiry) +); diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-sessions.oracle.sql b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-sessions.oracle.sql new file mode 100644 index 0000000..8fd5a34 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/adodb-sessions.oracle.sql @@ -0,0 +1,16 @@ +-- $CVSHeader$ + +DROP TABLE adodb_sessions; + +CREATE TABLE sessions ( + sesskey CHAR(32) DEFAULT '' NOT NULL, + expiry INT DEFAULT 0 NOT NULL, + expireref VARCHAR(64) DEFAULT '', + data VARCHAR(4000) DEFAULT '', + PRIMARY KEY (sesskey), + INDEX expiry (expiry) +); + +CREATE INDEX ix_expiry ON sessions (expiry); + +QUIT; diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/session/crypt.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/crypt.inc.php new file mode 100644 index 0000000..41cb06a --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/crypt.inc.php @@ -0,0 +1,161 @@ + +class MD5Crypt{ + function keyED($txt,$encrypt_key) + { + $encrypt_key = md5($encrypt_key); + $ctr=0; + $tmp = ""; + for ($i=0;$ikeyED($tmp,$key)); + } + + function Decrypt($txt,$key) + { + $txt = $this->keyED(base64_decode($txt),$key); + $tmp = ""; + for ($i=0;$i= 58 && $randnumber <= 64) || ($randnumber >= 91 && $randnumber <= 96)) + { + $randnumber = rand(48,120); + } + + $randomPassword .= chr($randnumber); + } + return $randomPassword; + } + +} + + +class SHA1Crypt{ + + function keyED($txt,$encrypt_key) + { + + $encrypt_key = sha1($encrypt_key); + $ctr=0; + $tmp = ""; + + for ($i=0;$ikeyED($tmp,$key)); + + } + + + + function Decrypt($txt,$key) + { + + $txt = $this->keyED(base64_decode($txt),$key); + + $tmp = ""; + + for ($i=0;$i= 58 && $randnumber <= 64) || ($randnumber >= 91 && $randnumber <= 96)) + { + $randnumber = rand(48,120); + } + + $randomPassword .= chr($randnumber); + } + + return $randomPassword; + + } + + + +} +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/session/session_schema.xml b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/session_schema.xml new file mode 100644 index 0000000..3c61ff6 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/session/session_schema.xml @@ -0,0 +1,26 @@ + + + + table for ADOdb session-management + + + session key + + + + + + + + + + + + + + + + + +
    +
    diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/toexport.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/toexport.inc.php new file mode 100644 index 0000000..b9195d2 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/toexport.inc.php @@ -0,0 +1,133 @@ +FieldTypesArray(); + reset($fieldTypes); + while(list(,$o) = each($fieldTypes)) { + + $v = $o->name; + if ($escquote) $v = str_replace($quote,$escquotequote,$v); + $v = strip_tags(str_replace("\n", $replaceNewLine, str_replace("\r\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)))); + $elements[] = $v; + + } + $s .= implode($sep, $elements).$NEWLINE; + } + $hasNumIndex = isset($rs->fields[0]); + + $line = 0; + $max = $rs->FieldCount(); + + while (!$rs->EOF) { + $elements = array(); + $i = 0; + + if ($hasNumIndex) { + for ($j=0; $j < $max; $j++) { + $v = $rs->fields[$j]; + if (!is_object($v)) $v = trim($v); + else $v = 'Object'; + if ($escquote) $v = str_replace($quote,$escquotequote,$v); + $v = strip_tags(str_replace("\n", $replaceNewLine, str_replace("\r\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)))); + + if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote"; + else $elements[] = $v; + } + } else { // ASSOCIATIVE ARRAY + foreach($rs->fields as $v) { + if ($escquote) $v = str_replace($quote,$escquotequote,trim($v)); + $v = strip_tags(str_replace("\n", $replaceNewLine, str_replace("\r\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)))); + + if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote"; + else $elements[] = $v; + } + } + $s .= implode($sep, $elements).$NEWLINE; + $rs->MoveNext(); + $line += 1; + if ($fp && ($line % $BUFLINES) == 0) { + if ($fp === true) echo $s; + else fwrite($fp,$s); + $s = ''; + } + } + + if ($fp) { + if ($fp === true) echo $s; + else fwrite($fp,$s); + $s = ''; + } + + return $s; +} +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/tohtml.inc.php b/seed/galette/manual/image/postinstall/galette/includes/adodb/tohtml.inc.php new file mode 100644 index 0000000..ebc34f9 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/tohtml.inc.php @@ -0,0 +1,195 @@ + +*/ + +// specific code for tohtml +GLOBAL $gSQLMaxRows,$gSQLBlockRows,$ADODB_ROUND; + +$ADODB_ROUND=4; // rounding +$gSQLMaxRows = 1000; // max no of rows to download +$gSQLBlockRows=20; // max no of rows per table block + +// RecordSet to HTML Table +//------------------------------------------------------------ +// Convert a recordset to a html table. Multiple tables are generated +// if the number of rows is > $gSQLBlockRows. This is because +// web browsers normally require the whole table to be downloaded +// before it can be rendered, so we break the output into several +// smaller faster rendering tables. +// +// $rs: the recordset +// $ztabhtml: the table tag attributes (optional) +// $zheaderarray: contains the replacement strings for the headers (optional) +// +// USAGE: +// include('adodb.inc.php'); +// $db = ADONewConnection('mysql'); +// $db->Connect('mysql','userid','password','database'); +// $rs = $db->Execute('select col1,col2,col3 from table'); +// rs2html($rs, 'BORDER=2', array('Title1', 'Title2', 'Title3')); +// $rs->Close(); +// +// RETURNS: number of rows displayed + + +function rs2html(&$rs,$ztabhtml=false,$zheaderarray=false,$htmlspecialchars=true,$echo = true) +{ +$s ='';$rows=0;$docnt = false; +GLOBAL $gSQLMaxRows,$gSQLBlockRows,$ADODB_ROUND; + + if (!$rs) { + printf(ADODB_BAD_RS,'rs2html'); + return false; + } + + if (! $ztabhtml) $ztabhtml = "BORDER='1' WIDTH='98%'"; + //else $docnt = true; + $typearr = array(); + $ncols = $rs->FieldCount(); + $hdr = "\n\n"; + for ($i=0; $i < $ncols; $i++) { + $field = $rs->FetchField($i); + if ($field) { + if ($zheaderarray) $fname = $zheaderarray[$i]; + else $fname = htmlspecialchars($field->name); + $typearr[$i] = $rs->MetaType($field->type,$field->max_length); + //print " $field->name $field->type $typearr[$i] "; + } else { + $fname = 'Field '.($i+1); + $typearr[$i] = 'C'; + } + if (strlen($fname)==0) $fname = ' '; + $hdr .= ""; + } + $hdr .= "\n"; + if ($echo) print $hdr."\n\n"; + else $html = $hdr; + + // smart algorithm - handles ADODB_FETCH_MODE's correctly by probing... + $numoffset = isset($rs->fields[0]) ||isset($rs->fields[1]) || isset($rs->fields[2]); + while (!$rs->EOF) { + + $s .= "\n"; + + for ($i=0; $i < $ncols; $i++) { + if ($i===0) $v=($numoffset) ? $rs->fields[0] : reset($rs->fields); + else $v = ($numoffset) ? $rs->fields[$i] : next($rs->fields); + + $type = $typearr[$i]; + switch($type) { + case 'D': + if (empty($v)) $s .= "\n"; + else if (!strpos($v,':')) { + $s .= " \n"; + } + break; + case 'T': + if (empty($v)) $s .= "\n"; + else $s .= " \n"; + break; + + case 'N': + if (abs($v) - round($v,0) < 0.00000001) + $v = round($v); + else + $v = round($v,$ADODB_ROUND); + case 'I': + $s .= " \n"; + + break; + /* + case 'B': + if (substr($v,8,2)=="BM" ) $v = substr($v,8); + $mtime = substr(str_replace(' ','_',microtime()),2); + $tmpname = "tmp/".uniqid($mtime).getmypid(); + $fd = @fopen($tmpname,'a'); + @ftruncate($fd,0); + @fwrite($fd,$v); + @fclose($fd); + if (!function_exists ("mime_content_type")) { + function mime_content_type ($file) { + return exec("file -bi ".escapeshellarg($file)); + } + } + $t = mime_content_type($tmpname); + $s .= (substr($t,0,5)=="image") ? " \\n" : " \\n"; + break; + */ + + default: + if ($htmlspecialchars) $v = htmlspecialchars(trim($v)); + $v = trim($v); + if (strlen($v) == 0) $v = ' '; + $s .= " \n"; + + } + } // for + $s .= "\n\n"; + + $rows += 1; + if ($rows >= $gSQLMaxRows) { + $rows = "

    Truncated at $gSQLMaxRows

    "; + break; + } // switch + + $rs->MoveNext(); + + // additional EOF check to prevent a widow header + if (!$rs->EOF && $rows % $gSQLBlockRows == 0) { + + //if (connection_aborted()) break;// not needed as PHP aborts script, unlike ASP + if ($echo) print $s . "
    $fname
      ".$rs->UserDate($v,"D d, M Y") ."    ".$rs->UserTimeStamp($v,"D d, M Y, h:i:s") ." ".stripslashes((trim($v))) ." $t$t". str_replace("\n",'
    ',stripslashes($v)) ."
    \n\n"; + else $html .= $s ."\n\n"; + $s = $hdr; + } + } // while + + if ($echo) print $s."\n\n"; + else $html .= $s."\n\n"; + + if ($docnt) if ($echo) print "

    ".$rows." Rows

    "; + + return ($echo) ? $rows : $html; + } + +// pass in 2 dimensional array +function arr2html(&$arr,$ztabhtml='',$zheaderarray='') +{ + if (!$ztabhtml) $ztabhtml = 'BORDER=1'; + + $s = "";//';print_r($arr); + + if ($zheaderarray) { + $s .= ''; + for ($i=0; $i\n"; + } else $s .= " \n"; + $s .= "\n\n"; + } + $s .= '
     
    '; + print $s; +} + +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/xmlschema.dtd b/seed/galette/manual/image/postinstall/galette/includes/adodb/xmlschema.dtd new file mode 100644 index 0000000..4a055da --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/xmlschema.dtd @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +] > \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/xsl/convert-0.1-0.2.xsl b/seed/galette/manual/image/postinstall/galette/includes/adodb/xsl/convert-0.1-0.2.xsl new file mode 100644 index 0000000..8cd534f --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/xsl/convert-0.1-0.2.xsl @@ -0,0 +1,205 @@ + + + + + + + +ADODB XMLSchema +http://adodb-xmlschema.sourceforge.net + + + + 0.2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/xsl/convert-0.2-0.1.xsl b/seed/galette/manual/image/postinstall/galette/includes/adodb/xsl/convert-0.2-0.1.xsl new file mode 100644 index 0000000..61841b4 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/xsl/convert-0.2-0.1.xsl @@ -0,0 +1,207 @@ + + + + + + + +ADODB XMLSchema +http://adodb-xmlschema.sourceforge.net + + + + 0.1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/adodb/xsl/remove-0.2.xsl b/seed/galette/manual/image/postinstall/galette/includes/adodb/xsl/remove-0.2.xsl new file mode 100644 index 0000000..9b10a52 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/adodb/xsl/remove-0.2.xsl @@ -0,0 +1,54 @@ + + + + + + + +ADODB XMLSchema +http://adodb-xmlschema.sourceforge.net + + + +Uninstallation Schema + + + + 0.2 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/database.inc.php b/seed/galette/manual/image/postinstall/galette/includes/database.inc.php new file mode 100644 index 0000000..1ffd417 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/database.inc.php @@ -0,0 +1,106 @@ +debug = false; + if(!@$DB->Connect(HOST_DB, USER_DB, PWD_DB, NAME_DB)) die("No database connection..."); + + if (!defined("PREFIX_DB")) + define("PREFIX_DB",""); + + // Chargement des preferences + $result = $DB->Execute("SELECT * FROM ".PREFIX_DB."preferences"); + if ($result != false) { + $result->MoveFirst(); + while (!$result->EOF) + { + define(strtoupper($result->fields["nom_pref"]), $result->fields["val_pref"]); + $result->MoveNext(); + } + $result->Close(); + } + + function get_echeance ($DB, $cotisant, $exempt_default="") { + if ($exempt_default=="") + { + $requete_cotis = "SELECT bool_exempt_adh + FROM ".PREFIX_DB."adherents + WHERE id_adh=" . $cotisant; + $resultat_cotis = $DB->Execute($requete_cotis); + if ($resultat_cotis->EOF) + $exempt="1"; + else + $exempt=$resultat_cotis->fields[0]; + $resultat_cotis->Close(); + } + else + $exempt=$exempt_default; + + // définition couleur pour adherent exempt de cotisation + if ($exempt=="1") + return ""; + else + { + $requete_cotis = "SELECT * + FROM ".PREFIX_DB."cotisations + WHERE id_adh=" . $cotisant . " + ORDER BY date_cotis"; + $resultat_cotis = $DB->Execute($requete_cotis); + $diff = 0; + $duree_old = 0; + $ts_old = 0; + while (!$resultat_cotis->EOF) + { + // difference avec date precedente + + // timestamp actuel + list($a,$m,$j)=explode("-",$resultat_cotis->fields["date_cotis"]); + $ts = mktime(0,0,0,$m,$j,$a); + + // duree cotisation courante (en s) + $duree = (mktime(0,0,0,$m+$resultat_cotis->fields["duree_mois_cotis"],$j,$a)-mktime(0,0,0,$m,$j,$a)); + + // diff = (date_prec + duree_prec + diff) - date_courante + $diff = ($ts_old + $duree_old + $diff)-$ts; + + if ($diff < 0) + $diff = 0; + + $ts_old = $ts; + $duree_old = $duree; + $resultat_cotis->MoveNext(); + } + $resultat_cotis->Close(); + + if ($ts_old==0) + return ""; + else + $cumul = intval((($ts_old + $duree_old + $diff)-time())/(3600*24)); + } + + // + // Fin du calcul du temps d'adhésion + // + + $return_date = date("d/m/Y",time()+$cumul*3600*24); + return explode("/",$return_date); + } +?> diff --git a/seed/galette/manual/image/postinstall/galette/includes/functions.inc.php b/seed/galette/manual/image/postinstall/galette/includes/functions.inc.php new file mode 100644 index 0000000..206729a --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/functions.inc.php @@ -0,0 +1,150 @@ + + * + * This function matches a proposed e-mail address against a validating + * regular expression. It's intended for use in web registration systems + * and other places where the user is inputting their e-mail address and + * you want to check that it's OK. + * + */ + + function is_valid_email ($address) { + return (preg_match( + '/^[-!#$%&\'*+\\.\/0-9=?A-Z^_`{|}~]+'. // the user name + '@'. // the ubiquitous at-sign + '([-0-9A-Z]+\.)+' . // host, sub-, and domain names + '([0-9A-Z]){2,4}$/i', // top-level domain (TLD) + trim($address))); + } + + function dblog($text, $query="") + { + if (PREF_LOG=="2") + { + $requete = "INSERT INTO ".PREFIX_DB."logs (date_log, ip_log, adh_log, text_log) VALUES (" . $GLOBALS["DB"]->DBTimeStamp(time()) . ", " . $GLOBALS["DB"]->qstr($_SERVER["REMOTE_ADDR"]) . ", " . $GLOBALS["DB"]->qstr($_SESSION["logged_nom_adh"]) . ", " . $GLOBALS["DB"]->qstr($text."\n".$query) . ");"; + $GLOBALS["DB"]->Execute($requete); + } + elseif (PREF_LOG=="1") + { + $requete = "INSERT INTO ".PREFIX_DB."logs (date_log, ip_log, adh_log, text_log) VALUES (" . $GLOBALS["DB"]->DBTimeStamp(time()) . ", " . $GLOBALS["DB"]->qstr($_SERVER["REMOTE_ADDR"]) . ", " . $GLOBALS["DB"]->qstr($_SESSION["logged_nom_adh"]) . ", " . $GLOBALS["DB"]->qstr($text) . ");"; + $GLOBALS["DB"]->Execute($requete); + } + } + + + + + function resizeimage($img,$img2,$w,$h) + { + if (function_exists("imagecreate")) + { + $ext = substr($img,-4); + $imagedata = getimagesize($img); + $ratio = $imagedata[0]/$imagedata[1]; + if ($imagedata[0]>$imagedata[1]) + $h = $w/$ratio; + else + $w = $h*$ratio; + $thumb = imagecreate ($w, $h); + switch($ext) + { + case ".jpg": + $image = ImageCreateFromJpeg($img); + imagecopyresized ($thumb, $image, 0, 0, 0, 0, $w, $h, $imagedata[0], $imagedata[1]); + imagejpeg($thumb, $img2); + break; + case ".png": + $image = ImageCreateFromPng($img); + imagecopyresized ($thumb, $image, 0, 0, 0, 0, $w, $h, $imagedata[0], $imagedata[1]); + imagepng($thumb, $img2); + break; + case ".gif": + if (function_exists("imagegif")) + { + $image = ImageCreateFromGif($img); + imagecopyresized ($thumb, $image, 0, 0, 0, 0, $w, $h, $imagedata[0], $imagedata[1]); + imagegif($thumb, $img2); + } + break; + } + } + } + + function custom_html_entity_decode( $given_html, $quote_style = ENT_QUOTES ) + { + $trans_table = array_flip(get_html_translation_table( HTML_ENTITIES, $quote_style )); + $trans_table['''] = "'"; + return ( strtr( $given_html, $trans_table ) ); + } + + + + + +?> diff --git a/seed/galette/manual/image/postinstall/galette/includes/lang.inc.php b/seed/galette/manual/image/postinstall/galette/includes/lang.inc.php new file mode 100644 index 0000000..ec80974 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/lang.inc.php @@ -0,0 +1,13 @@ + diff --git a/seed/galette/manual/image/postinstall/galette/includes/phppdflib/COPYING b/seed/galette/manual/image/postinstall/galette/includes/phppdflib/COPYING new file mode 100644 index 0000000..a43ea21 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/phppdflib/COPYING @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 675 Mass Ave, Cambridge, MA 02139, USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + Appendix: How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) 19yy + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) 19yy name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/seed/galette/manual/image/postinstall/galette/includes/phppdflib/chart.class.php b/seed/galette/manual/image/postinstall/galette/includes/phppdflib/chart.class.php new file mode 100644 index 0000000..cc0b7ce --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/phppdflib/chart.class.php @@ -0,0 +1,130 @@ +clearchart(); + } + + function clearchart() + { + // Default colors + unset($this->colors); + // This oughta make things more readible + $white['red'] = $white['green'] = $white['blue'] = 1; + $black['red'] = $black['green'] = $black['blue'] = 0; + $this->colors['background'] = $white; + $this->colors['border'] = $black; + $this->colors['hlabel'] = $black; + $this->colors['vlabel'] = $black; + $this->colors['vgrade'] = $black; + $this->colors['hgrade'] = $black; + unset($this->series); + } + + /* Set up default colors to use globally on the chart + */ + function setcolor($name, $red, $green, $blue) + { + $this->colors[$name]['red'] = $red; + $this->colors[$name]['green'] = $green; + $this->colors[$name]['blue'] = $blue; + } + + function add_series($name, $points, $color = 'black', $width = 1, $style = 'default') + { + $t['points'] = $points; + $t['color'] = $color; + $t['width'] = $width; + $t['style'] = $style; + $this->series[$name] = $t; + } + + function place_chart($page, $left, $bottom, $width, $height, $type = 'line') + { + switch (strtolower($type)) { + case 'pie' : + case '3dpie' : + case 'bar' : + case '3dbar' : + case '3dline' : + case 'line' : + default : + $this->_place_line_chart($page, $left, $bottom, $width, $height); + } + } + + function _place_line_chart($page, $left, $bottom, $width, $height) + { + // First a filled rectangle to set background color + $this->_fill_background($page, $left, $bottom, $width, $height); + // caclulate a scale + $low = $high = $numx = 0; + foreach($this->series as $data) { + foreach($data['points'] as $value) { + if ($value < $low) $low = $value; + if ($value > $high) $high = $value; + } + if (count($data['points']) > $numx) $numx = count($data); + } + if (($high - $low) <= 0) return false; + $xscale = $width / $numx; + $yscale = $height / ($high - $low); + foreach($this->series as $data) { + $a['strokecolor'] = $this->pdf->get_color($data['color']); + $a['width'] = $data['width']; + $c = 0; + unset($x); + unset($y); + foreach ($data['points'] as $value) { + $x[$c] = ($c * $xscale) + $left; + //echo $x[$c] . " "; + $y[$c] = (($value - $low) * $yscale) + $bottom; + //echo $y[$c] . "
    \n"; + $c++; + } + $this->pdf->draw_line($x, $y, $page, $a); + } + } + + function _fill_background($page, $left, $bottom, $width, $height) + { + $a['fillcolor'] = $this->colors['background']; + $a['mode'] = 'fill'; + $this->pdf->draw_rectangle($bottom + $height, + $left, + $bottom, + $left + $width, + $page, + $a); + } +} + +?> diff --git a/seed/galette/manual/image/postinstall/galette/includes/phppdflib/import.class.php b/seed/galette/manual/image/postinstall/galette/includes/phppdflib/import.class.php new file mode 100644 index 0000000..51ca6bd --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/phppdflib/import.class.php @@ -0,0 +1,443 @@ +xref = + $this->pdftolib = + $this->ob = array(); + $this->d = new StreamHandler($data); + if (!$this->capture_xref()) { + echo "Couldn't find xref\n"; + return false; + } + foreach ($this->xref as $pdfid => $junk) { + $this->extract($pdfid); + } + foreach ($this->ob as $id => $junk) { + $this->import_ob($id); + } + $root = $this->find_root(); + $this->recursive_create($root); + return true; + } + + function capture_xref() + { + $data = &$this->d; + // First we find the start of the xref + $data->end(); + while ($data->previous_word() != 'startxref') + ; + // Now we capture where the xref starts + $data->next_word(); // slurp 'startxref' + $xref = $data->next_word(); + $data->l = (int)$xref; + echo "found xref at $xref
    \n"; + if ($data->next_word() != 'xref') { + echo "Proposed xref location was bogus: $xref\n"; + return false; + } + $firstx = $data->next_word(); + $numx = $data->next_word(); + echo "firstx=$firstx, numx=$numx
    \n"; + for ($i = $firstx; $i < $firstx + $numx; $i++) { + $loc = $data->next_word(); + $gen = $data->next_word(); + if ($data->next_word() == 'n') { + $this->xref[$i] = $loc; + } + } + return true; + } + + function find_root() + { + // Find trailer + $d = &$this->d; + $d->end(); + while ($d->previous_word() != 'trailer') + ; + while ($d->next_word() != '/Root') + ; + return $d->next_word(); + } + + function recursive_create($id) + { + if (!isset($this->ob[$id]['/Type'])} + $this->ob[$id]['/Type'] = ''; + switch ($this->ob[$id]['/Type']) { + case '/Info' : + return false; + break; + + case '/Root' : + return $this-> + break; + } + } + + function extract($id) + { + if (!isset($this->ob[$id])) { + $location = $this->xref[$id]; + $data = &$this->d; + $data->l = $location; + $id = $data->next_word(); + $gn = $data->next_word(); + echo "Found $id $gn R at $location
    \n"; + flush(); + $this->extract_obj($id); + } + return $this->ob[$id]; + } + + function extract_obj($id) + { + $d = &$this->d; + // Magic test + if ($d->next_word() != 'obj') { + echo "Didn't find an object here!
    \n"; + return false; + } + $this->ob[$id]['value'] = ''; + while (true) { + $d->skip_whitespace(); + if (substr($d->d, $d->l, 2) == '<<') { + echo "Found a dictionary
    \n"; + $this->ob[$id] = $this->extract_dictionary(); + } else { + $w = $d->next_word(); + if ($w == 'endobj') break; + if ($w == 'stream') { + echo "Found a stream: {$d->l}
    \n"; + $d->l -= 6; + $this->ob[$id]['stream'] = + $this->extract_stream($this->ob[$id]); + } else { + // Must be a raw value + echo "Assuming a raw value in object
    \n"; + $this->ob[$id]['value'] .= $w . ' '; + } + } + } + echo "
    \n";
    +        print_r($this->ob[$id]);
    +        echo "
    \n"; + } + + function extract_dictionary() + { + $d = &$this->d; + if (substr($d->d, $d->l, 2) != '<<') { + echo "Didn't find a dictionary here!
    \n"; + return array(); + } + $d->l += 2; // Slurp the '<<' + $r = array(); + $r['itype'] = 'dictionary'; + $label = false; + $state = array(); + while (true) { + $d->skip_whitespace(); + if (substr($d->d, $d->l, 2) == '>>') { + echo "Found end of dictionary
    \n"; + $d->l += 2; + if (count($state) > 0) { + $r[$l] = ''; + foreach ($state as $v) { + $r[$l] .= $v . ' '; + echo "Popping remainer of stack for [$l] = '{$r[$l]}'
    \n"; + } + } + break; + } + if (substr($d->d, $d->l, 2) == '<<') { + echo "Found subdictionary
    \n"; + $r[$l] = $this->extract_dictionary(); + $label = false; + continue; + } + if (substr($d->d, $d->l, 1) == '[') { + echo "Analyzing array '" . substr($d->d, $d->l, 15) . + "...' for [$l]
    \n"; + $r[$l] = $d->get_array(); + $label = false; + continue; + } + $w = $d->next_word(); + if (!$label) { + echo "Making '$w' a label
    \n"; + $label = true; + $l = $w; + } else { + echo "Current character = '" . $d->cc() . "'
    \n"; + if ($w{0} == '/') { + if (!isset($state[0])) { + echo "Assigning '$w' as value of [$l]
    \n"; + $r[$l] = $w; + } else { + $d->rewind(); + echo "Popping the stack for [$l]
    \n"; + $r[$l] = $state[0]; + $state = array(); + } + } else if ($w{0} == '(' && $w{strlen($w) - 1} == ')') { + // We've got a string + echo "Assigning string value '$w' to [$l]
    \n"; + $r[$l] = $w; + } else if ($w == 'R') { + $ir = $state[0] . ' ' . $state[1] . ' R'; + echo "Stored IR $ir
    \n"; + $r[$l] = $ir; + $state = array(); + } else { + // Push this on the stack + echo "pushing '$w' on the stack
    \n"; + $state[] = $w; + continue; + } + $label = false; + } + } + return $r; + } + + function extract_stream($meta) + { + $d = &$this->d; + $t = $d->next_word(); + if ($t == 'stream') { + if ($d->strpos($meta['/Length'], 'R')) { + // We must resolve an indirect reference + echo "Resolving IR for /Length
    \n"; + $t = $d->l; + $this->extract((int)$meta['/Length']); + $d->l = $t; + $length = $this->ob[(int)$meta['/Length']]['value']; + } else { + $length = (int)$meta['/Length']; + } + echo "Stream should be {$length}
    \n"; + $stream = substr($d->d, $d->l + 1, $length); + $d->l += 1 + $length; + $d->next_word(); // Consume "endstream" + if (!isset($meta['/Filter'])) $meta['/Filter'] = ''; + $r = new StreamHandler($stream, $meta['/Filter']); + return $r; + } else { + echo "I didn't find a stream here: '$t'
    \n"; + $d->rewind(); + return ''; + } + } +} + +class StreamHandler +{ + var $d; + var $l; + + function StreamHandler($stream, $filter = '') + { + $this->l = 0; + if ($this->strpos($filter, 'FlateDecode')) { + $this->d = trim(gzuncompress($stream)) . "\n"; + } else { + $this->d = trim($stream) . "\n"; + } + } + + function get_array() + { + $s = new StreamHandler($this->read_array()); + echo "Got array of '" . $s->d . "'
    \n"; + $r = array(); + $r['itype'] = 'array'; + $as = array(); + while ($s->l < strlen($s->d) - 1) { + $c = $s->next_word(); + if ($c == 'R') { + $t = $as[0] . ' ' . $as[1] . ' R'; + $r[] = $t; + $as = array(); + } else { + $as[] = $c; + } + } + return array_merge($r, $as); + } + + function read_array() + { + $this->back_to_array(); + if ($this->cc() != '[') { + // No array here + echo "I don't see an array: '" . + substr($this->d, $this->l, 15) . "...'
    \n"; + return ''; + } + $this->next(); + $r = ''; + do { + $r .= $this->cc(); + $this->l++; + } while ($this->cc() != ']'); + $this->next(); + return $r; + } + + function back_to_array() + { + if ($this->cc() != '[') { + $this->l--; + } + } + + function end() + { + $this->l = strlen($this->d) - 1; + } + + function start() + { + $this->l = 0; + } + + function next_word() + { + $this->skip_whitespace(); + $r = ''; + // Slurp a PDF string + if ($this->cc() == '(') { + while ($this->cc() != ')' || $this->cc($this->l - 1) == '\\') { + $r .= $this->cc(); + $this->next(); + } + $r .= $this->cc(); + $this->next(); + return $r; + } + do { + $r .= $this->cc(); + $this->next(); + } while (!$this->is_whitespace() && + !$this->boundry() && + $this->l < strlen($this->d)); + return $r; + } + + function previous_word() + { + $this->rewind(); + $r = $this->next_word(); + $this->rewind(); + return $r; + } + + // Backs up 1 word + function rewind() + { + $this->skip_whitespace(false); + do { + $this->l--; + } while (!$this->is_whitespace() && !$this->boundry()); + } + + function skip_whitespace($forward = true) + { + while ($this->is_whitespace()) { + if ($forward) { + $this->next(); + } else { + $this->l--; + } + if ($this->l == 0 || $this->l == (strlen($this->d) - 1)) break; + } + return $this->l; + } + + function boundry($c = false) + { + if ($c === false) $c = $this->cc(); + if ($this->strpos('()/><[]', $c)) { + return true; + } else { + return false; + } + } + + function is_whitespace($c = '') + { + if ($c == '') $c = $this->cc(); + if ($c == ' ' || + $c == "\x0a" || + $c == "\x0d" || + $c == "\t") { + return true; + } else { + return false; + } + } + + // Returns current byte (character) + function cc($l = false) + { + if ($l === false) $l = $this->l; + return $this->d{$l}; + } + + function next() + { + $this->l++; + if ($this->l >= strlen($this->d)) { + echo "fell off the end!
    \n"; + $this->end(); + } + } + + function strpos($haystack, $needle) + { + if (strpos($haystack, $needle) === false) { + return false; + } else { + return true; + } + } +} +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/phppdflib/packer.class.php b/seed/galette/manual/image/postinstall/galette/includes/phppdflib/packer.class.php new file mode 100644 index 0000000..f5929ad --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/phppdflib/packer.class.php @@ -0,0 +1,357 @@ +new_page() + * that saves the relevent information for packer operation + */ + function new_page() + { + $this->curpage = $this->pdf->new_page(); + $right = $this->pdf->objects[$this->curpage]['width'] - + $this->pdf->default['margin-right']; + $top = $this->pdf->objects[$this->curpage]['height'] - + $this->pdf->default['margin-top']; + $this->fields[] = $this->newfield($this->pdf->default['margin-left'], + $right, + $this->pdf->default['margin-bottom'], + $top); + foreach (array('margin-left', + 'margin-right', + 'margin-top', + 'margin-bottom') as $margin) { + $this->pdf->objects[$this->curpage][$margin] = 0; + } + return $this->curpage; + } + + /* Fill text into the remaining space. + * padding is in ems + * minwidth is in ems, current defaults are used for all parameters + */ + function fill_text($text, $padding = 1, $minwidth = 10) + { + $ignore = array(); + $m = $this->pdf->strlen('M'); + $w = $minwidth * $m; + $p = $m * $padding; + while (strlen($text)) { + $r = $this->find_upper_left($ignore); + if ($r === false) break; + $f = $this->fields[$r]; + if (($f->r - $f->l - (2 * $p)) <= $w) { + $ignore[] = $r; + continue; + } + $text = $this->pdf->draw_paragraph($f->t - $p, $f->l + $p, + $f->b + $p, $f->r - $p, + $text, $this->curpage); + if (is_string($text)) { + unset($this->fields[$r]); + $this->fields_cleanup(); + } else { + $this->fields[$r]->t = $text; + $this->fields_cleanup(); + break; + } + } + if (is_string($text)) + return $text; + else + return true; + } + + /* Here we manually allocate a set region from the fields + * This is likely to be the foundation of everything else that's + * done in this class. $space is a 'field' object. + */ + function allocate($space) + { + foreach ($this->fields as $fid => $field) { + if (!$space->intersects($field)) continue; + if ($space->obliterates($field)) { + unset($this->fields[$fid]); + $this->fields_cleanup(); + continue; + } + if ($space->punches($field)) { + $this->punch($space, $fid); + continue; + } + if (($n = $space->notches($field)) != 0) { + $this->notch($space, $fid, $n); + } + } + $this->merge(); + } + + // Punch a hole in $target + function punch($hole, $target) { + $t = $this->fields[$target]; + $this->newfield($hole->l, $hole->r, $t->t, $hole->t); // top + $this->newfield($hole->l, $hole->r, $t->b, $hole->b); // bottom + $this->newfield($t->l, $hole->l, $t->t, $t->b); // left + $this->fields[$target]->l = $hole->r; // right + $this->fields_cleanup(); + } + + /* Don't call this unless you've already established the operation to + * be a notch, behaviour is undefined otherwise. + */ + function notch($hole, $target, $how) { + $t = &$this->fields[$target]; + // 3 scenerios + if ($how == 1 || $how == 2 || $how == 4 || $how == 8) { + // Side notch + switch ($how) { + case 1 : // Bottom + $this->newfield($t->l, $hole->l, $t->t, $t->b); + $this->newfield($t->r, $hole->r, $t->t, $t->b); + $t->l = $hole->l; + $t->r = $hole->r; + $t->b = $hole->t; + break; + case 4 : // Top + $this->newfield($t->l, $hole->l, $t->t, $t->b); + $this->newfield($t->r, $hole->r, $t->t, $t->b); + $t->l = $hole->l; + $t->r = $hole->r; + $t->t = $hole->b; + break; + case 2 : // Left + $this->newfield($t->l, $hole->r, $t->t, $hole->t); + $this->newfield($t->l, $hole->r, $hole->b, $t->b); + $t->l = $hole->r; + break; + case 8 : // Right + $this->newfield($t->r, $hole->l, $t->t, $hole->t); + $this->newfield($t->r, $hole->l, $hole->b, $t->b); + $t->r = $hole->l; + break; + } + } else if ($how == 3 || $how == 6 || $how == 12 || $how == 9) { + // Corner notch + if (($how & 2) == 2) { // Notching left side + if (($how & 4) == 4) { // left top + $this->newfield($t->l, $hole->r, $hole->b, $t->b); + } else { // left bottom + $this->newfield($t->l, $hole->r, $hole->t, $t->t); + } + $t->l = $hole->r; + } else { // notching right side + if (($how & 4) == 4) { // right top + $this->newfield($t->r, $hole->l, $hole->b, $t->b); + } else { // right bottom + $this->newfield($t->r, $hole->l, $hole->t, $t->t); + } + $t->r = $hole->l; + } + } else { + // We assume it must be a chop + switch ($how) { + case 11 : // bottom + $t->b = $hole->t; break; + + case 7 : // left + $t->l = $hole->r; break; + + case 14 : // top + $t->t = $hole->b; break; + + case 13 : // right + $t->r = $hold->l; break; + + default : // error + $this->pdf->push_error(666, 'notch encountered invalid chop'); + } + } + } + + function find_upper_left($ignore = array()) + { + if (!count($this->fields)) return false; + $r = false; + $top = $this->pdf->objects[$this->curpage]['height']; + $dist = $this->dist($top, $this->pdf->objects[$this->curpage]['width']); + foreach ($this->fields as $fid => $f) { + if (in_array($fid, $ignore)) continue; + $tdist = $this->dist($top - $f->t, $f->l); + if ($tdist < $dist) { + $r = $fid; + $dist = $tdist; + } + } + return $r; + } + + function dist($x, $y) + { + return pow(pow($x, 2) + pow($y, 2), 0.5); + } + + /* Scan the array of regions for regions that share an exactly equal border + * and can thus be joined without altering the function of things. + */ + function merge() + { + foreach ($this->fields as $fid1 => $f1) { + foreach ($this->fields as $fid2 => $f2) { + if ($f1->l == $f2->r && $f1->t == $f2->t && $f1->b == $f2->b) { + $this->fields[$fid1]->l = $f2->l; + unset($this->fields[$fid2]); + } + if ($f1->r == $f2->l && $f1->t == $f2->t && $f1->b == $f2->b) { + $this->fields[$fid1]->r = $f2->r; + unset($this->fields[$fid2]); + } + if ($f1->t == $f2->b && $f1->l == $f2->l && $f1->l == $f2->l) { + $this->fields[$fid1]->t = $f2->t; + unset($this->fields[$fid2]); + } + if ($f1->b == $f2->t && $f1->l == $f2->l && $f1->l == $f2->l) { + $this->fields[$fid1]->b = $f2->b; + unset($this->fields[$fid2]); + } + } + } + $this->fields_cleanup(); + } + + function newfield($l, $r, $t, $b) + { + $temp = new field($l, $r, $t, $b); + $this->fields[] = $temp; + } + + /* PHP seems to have a lot of trouble not messing up its arrays. Some + * operations leave gaps in the array that I wouldn't have expected to do + * so. In lieu of having to contstantly check for gaps in the array prior + * to processing, I call this to remove them whenever I identify an + * operation that can cause gaps. Hopefully I'll find a better way to + * handle this, as this seems like a hack to me. + */ + function fields_cleanup() + { + $t = array(); + foreach ($this->fields as $f) { + if (is_object($f)) { + $t[] = $f; + } + } + $this->fields = $t; + reset($this->fields); + } +} + +class field +{ + var $l, $r, $t, $b; // left, right, top, bottom + + function field($x1, $x2, $y1, $y2) + { + if ($x1 < $x2) { + $this->l = $x1; + $this->r = $x2; + } else { + $this->l = $x2; + $this->r = $x1; + } + if ($y1 < $y2) { + $this->t = $y2; + $this->b = $y1; + } else { + $this->t = $y1; + $this->b = $y2; + } + } + + // Return true if any part of me includes $target + function intersects($target) + { + if ($this->t <= $target->b) return false; + if ($this->b >= $target->t) return false; + if ($this->l >= $target->r) return false; + if ($this->r <= $target->l) return false; + return true; + } + + // Returns true if this field completely covers $target + function obliterates($target) + { + if ($this->l <= $target->l && + $this->r >= $target->r && + $this->t >= $target->t && + $this->b <= $target->b) { + return true; + } else { + return false; + } + } + + // Returns true if this field punches a hole in $target + function punches($target) { + if ($this->l > $target->l && + $this->r < $target->r && + $this->t < $target->t && + $this->b > $target->b) { + return true; + } else { + return false; + } + } + + /* Returns a bitmap of notches in $target + * 0 = no notches + * 1 = notches bottom + * 2 = notches left + * 4 = notches top + * 8 = notches right + */ + function notches($target) { + $notch = 0; + if ($this->t > $target->b && $this->b <= $target->b) $notch = 1; + if ($this->r > $target->l && $this->l <= $target->l) $notch += 2; + if ($this->b < $target->t && $this->t >= $target->t) $notch += 4; + if ($this->l < $target->r && $this->r >= $target->r) $notch += 8; + return $notch; + } +} + +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/phppdflib/phppdflib.class.php b/seed/galette/manual/image/postinstall/galette/includes/phppdflib/phppdflib.class.php new file mode 100644 index 0000000..caf419f --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/phppdflib/phppdflib.class.php @@ -0,0 +1,1687 @@ +generate() + * is called. + * The layout of ->objects does not directly + * mimic the pdf format, although it is similar. + * nextoid always holds the next available oid ( oid is short for object id ) + */ + var $objects, $nextoid; + + /* xreftable is an array containing data to + * create the xref section (PDF calls it a referance table) + */ + var $xreftable, $nextobj; + + /* These arrays allow quick translation between + * pdflib OIDs and the final PDF OIDs (OID stands for object ids) + */ + var $libtopdf, $pdftolib; + + // Errors + var $ermsg = array(), $erno = array(); + + var $builddata; // Various data required during the pdf build + var $nextpage; // Tracks the next page number + var $widths, $needsset; // Store the font width arrays here + var $default; // Default values for objects + var $x, $chart, $template, + $packer, $import; // extension class is instantiated here + var $debug = 0, $dbs = ''; // Default debug level, higher = more data + + /* Constructor function: is automatically called when the + * object is created. Used to set up the environment + */ + function pdffile() + { + /* Per spec, obj 0 should always have a generation + * number of 65535 and is always free + */ + $this->xreftable[0]["gennum"] = 65535; + $this->xreftable[0]["offset"] = 0; + $this->xreftable[0]["free"] = "f"; + + // Object #1 will always be the Document Catalog + $this->xreftable[1]["gennum"] = 0; + $this->xreftable[1]["free"] = "n"; + + // Object #2 will always be the root pagenode + $this->xreftable[2]["gennum"] = 0; + $this->xreftable[2]["free"] = "n"; + $this->pdftolib[2] = 1; + $this->libtopdf[1] = 2; + + // Object #3 is always the resource library + $this->xreftable[3]["gennum"] = 0; + $this->xreftable[3]["free"] = "n"; + + /* nextoid starts at 2 because all + * drawing functions return either the + * object ID or FALSE on error, so we can't + * return an OID of 0, because it equates + * to false and error checking would think + * the procedure failed + */ + $this->nextoid = 2; + $this->nextobj = 3; + + // Pages start at 0 + $this->nextpage = 0; + + // Font width tables are not set unless they are needed + $this->needsset = true; + + // Set all the default values + $t['pagesize'] = 'letter'; + $t['font'] = 'Helvetica'; + $t['height'] = 12; + $t['align'] = 'left'; + $t['width'] = 1; + $t['rotation'] = 0; + $t['scale'] = 1; + $t['strokecolor'] = $this->get_color('black'); + $t['fillcolor'] = $this->get_color('black'); + $t['margin-left'] = $t['margin-right'] = $t['margin-top'] = $t['margin-bottom'] =72; + $t['tmode'] = 0; // Text: fill + $t['smode'] = 1; // Shapes: stroke + $this->default = $t; + } + +/****************************************************** + * These functions are the public ones, they are the * + * way that the user will actually enter the data * + * that will become the pdf * + ******************************************************/ + + function set_default($setting, $value) + { + switch ($setting) { + case 'margin' : + $this->default['margin-left'] = $value; + $this->default['margin-right'] = $value; + $this->default['margin-top'] = $value; + $this->default['margin-bottom'] = $value; + break; + + case 'mode' : + $this->default['tmode'] = $this->default['smode'] = $value; + break; + + default : + $this->default[$setting] = $value; + } + return true; + } + + function draw_rectangle($top, $left, $bottom, $right, $parent, $attrib = array()) + { + if ($this->objects[$parent]["type"] != "page") { + $this->_push_std_error(6001); + return false; + } + $o = $this->_addnewoid(); + $attrib = $this->_resolve_param($attrib, false); + $this->_resolve_colors($n, $attrib); + $this->objects[$o] = $n; + $this->objects[$o]["width"] = $attrib["width"]; + $this->objects[$o]["type"] = "rectangle"; + $this->_adjust_margin($left, $top, $parent); + $this->_adjust_margin($right, $bottom, $parent); + $this->objects[$o]["top"] = $top; + $this->objects[$o]["left"] = $left; + $this->objects[$o]["bottom"] = $bottom; + $this->objects[$o]["right"] = $right; + $this->objects[$o]["parent"] = $parent; + $this->objects[$o]["mode"] = $this->_resolve_mode($attrib, 'smode'); + $this->_debug_var(10, "Placed rectangle: ", $this->objects[$o]); + return $o; + } + + function draw_circle($x, $y, $r, $parent, $attrib = array()) + { + if ($this->objects[$parent]["type"] != "page") { + $this->_push_std_error(6001); + return false; + } + $o = $this->_addnewoid(); + $attrib = $this->_resolve_param($attrib, false); + $this->_resolve_colors($n, $attrib); + $n['width'] = $attrib['width']; + $this->_adjust_margin($x, $y, $parent); + $n['x'] = $x; + $n['y'] = $y; + $n['radius'] = $r; + $n['type'] = 'circle'; + $n['parent'] = $parent; + $n['mode'] = $this->_resolve_mode($attrib, 'smode'); + $this->objects[$o] = $n; + $this->_debug_var(10, "Placed circle ", $o); + return $o; + } + + function draw_line($x, $y, $parent, $attrib = array()) + { + if ($this->objects[$parent]["type"] != "page") { + $this->_push_std_error(6001); + return false; + } + if (count($x) != count($y)) { + $this->_push_error(6002, "X & Y variables must have equal number of elements"); + return false; + } + $o = $this->_addnewoid(); + $attrib = $this->_resolve_param($attrib, false); + $this->_resolve_colors($n, $attrib); + $this->objects[$o] = $n; + @$this->objects[$o]["width"] = $attrib["width"]; + $this->objects[$o]['mode'] = $this->_resolve_mode($attrib, 'smode'); + $this->objects[$o]["type"] = "line"; + foreach ($x as $key => $value) { + if (isset($x[$key]) && isset($y[$key])) { + $this->_adjust_margin($x[$key], $y[$key], $parent); + } + } + $this->objects[$o]["x"] = $x; + $this->objects[$o]["y"] = $y; + $this->objects[$o]["parent"] = $parent; + $this->_debug_var(10, 'Placed line', $this->objects[$o]); + return $o; + } + + // draw text + function draw_text($left, $bottom, $text, $parent, $attrib = array()) + { + if ($this->objects[$parent]["type"] != "page") { + $this->_push_std_error(6001); + return false; + } + $attrib = $this->_resolve_param($attrib); + // Validate the font + if (!($n["font"] = $this->_use_font($attrib))) { + // Couldn't find/add the font + $this->_push_error(6003, "Font was not found"); + return false; + } + if (isset($attrib["rotation"])) { + $n["rotation"] = $attrib["rotation"]; + } + $n['mode'] = $this->_resolve_mode($attrib, 'tmode'); + if (isset($attrib["height"]) && $attrib["height"] > 0) { + $n["height"] = $attrib["height"]; + } + $this->_resolve_colors($n, $attrib); + $n["type"] = "texts"; + $this->_adjust_margin($left, $bottom, $parent); + $n["left"] = $left; + $n["bottom"] = $bottom; + $n["text"] = $text; + $n["parent"] = $parent; + + $o = $this->_addnewoid(); + $this->objects[$o] = $n; + $this->_debug_var(10, 'Placed text', $n); + return $o; + } + + function new_page($size = null) + { + if (is_null($size)) { + $size = $this->default['pagesize']; + } + switch ($size) { + case "letter" : + $o = $this->_addnewoid(); + $this->objects[$o]["height"] = 792; + $this->objects[$o]["width"] = 612; + break; + + case "legal" : + $o = $this->_addnewoid(); + $this->objects[$o]["height"] = 1008; + $this->objects[$o]["width"] = 612; + break; + + case "executive" : + $o = $this->_addnewoid(); + $this->objects[$o]["height"] = 720; + $this->objects[$o]["width"] = 540; + break; + + case "tabloid" : + $o = $this->_addnewoid(); + $this->objects[$o]["height"] = 1224; + $this->objects[$o]["width"] = 792; + break; + + case "a3" : + $o = $this->_addnewoid(); + $this->objects[$o]["height"] = 1188; + $this->objects[$o]["width"] = 842; + break; + + case "a4" : + $o = $this->_addnewoid(); + $this->objects[$o]["height"] = 842; + $this->objects[$o]["width"] = 595; + break; + + case "a4-landscape" : + $o = $this->_addnewoid(); + $this->objects[$o]["height"] = 595; + $this->objects[$o]["width"] = 842; + break; + + case "a5" : + $o = $this->_addnewoid(); + $this->objects[$o]["height"] = 598; + $this->objects[$o]["width"] = 418; + break; + + default : + if (preg_match("/in/",$size)) { + $o = $this->_addnewoid(); + $size = substr($size, 0, strlen($size) - 2); + $dims = split("x",$size); + $this->objects[$o]["height"] = ($dims[1] * 72); + $this->objects[$o]["width"] = ($dims[0] * 72); + } else { + if (preg_match("/cm/",$size)) { + $o = $this->_addnewoid(); + $size = substr($size, 0, strlen($size) - 2); + $dims = split("x",$size); + $this->objects[$o]["height"] = ($dims[1] * 28.346); + $this->objects[$o]["width"] = ($dims[0] * 28.346); + } else { + $this->_push_error(6004, "Could not deciper page size description: $size"); + return false; + } + + } + } + $this->objects[$o]['type'] = 'page'; + $this->objects[$o]['parent'] = 1; + $this->objects[$o]['number'] = $this->nextpage; + $this->nextpage ++; + foreach (array('margin-left', 'margin-right', 'margin-top', 'margin-bottom') as $margin) { + $this->objects[$o][$margin] = $this->default[$margin]; + } + $this->_debug_var(10, 'New page', $this->objects[$o]); + return $o; + } + + function swap_pages($p1, $p2) + { + if ($this->objects[$p1]["type"] != "page" || + $this->objects[$p2]["type"] != "page") { + $this->_push_std_error(6001); + return false; + } + $temp = $this->objects[$p1]["number"]; + $this->objects[$p1]["number"] = $this->objects[$p2]["number"]; + $this->objects[$p2]["number"] = $temp; + return true; + } + + function move_page_before($page, $infrontof) + { + if ($this->objects[$page]["type"] != "page" || + $this->objects[$infrontof]["type"] != "page") { + $this->_push_std_error(6001); + return false; + } + if ($page == $infrontof) { + $this->_push_error(6005, "You're trying to swap a page with itself"); + return false; + } + $target = $this->objects[$infrontof]["number"]; + $leaving = $this->objects[$page]["number"]; + foreach ($this->objects as $id => $o) { + if ($o["type"] == "page") { + if ($target < $leaving) { + if ($o["number"] >= $target && $o["number"] < $leaving) { + $this->objects[$id]["number"]++; + } + } else { + if ($o["number"] < $target && $o["number"] > $leaving) { + $this->objects[$id]["number"]--; + } + } + } + } + if ($target < $leaving) { + $this->objects[$page]["number"] = $target; + } else { + $this->objects[$page]["number"] = $target - 1; + } + return true; + } + + function new_font($identifier) + { + $n["type"] = "font"; + + switch ($identifier) { + /* The "standard" Type 1 fonts + * These are "guaranteed" to be available + * to the viewer application and don't + * need embedded + */ + case "Courier": + case "Courier-Bold": + case "Courier-Oblique": + case "Courier-BoldOblique": + case "Helvetica": + case "Helvetica-Bold": + case "Helvetica-Oblique": + case "Helvetica-BoldOblique": + case "Times-Roman": + case "Times-Bold": + case "Times-Italic": + case "Times-BoldItalic": + case "Symbol": + case "ZapfDingbats": + $o = $this->_addnewoid(); + $this->builddata["fonts"][$o] = $identifier; + $n["subtype"] = "Type1"; + $n["basefont"] = $identifier; + break; + + default: + if ($this->objects[$identifier]["type"] != "fontembed") { + $this->_push_error(6006, "Object must be of type 'fontembed'"); + return false; + } else { + // Not ready yet + $this->_push_error(6007, "Feature not implemented yet"); + return false; + } + } + $this->objects[$o] = $n; + $this->_debug_var(10, 'Added font', $n); + return $o; + } + + function generate($clevel = 9) + { + $this->_debug(1, 'Starting ->generate()'); + // Validate the compression level + if (!$clevel) { + $this->builddata["compress"] = false; + } else { + if ($clevel < 10) { + $this->builddata["compress"] = $clevel; + } else { + $this->builddata["compress"] = 9; + } + } + /* Preprocess objects to see if they can + * be combined into a single stream + * We scan through each page, and create + * a multistream object out of all viable + * child objects + */ + $temparray = $this->objects; + foreach ($this->objects as $oid => $def) { + if ( $def["type"] == "page" ) { + unset($temp); + $temp['data'] = ""; + reset($temparray); + while ( list ($liboid, $obj) = each($temparray) ) { + if (isset($obj["parent"]) && $obj["parent"] == $oid) { + $this->_debug(10, "Adding # $liboid to mstream"); + switch ($obj["type"]) { + case "texts" : + $temp["data"] .= $this->_make_text($liboid); + $this->objects[$liboid]["type"] = "null"; + $this->objects[$liboid]["parent"] = -1; + break; + + case "rectangle" : + $temp["data"] .= $this->_make_rect($liboid); + $this->objects[$liboid]["type"] = "null"; + $this->objects[$liboid]["parent"] = -1; + break; + + case "iplace" : + $temp["data"] .= $this->_place_raw_image($liboid); + $this->objects[$liboid]["type"] = "null"; + $this->objects[$liboid]["parent"] = -1; + break; + + case "line" : + $temp["data"] .= $this->_make_line($liboid); + $this->objects[$liboid]["type"] = "null"; + $this->objects[$liboid]["parent"] = -1; + break; + + case "circle" : + $temp["data"] .= $this->_make_circle($liboid); + $this->objects[$liboid]["type"] = "null"; + $this->objects[$liboid]["parent"] = -1; + break; + } + } + } + if (strlen($temp["data"]) > 0) { + // this line takes the next available oid + $o = $this->_addnewoid(); + $this->_debug(10, "Saving mstream to # $o"); + $temp["type"] = "mstream"; + $temp["parent"] = $oid; + $this->objects[$o] = $temp; + } + } + } + unset($temparray); + + // Generate a list of PDF object IDs to + // use and map them to phppdflib IDs + foreach ( $this->objects as $oid => $properties ) { + if ( $this->_becomes_object( $properties["type"] ) ) { + $o = $this->_addtoxreftable(0,0); + $this->libtopdf[$oid] = $o; + $this->pdftolib[$o] = $oid; + } + } + + /* First characters represent the version + * of the PDF spec to conform to. + * The PDF spec recommends that the next + * four bytes be a comment containing four + * non-ASCII characters, to convince + * (for example) ftp programs that this is + * a binary file + */ + $os = "%PDF-1.3%\xe2\xe3\xcf\xd3\x0a"; + + // Create the Document Catalog + $carray["Type"] = "/Catalog"; + $carray["Pages"] = "2 0 R"; + $temp = $this->_makedictionary($carray); + $temp = "1 0 obj" . $temp . "endobj\x0a"; + $this->xreftable[1]["offset"] = strlen($os); + $os .= $temp; + + // Create the root page node + unset($carray); + $kids = $this->_order_pages(2); + $this->xreftable[2]["offset"] = strlen($os); + $os .= "2 0 " . $this->_makepagenode($kids, "" ) . "\x0a"; + + /* Create a resource dictionary for the entire + * PDF file. This may not be the most efficient + * way to store it, but it makes the code simple. + * At some point, we should analyze performance + * and see if it's worth splitting the resource + * dictionary up + */ + unset($temp); + unset($carray); + if (isset($this->builddata["fonts"]) && count($this->builddata["fonts"]) > 0) { + foreach ($this->builddata["fonts"] as $id => $base) { + $ta["F$id"] = $this->libtopdf[$id] . " 0 R"; + } + $temp["Font"] = $this->_makedictionary($ta); + } + reset($this->objects); + while (list($id, $obj) = each($this->objects)) { + if ($obj["type"] == "image") { + $xol["Img$id"] = $this->libtopdf[$id] . " 0 R"; + } + } + if ( isset($xol) && count($xol) > 0 ) { + $temp["XObject"] = $this->_makedictionary($xol); + } + $this->xreftable[3]["offset"] = strlen($os); + $os .= "3 0 obj"; + if (isset($temp)) { + $os .= $this->_makedictionary($temp); + } else { + $os .= '<<>>'; + } + $os .= " endobj\x0a"; + + // Go through and add the rest of the objects + foreach ( $this->pdftolib as $pdfoid => $liboid ) { + if ($pdfoid < 4) { + continue; + } + // Set the location of the start + $this->xreftable[$pdfoid]["offset"] = strlen($os); + switch ( $this->objects[$liboid]["type"] ) { + case "page": + $kids = $this->_get_kids($pdfoid); + $os .= $pdfoid . " 0 "; + $os .= $this->_makepage($this->objects[$liboid]["parent"], + $kids, $liboid); + break; + + case "rectangle": + $os .= $pdfoid . " 0 obj"; + $os .= $this->_streamify($this->_make_rect($liboid)); + $os .= " endobj"; + break; + + case "line": + $os .= $pdfoid . " 0 obj"; + $os .= $this->_streamify($this->_make_line($liboid)); + $os .= " endobj"; + break; + + case "circle": + $os .= $pdfoid . " 0 obj"; + $os .= $this->_streamify($this->_make_circle($liboid)); + $os .= " endobj"; + break; + + case "texts": + $os .= $pdfoid . " 0 obj"; + $temp = $this->_make_text($liboid); + $os .= $this->_streamify($temp) . " endobj"; + break; + + case "mstream": + $os .= $pdfoid . " 0 obj" . + $this->_streamify(trim($this->objects[$liboid]["data"])) . + " endobj"; + break; + + case "image": + $os .= $pdfoid . " 0 obj"; + $os .= $this->_make_raw_image($liboid); + $os .= " endobj"; + break; + + case "iplace": + $os .= $pdfoid . " 0 obj"; + $os .= $this->_streamify($this->_place_raw_image($liboid)); + $os .= " endobj"; + break; + + case "font" : + $os .= $pdfoid . " 0 obj"; + unset ( $temp ); + $temp["Type"] = "/Font"; + $temp["Subtype"] = "/" . $this->objects[$liboid]["subtype"]; + $temp["BaseFont"] = "/" . $this->objects[$liboid]["basefont"]; + $temp["Encoding"] = "/WinAnsiEncoding"; + $temp["Name"] = "/F$liboid"; + $os .= $this->_makedictionary($temp); + $os .= " endobj"; + break; + } + $os .= "\x0a"; + } + + // Create an Info entry + $info = $this->_addtoxreftable(0,0); + $this->xreftable[$info]["offset"] = strlen($os); + unset($temp); + $temp["Producer"] = + $this->_stringify("phppdflib http://www.potentialtech.com/ppl.php"); + $os .= $info . " 0 obj" . $this->_makedictionary($temp) . " endobj\x0a"; + + // Create the xref table + $this->builddata["startxref"] = strlen($os); + $os .= "xref\x0a0 " . (string)($this->nextobj + 1) . "\x0a"; + for ( $i = 0; $i <= $this->nextobj; $i ++ ) { + $os .= sprintf("%010u %05u %s \x0a", $this->xreftable[$i]["offset"], + $this->xreftable[$i]["gennum"], + $this->xreftable[$i]["free"]); + } + + // Create document trailer + $os .= "trailer\x0a"; + unset($temp); + $temp["Size"] = $this->nextobj + 1; + $temp["Root"] = "1 0 R"; + $temp["Info"] = $info . " 0 R"; + $os .= $this->_makedictionary($temp); + $os .= "\x0astartxref\x0a"; + $os .= $this->builddata["startxref"] . "\x0a"; + + // Required end of file marker + $os .= "%%EOF\x0a"; + + return $os; + } + + function png_embed($data) + { + // Sanity, make sure this is a png + if (substr($data, 0, 8) != "\x89PNG\x0d\x0a\x1a\x0a") { + $this->_push_error(6011, 'brand not valid'); + return false; + } + $data = substr($data, 12); + if (substr($data, 0, 4) != 'IHDR') { + $this->_push_error(6011, 'IHDR chunk missing'); + return false; + } + $data = substr($data, 4); + $width = $this->_int_val(substr($data, 0, 4)); + $height = $this->_int_val(substr($data, 4, 4)); + $data = substr($data, 8); + $bpc = ord(substr($data, 0, 1)); + $ct = ord(substr($data, 1, 1)); + if ($bpc > 8) { + $this->_push_error(6014, '16 bit PNG unsupported'); + return false; + } + switch ($ct) { + case 0 : $cspace = '/DeviceGray'; break; + case 2 : $cspace = '/DeviceRGB'; break; + case 3 : $cspace = '/Indexed'; break; + default: + $this->_push_error(6015, 'PNG with alpha not supported'); + return false; + } + if (ord(substr($data, 2, 1)) != 0) { + $this->_push_error(6016, 'Unknown compression type'); + return false; + } + if (ord(substr($data, 3, 1)) != 0) { + $this->_push_error(6017, 'Unknown PNG filter method'); + return false; + } + if (ord(substr($data, 4, 1)) != 0) { + $this->_push_error(6018, 'PNG interlacing not supported'); + return false; + } + $params['Predictor'] = '15'; + $params['Colors'] = $ct == 2 ? 3 : 1; + $params['BitsPerComponent'] = $bpc; + $params['Columns'] = $width; + $additional['DecodeParms'] = $this->_makedictionary($params); + $data = substr($data, 9); + $pal = ''; + $trns = ''; + $rawdata = ''; + do { + $n = $this->_int_val(substr($data, 0, 4)); + $type = substr($data, 4, 4); + $data = substr($data, 8); + switch ($type) { + case 'PLTE' : + $pal = substr($data, 0, $n); + $data = substr($data, $n + 4); + break; + + case 'tRNS' : + $t = substr($data, 0, $n); + if ($ct == 0) + $trns = array(ord(substr($t, 1, 1))); + elseif ($ct == 2) + $trns = array(ord(substr($t, 1, 1)), + ord(substr($t, 3, 1)), + ord(substr($t, 5, 1))); + else { + $pos = strpos($t, chr(0)); + if (is_int($pos)) + $trns = array($pos); + } + $data = substr($data, $n + 4); + break; + + case 'IDAT' : + $rawdata .= substr($data, 0, $n); + $data = substr($data, $n + 4); + break; + + case 'IEND' : + break 2; + + default : + $data = substr($data, $n + 4); + } + } while ($n); + if ($cspace == '/Indexed') { + $this->_push_error(6011, 'Indexed without palette'); + return false; + } + return $this->image_raw_embed($rawdata, + $cspace, + $bpc, + $height, + $width, + '/FlateDecode', + $additional); + } + + function jfif_embed($data) + { + /* Sanity check: Check magic numbers to see if + * this is really a JFIF stream + */ + if ( substr($data, 0, 4) != "\xff\xd8\xff\xe0" || + substr($data, 6, 4) != "JFIF" ) { + // This is not in JFIF format + $this->_push_std_error(6008); + return false; + } + + /* Now we'll scan through all the markers in the + * JFIF and extract whatever data we need from them + * We're not being terribly anal about validating + * the structure of the JFIF, so a corrupt stream + * could have very unpredictable results + */ + // Default values + $pos = 0; + $size = strlen($data); + + while ( $pos < $size ) { + $marker = substr($data, $pos + 1, 1); + // Just skip these markers + if ($marker == "\xd8" || $marker == "\xd9" || $marker == "\x01") { + $pos += 2; + continue; + } + if ($marker == "\xff") { + $pos ++; + continue; + } + + switch ($marker) { + // Start of frame + // Baseline + case "\xc0": + // Extended sequential + case "\xc1": + // Differential sequential + case "\xc5": + // Progressive + case "\xc2": + // differential progressive + case "\xc6": + // Lossless + case "\xc3": + // differential lossless + case "\xc7": + // Arithmetic encoded + case "\xc9": + case "\xca": + case "\xcb": + case "\xcd": + case "\xce": + case "\xcf": + $precision = $this->_int_val(substr($data, $pos + 4, 1)); + $height = $this->_int_val(substr($data, $pos + 5, 2)); + $width = $this->_int_val(substr($data, $pos + 7, 2)); + $numcomp = $this->_int_val(substr($data, $pos + 9, 1)); + if ( $numcomp != 3 && $numcomp != 1 ) { + // Abort if we aren't encoded as B&W or YCbCr + $this->_push_std_error(6008); + return false; + } + $pos += 2 + $this->_int_val(substr($data, $pos + 2, 2)); + break 2; + } + + /* All marker identifications continue the + * loop, thus if we got here, we need to skip + * this marker as we don't understand it. + */ + $pos += 2 + $this->_int_val(substr($data, $pos + 2, 2)); + } + $cspace = $numcomp == 1 ? "/DeviceGray" : "/DeviceRGB"; + return $this->image_raw_embed($data, + $cspace, + $precision, + $height, + $width, + "/DCTDecode"); + } + + function image_raw_embed($data, + $cspace, + $bpc, + $height, + $width, + $filter = "", + $addtl = array()) + { + $o = $this->_addnewoid(); + $t['additional'] = $addtl; + $t['data'] = $data; + $t['colorspace'] = $cspace; + $t['bpc'] = $bpc; + $t['type'] = "image"; + $t['height'] = $height; + $t['width'] = $width; + $t['filter'] = $filter; + $this->objects[$o] = $t; + $t['data'] = '[Data stripped]'; + $this->_debug_var(10, 'Embedded image', $t); + return $o; + } + + function get_image_size($id) + { + if ($this->objects[$id]['type'] != 'image') { + $this->_push_std_error(6009); + return false; + } + $r['width'] = $this->objects[$id]['width']; + $r['height'] = $this->objects[$id]['height']; + return $r; + } + + function image_place($oid, $bottom, $left, $parent, $param = array()) + { + if ($this->objects[$oid]["type"] != "image") { + $this->_push_std_error(6009); + return false; + } + if ($this->objects[$parent]["type"] != "page") { + $this->_push_std_error(6001); + return false; + } + + $o = $this->_addnewoid(); + $param = $this->_resolve_param($param, false); + $t["type"] = "iplace"; + $this->_adjust_margin($left, $bottom, $parent); + $t["bottom"] = $bottom; + $t["left"] = $left; + $t["parent"] = $parent; + // find out what the image size should be + $width = $this->objects[$oid]["width"]; + $height = $this->objects[$oid]["height"]; + $scale = $param['scale']; + if (is_array($scale)) { + $t["xscale"] = $scale["x"] * $width; + $t["yscale"] = $scale["y"] * $height; + } else { + $t["xscale"] = $scale * $width; + $t["yscale"] = $scale * $height; + } + $t["rotation"] = $param['rotation']; + $t["image"] = $oid; + $this->objects[$o] = $t; + $this->_debug_var(10, 'Placed image', $t); + return $o; + } + + function strlen($string , $params = false, $tabwidth = 4) + { + if ($this->needsset) { + require_once(dirname(__FILE__) . '/strlen.inc.php'); + } + if (empty($params["font"])) { + $font = $this->default['font']; + } else { + $font = $params["font"]; + switch ($font) { + case "Times-Roman" : + $font = "Times"; + break; + case "Helvetica-Oblique" : + $font = "Helvetica"; + break; + case "Helvetica-BoldOblique" : + $font = "Helvetica-Bold"; + break; + case "ZapfDingbats" : + $font = "Dingbats"; + break; + } + } + if ($params["height"] == 0) { + $size = $this->default['height']; + } else { + $size = $params["height"]; + } + $tab = ''; + for ($i = 0; $i < $tabwidth; $i++) { + $tab .= ' '; + } + $string = str_replace(chr(9), $tab, $string); + if (substr($font, 0, 7) == "Courier") { + // Courier is a fixed-width font + $width = strlen($string) * 600; + } else { + $width = 0; + $len = strlen($string); + for ($i = 0; $i < $len; $i++) { + $width += $this->widths[$font][ord($string{$i})]; + } + } + // We now have the string width in font units + return $width * $size / 1000; + } + + function wrap_line(&$text, $width, $param = array()) + { + $maxchars = (int)(1.1 * $width / $this->strlen("i", $param)); + $words = explode(" ", substr($text, 0, $maxchars)); + if ($this->strlen($words[0]) >= $width) { + $this->_push_error(3001, "Single token too long for allowed space"); + $final = $words[0]; + } else { + $space = $this->strlen(" ", $param); + $len = 0; + $word = 0; + $final = ""; + while ($len < $width) { + if ($word >= count($words)) { + break; + } + $temp = $this->strlen($words[$word], $param); + if ( ($len + $temp) <= $width) { + $final .= $words[$word] . " "; + $word ++; + } + $len += $space + $temp; + } + } + $text = substr($text, strlen($final)); + return $final; + } + + function word_wrap($words, $width, $param = array()) + { + // break $words into an array separated by manual paragraph break character + $paragraph = explode("\n", $words); + // find the width of 1 space in this font + $swidth = $this->strlen( " " , $param ); + // uses each element of $paragraph array and splits it at spaces + for ($lc = 0; $lc < count($paragraph); $lc++){ + while (strlen($paragraph[$lc]) > 0) { + $returnarray[] = $this->wrap_line($paragraph[$lc], $width, $param); + } + } + return $returnarray; + } + + function draw_one_paragraph($top, $left, $bottom, $right, $text, $page, $param = array()) + { + $param = $this->_resolve_param($param); + $height = 1.1 * $param['height']; + $width = $right - $left; + while ($top > $bottom) { + if (strlen($text) < 1) { + break; + } + $top -= $height; + if ($top >= $bottom) { + $line = $this->wrap_line($text, $width, $param); + switch ($param['align']) { + case 'right' : + $line = trim($line); + $l = $right - $this->strlen($line, $param); + break; + + case 'center' : + $line = trim($line); + $l = $left + (($width - $this->strlen($line, $param)) / 2); + break; + + default : + $l = $left; + } + $this->draw_text($l, $top, $line, $page, $param); + } else { + $top += $height; + break; + } + } + if (strlen($text) > 0) { + return $text; + } else { + return $top; + } + } + + function draw_paragraph($top, $left, $bottom, $right, $text, $page, $param = array()) + { + $paras = split("\n", $text); + for ($i = 0; $i < count($paras); $i++) { + $over = $this->draw_one_paragraph($top, + $left, + $bottom, + $right, + $paras[$i], + $page, + $param); + if (is_string($over)) { + break; + } + $top = $over; + } + $rv = $over; + if ($i < count($paras)) { + for ($x = $i + 1; $x < count($paras); $x++) { + $rv .= "\n" . $paras[$x]; + } + } + $this->_debug(10, "Drawing paragraph\n$text\nReturning\n$rv"); + return $rv; + } + + function error_array() + { + $rv = array(); + while (count($this->ermsg) > 0) { + $this->pop_error($num, $msg); + $rv[] = "Error $num: $msg"; + } + return $rv; + } + + function pop_error(&$num, &$msg) + { + $num = array_pop($this->erno); + $msg = array_pop($this->ermsg); + if (is_null($num)) { + return false; + } else { + return $num; + } + } + + function enable($name) + { + $name = strtolower($name); + include_once(dirname(__FILE__) . "/${name}.class.php"); + $this->x[$name] = new $name; + $this->x[$name]->pdf = &$this; + switch ($name) { + case 'chart' : + case 'template' : + case 'packer' : + case 'import' : + $this->$name = &$this->x[$name]; + break; + } + $this->_debug(10, "enabled extension: $name"); + } + + function get_color($desc) + { + $r = array(); + switch (strtolower($desc)) { + case 'black' : + $r['red'] = $r['blue'] = $r['green'] = 0; + break; + + case 'white' : + $r['red'] = $r['blue'] = $r['green'] = 1; + break; + + case 'red' : + $r['red'] = 1; + $r['blue'] = $r['green'] = 0; + break; + + case 'blue' : + $r['blue'] = 1; + $r['red'] = $r['green'] = 0; + break; + + case 'green' : + $r['green'] = 1; + $r['blue'] = $r['red'] = 0; + break; + + default : + if (substr($desc, 0, 1) == '#') { + // Parse out a hex triplet + $v = substr($desc, 1, 2); + $r['red'] = eval("return ord(\"\\x$v\");") / 255; + $v = substr($desc, 3, 2); + $r['green'] = eval("return ord(\"\\x$v\");") / 255; + $v = substr($desc, 5, 2); + $r['blue'] = eval("return ord(\"\\x$v\");") / 255; + } else { + // Error condition? + $this->_push_error(6012, "Unparsable color identifier: $desc"); + $r = false; + } + } + $this->_debug_var(10, "get_color: $desc ", $r); + return $r; + } + +/****************************************************** + * These functions are internally used by the library * + * and shouldn't really be called by a user of * + * phppdflib * + ******************************************************/ + + function _debug_var($level, $name, $value) + { + if ($level <= $this->debug) { + $this->dbs .= $name . ' -> ' . $this->_print_r($value) . "\n"; + } + } + + function _print_r($v) + { + if (version_compare('4.3.0', phpversion()) <= 0) { + return print_r($v, true); + } else { + if (is_array($v)) { + $r = "array {\n"; + foreach ($v as $key => $value) { + $r .= "[$key] = " . $this->print_r($value) . "\n"; + } + $r .= "}\n"; + return $r; + } else { + return $v; + } + } + } + + function _debug($level, $string) + { + if ($level <= $this->debug) { + $this->dbs .= $string . "\n"; + } + } + + function _resolve_mode($attrib, $mode) + { + $rmode = $attrib[$mode]; + if ($rmode != 0) { + $r = $rmode; + } else { + switch ($rmode) { + case "fill": + $r = 0; + break; + + case "stroke": + $r = 1; + break; + + case "fill+stroke": + $r = 2; + break; + } + } + return $r; + } + + function _adjust_margin(&$x, &$y, $page) + { + $x += $this->objects[$page]['margin-left']; + $y += $this->objects[$page]['margin-bottom']; + } + + function _resolve_param($param, $text = true) + { + $rv = $this->default; + if (is_array($param)) { + if (isset($param['mode'])) { + $param['tmode'] = $param['smode'] = $param['mode']; + } + foreach ($param as $key => $value) { + $rv[$key] = $value; + } + } + return $rv; + } + + function _push_error($num, $msg) + { + array_push($this->erno, $num); + array_push($this->ermsg, $msg); + $this->_debug(1, "ERROR: $num: $msg"); + } + + function _push_std_error($num) + { + switch ($num) { + case 6001 : $m = "Object must be of type 'page'"; break; + case 6008 : $m = "Data stream not recognized as JFIF"; break; + case 6009 : $m = "Object must be of type 'image'"; break; + case 6011 : $m = "Data stream not recognized as PNG"; break; + default : $m = "_push_std_error() called with invalid error number: $num"; break; + } + $this->_push_error($num, $m); + } + + function _resolve_colors(&$n, $attrib) + { + $temp = array('red','green','blue'); + foreach ($temp as $colcomp) { + if (isset($attrib['fillcolor'][$colcomp])) { + $n['fillcolor'][$colcomp] = $attrib['fillcolor'][$colcomp]; + } + if (isset($attrib['strokecolor'][$colcomp])) { + $n['strokecolor'][$colcomp] = $attrib['strokecolor'][$colcomp]; + } + } + } + + /* Check to see if a requested font is already in the + * list, if not add it. Either way, return the libid + * of the font + */ + function _use_font($id) + { + if (!isset($id['font'])) { + $id['font'] = $this->default['font']; + } + if ( isset($this->builddata["fonts"]) && count($this->builddata["fonts"]) > 0 ) { + foreach ($this->builddata["fonts"] as $libid => $name) { + if ($name == $id['font']) { + return $libid; + } + } + } + /* The font isn't in the table, so we add it + * and return it's ID + */ + return $this->new_font($id['font']); + } + + /* Convert a big-endian byte stream into an integer */ + function _int_val($string) + { + $r = 0; + for ($i = 0; $i < strlen($string); $i ++ ) { + $r += ord($string{$i}) * pow(256, strlen($string) - $i -1); + } + return $r; + } + + function _make_raw_image($liboid) + { + if (is_array($this->objects[$liboid]['additional'])) + $s = $this->objects[$liboid]['additional']; + $s["Type"] = "/XObject"; + $s["Subtype"] = "/Image"; + $s["Width"] = $this->objects[$liboid]["width"]; + $s["Height"] = $this->objects[$liboid]["height"]; + $s["ColorSpace"] = $this->objects[$liboid]["colorspace"]; + $s["BitsPerComponent"] = $this->objects[$liboid]["bpc"]; + if (strlen($this->objects[$liboid]["filter"]) > 0) { + $s["Filter"] = $this->objects[$liboid]["filter"]; + } + return $this->_streamify($this->objects[$liboid]["data"], $s); + } + + function _place_raw_image($liboid) + { + $xscale = $this->objects[$liboid]["xscale"]; + $yscale = $this->objects[$liboid]["yscale"]; + $angle = $this->objects[$liboid]["rotation"]; + $temp = "q 1 0 0 1 " . + $this->objects[$liboid]["left"] . " " . + $this->objects[$liboid]["bottom"] . " cm "; + if ($angle != 0) { + $temp .= $this->_rotate($angle) . " cm "; + } + if ($xscale != 1 || $yscale != 1) { + $temp .= "$xscale 0 0 $yscale 0 0 cm "; + } + $temp .= "/Img" . $this->objects[$liboid]["image"] . + " Do Q\x0a"; + $this->_debug(20, "Made image: $temp"); + return $temp; + } + + function _rotate($angle) + { + $a = deg2rad($angle); + $cos = cos($a); + $sin = sin($a); + $r = sprintf("%1\$1.6f %2\$1.6f %3\$1.6f %1\$1.6f 0 0", $cos, $sin, -$sin); + return $r; + } + + function _get_operator($liboid) + { + switch ($this->objects[$liboid]['mode']) { + case 0 : return "f"; break; + case 1 : return "S"; break; + case 2 : return "b"; break; + } + } + + function _make_line($liboid) + { + $gstate = ""; + if ( $colortest = $this->_colorset($liboid) ) { + $gstate .= $colortest . " "; + } + if ( isset($this->objects[$liboid]["width"]) && $this->objects[$liboid]["width"] != 1 ) { + $gstate .= $this->objects[$liboid]["width"] . " w "; + } + $firstpoint = true; + $temp = ""; + foreach ($this->objects[$liboid]["x"] as $pointid => $x) { + $y = $this->objects[$liboid]["y"][$pointid]; + $temp .= $x . " " . $y . " "; + if ($firstpoint) { + $temp .= "m "; + $firstpoint = false; + } else { + $temp .= "l "; + } + } + $temp .= $this->_get_operator($liboid); + if ( strlen($gstate) > 0 ) { + $temp = "q " . $gstate . $temp . " Q"; + } + $this->_debug(20, "Made line: $temp"); + return $temp . "\x0a"; + } + + function _make_rect($liboid) + { + $gstate = ""; + if ( $colortest = $this->_colorset($liboid) ) { + $gstate .= $colortest . " "; + } + if ( isset($this->objects[$liboid]["width"]) && $this->objects[$liboid]["width"] != 1 ) { + $gstate .= $this->objects[$liboid]["width"] . " w "; + } + $temp = $this->objects[$liboid]["left"] . " "; + $temp .= $this->objects[$liboid]["bottom"]; + $temp .= " " . ( $this->objects[$liboid]["right"] + - $this->objects[$liboid]["left"] ); + $temp .= " " . ( $this->objects[$liboid]["top"] + - $this->objects[$liboid]["bottom"] ); + $temp .= ' re '; + $temp .= $this->_get_operator($liboid); + if ( strlen($gstate) > 0 ) { + $temp = "q " . $gstate . $temp . " Q"; + } + $this->_debug(20, "Made rectangle: $temp"); + return $temp . "\x0a"; + } + + function _make_circle($liboid) + { + $gstate = ""; + if ( $colortest = $this->_colorset($liboid) ) { + $gstate .= $colortest . " "; + } + if ( isset($this->objects[$liboid]["width"]) && $this->objects[$liboid]["width"] != 1 ) { + $gstate .= $this->objects[$liboid]["width"] . " w "; + } + $r = $this->objects[$liboid]['radius']; + $x = $this->objects[$liboid]['x']; + $y = $this->objects[$liboid]['y']; + $ql = $x - $r; + $pt = $y + $r * 1.33333; + $qr = $x + $r; + $pb = $y - $r * 1.33333; + $temp = "$ql $y m "; + $temp .= "$ql $pt $qr $pt $qr $y c "; + $temp .= "$qr $pb $ql $pb $ql $y c "; + $temp .= $this->_get_operator($liboid); + if ( strlen($gstate) > 0 ) { + $temp = "q " . $gstate . $temp . " Q"; + } + $this->_debug(20, "Made circle: $temp"); + return $temp . "\x0a"; + } + + function _make_text($liboid) + { + $statechange = ""; $locateinbt = true; + $statechange = $this->_colorset($liboid); + if (isset($this->objects[$liboid]["rotation"]) && $this->objects[$liboid]["rotation"] != 0) { + $statechange .= "1 0 0 1 " . + $this->objects[$liboid]["left"] . " " . + $this->objects[$liboid]["bottom"] . " cm " . + $this->_rotate($this->objects[$liboid]["rotation"]) . + " cm "; + $locateinbt = false; + } + $temp = "BT "; + if ($this->objects[$liboid]["mode"] != 0) { + $temp .= $this->objects[$liboid]["mode"] . + " Tr "; + // Adjust stroke width + $statechange .= $this->objects[$liboid]["height"] / 35 . " w "; + } + $temp .= "/F" . $this->objects[$liboid]["font"] . " "; + $temp .= $this->objects[$liboid]["height"]; + $temp .= " Tf "; + if ($locateinbt) { + $temp .= $this->objects[$liboid]["left"] . " " . + $this->objects[$liboid]["bottom"]; + } else { + $temp .= "0 0"; + } + $temp .= " Td "; + $temp .= $this->_stringify($this->objects[$liboid]["text"]); + $temp .= " Tj "; + $temp .= "ET"; + if (strlen($statechange) > 0) { + $temp = "q " . $statechange . $temp . " Q"; + } + $this->_debug(20, "Made text: $temp"); + return $temp . "\x0a"; + } + + function _colorset($libid) + { + $red = isset($this->objects[$libid]['fillcolor']["red"]) ? (float)$this->objects[$libid]['fillcolor']["red"] : 0; + $green = isset($this->objects[$libid]['fillcolor']["green"]) ? (float)$this->objects[$libid]['fillcolor']["green"] : 0; + $blue = isset($this->objects[$libid]['fillcolor']["blue"]) ? (float)$this->objects[$libid]['fillcolor']["blue"] : 0; + if (($red > 0) || ($green > 0) || ($blue > 0)) { + $r = $red . " " . $green . " " . $blue; + $r .= " rg "; + } else { + $r = ""; + } + $red = isset($this->objects[$libid]['strokecolor']["red"]) ? (float)$this->objects[$libid]['strokecolor']["red"] : 0; + $green = isset($this->objects[$libid]['strokecolor']["green"]) ? (float)$this->objects[$libid]['strokecolor']["green"] : 0; + $blue = isset($this->objects[$libid]['strokecolor']["blue"]) ? (float)$this->objects[$libid]['strokecolor']["blue"] : 0; + if (($red > 0) || ($green > 0) || ($blue > 0) ) { + $r .= $red . " " . $green . " " . $blue; + $r .= " RG "; + } + $this->_debug(20, "Resolved color for $libid: $r"); + return $r; + } + + /* Used to determine what pdflib objects need converted + * to actual PDF objects. + */ + function _becomes_object($object) + { + if ($object == "null") { + return false; + } + return true; + } + + /* builds an array of child objects */ + function _get_kids($pdfid) + { + $libid = $this->pdftolib[$pdfid]; + foreach( $this->objects as $obid => $object ) { + if (isset($object["parent"]) && $object["parent"] == $libid) { + $kids[] = $this->libtopdf[$obid] . " 0 R"; + } + } + return $kids; + } + + /* builds an array of pages, in order */ + function _order_pages($pdfid) + { + $libid = $this->pdftolib[$pdfid]; + foreach( $this->objects as $obid => $object ) { + if (isset($object["parent"]) && $object["parent"] == $libid) { + $kids[$object["number"]] = $this->libtopdf[$obid] . " 0 R"; + } + } + ksort($kids); + return $kids; + } + + /* simple helper function to return the current oid + * and increment it by one + */ + function _addnewoid() + { + $o = $this->nextoid; + $this->nextoid++; + return $o; + } + + /* The xreftable will contain a list of all the + * objects in the pdf file and the number of bytes + * from the beginning of the file that the object + * occurs. Each time we add an object, we call this + * to record it's location, then call ->_genxreftable() + * to generate the table from array + */ + function _addtoxreftable($offset, $gennum) + { + $this->nextobj ++; + $this->xreftable[$this->nextobj]["offset"] = $offset; + $this->xreftable[$this->nextobj]["gennum"] = $gennum; + $this->xreftable[$this->nextobj]["free"] = "n"; + return $this->nextobj; + } + + /* Returns a properly formatted pdf dictionary + * containing entries specified by + * the array $entries + */ + function _makedictionary($entries) + { + $rs = "<<\x0a"; + if (isset($entries) && count($entries) > 0) { + foreach ($entries as $key => $value) { + $rs .= "/" . $key . " " . $value . "\x0a"; + } + } + $rs .= ">>"; + return $rs; + } + + /* returns a properly formatted pdf array */ + function _makearray($entries) + { + $rs = "["; + if ( is_array($entries) ) { + foreach ($entries as $entry) { + $rs .= $entry . " "; + } + } else { + $rs .= $entries; + } + $rs = rtrim($rs) . "]"; + return $rs; + } + + /* Returns a properly formatted string, with any + * special characters escaped + */ + function _stringify($string) + { + // Escape potentially problematic characters + $string = preg_replace("-\\\\-","\\\\\\\\",$string); + $bad = array ("-\(-", "-\)-" ); + $good = array ("\\(", "\\)" ); + $string = preg_replace($bad,$good,$string); + return "(" . rtrim($string) . ")"; + } + + function _streamify($data, $sarray = array()) + { + /* zlib compression is a compile time option + * for php, thus we need to make sure it's + * available before using it. + */ + $go = true; + if (function_exists('gzcompress') && $this->builddata['compress']) { + if ( !isset($sarray['Filter']) || strlen($sarray['Filter']) == 0 ) { + $sarray['Filter'] = '/FlateDecode'; + } else { + if ($sarray['Filter'] != '/FlateDecode') + $sarray['Filter'] = '[/FlateDecode ' . $sarray['Filter'] . ']'; + else + $go = false; + } + if ($go) $data = gzcompress($data, $this->builddata['compress']); + } + $sarray['Length'] = strlen($data); + $os = $this->_makedictionary($sarray); + $os .= "stream\x0a" . $data . "\x0aendstream"; + return $os; + } + + /* Returns a properly formatted page node + * page nodes with 0 kids are not created + */ + function _makepagenode($kids, $addtlopts = false) + { + $parray["Type"] = "/Pages"; + if ( isset($kids) AND count($kids) > 0 ) { + // Array of child objects + $parray["Kids"] = $this->_makearray($kids); + // Number of pages + $parray["Count"] = count($kids); + } else { + // No kids is an error condition + $this->_push_error(600, "Pagenode has no children"); + return false; + } + if ( is_array($addtlopts) ) { + foreach ( $addtlopts as $key => $value ) { + $parray[$key] = $value; + } + } + + /* The resource dictionary is always object 3 + */ + $parray["Resources"] = "3 0 R"; + + $os = $this->_makedictionary($parray); + $os = "obj" . $os . "endobj"; + $this->_debug(20, "Pagenode: $os"); + return $os; + } + + function _makepage($parent, $contents, $liboid) + { + $parray["Type"] = "/Page"; + $parray["Parent"] = $this->libtopdf[$parent] . " 0 R"; + $parray["Contents"] = $this->_makearray($contents); + $parray["MediaBox"] = "[0 0 " + . $this->objects[$liboid]["width"] . " " + . $this->objects[$liboid]["height"] . "]"; + $os = $this->_makedictionary($parray); + $os = "obj" . $os . "endobj"; + $this->_debug(20, "Page from $liboid: $os"); + return $os; + } + +} +?> diff --git a/seed/galette/manual/image/postinstall/galette/includes/phppdflib/strlen.inc.php b/seed/galette/manual/image/postinstall/galette/includes/phppdflib/strlen.inc.php new file mode 100644 index 0000000..bf45c88 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/phppdflib/strlen.inc.php @@ -0,0 +1,290 @@ +needsset = false; +$this->widths['Symbol']= array ( 32 => 250, 33 => 333, 34 => 713, 35 => 500, 36 => 549, + 37 => 833, 38 => 778, 39 => 439, 40 => 333, 41 => 333, + 42 => 500, 43 => 549, 44 => 250, 45 => 549, 46 => 250, + 47 => 278, 48 => 500, 49 => 500, 50 => 500, 51 => 500, + 52 => 500, 53 => 500, 54 => 500, 55 => 500, 56 => 500, + 57 => 500, 58 => 278, 59 => 278, 60 => 549, 61 => 549, + 62 => 549, 63 => 444, 64 => 549, 65 => 722, 66 => 667, + 67 => 722, 68 => 612, 69 => 611, 70 => 763, 71 => 603, + 72 => 722, 73 => 333, 74 => 631, 75 => 722, 76 => 686, + 77 => 889, 78 => 722, 79 => 722, 80 => 768, 81 => 741, + 82 => 556, 83 => 592, 84 => 611, 85 => 690, 86 => 439, + 87 => 768, 88 => 645, 89 => 795, 90 => 611, 91 => 333, + 92 => 863, 93 => 333, 94 => 658, 95 => 500, 96 => 500, + 97 => 631, 98 => 549, 99 => 549, 100 => 494, 101 => 439, + 102 => 521, 103 => 411, 104 => 603, 105 => 329, 106 => 603, + 107 => 549, 108 => 549, 109 => 576, 110 => 521, 111 => 549, + 112 => 549, 113 => 521, 114 => 549, 115 => 603, 116 => 439, + 117 => 576, 118 => 713, 119 => 686, 120 => 493, 121 => 686, + 122 => 494, 123 => 480, 124 => 200, 125 => 480, 126 => 549, + 161 => 620, 162 => 247, 163 => 549, 164 => 167, 165 => 713, + 166 => 500, 167 => 753, 168 => 753, 169 => 753, 170 => 753, + 171 => 1042, 172 => 987, 173 => 603, 174 => 987, 175 => 603, + 176 => 400, 177 => 549, 178 => 411, 179 => 549, 180 => 549, + 181 => 713, 182 => 494, 183 => 460, 184 => 549, 185 => 549, + 186 => 549, 187 => 549, 188 => 1000, 189 => 603, 190 => 1000, + 191 => 658, 192 => 823, 193 => 686, 194 => 795, 195 => 987, + 196 => 768, 197 => 768, 198 => 823, 199 => 768, 200 => 768, + 201 => 713, 202 => 713, 203 => 713, 204 => 713, 205 => 713, + 206 => 713, 207 => 713, 208 => 768, 209 => 713, 210 => 790, + 211 => 790, 212 => 890, 213 => 823, 214 => 549, 215 => 250, + 216 => 713, 217 => 603, 218 => 603, 219 => 1042, 220 => 987, + 221 => 603, 222 => 987, 223 => 603, 224 => 494, 225 => 329, + 226 => 790, 227 => 790, 228 => 786, 229 => 713, 230 => 384, + 231 => 384, 232 => 384, 233 => 384, 234 => 384, 235 => 384, + 236 => 494, 237 => 494, 238 => 494, 239 => 494, 241 => 329, + 242 => 274, 243 => 686, 244 => 686, 245 => 686, 246 => 384, + 247 => 384, 248 => 384, 249 => 384, 250 => 384, 251 => 384, + 252 => 494, 253 => 494, 254 => 494 ); +$this->widths['Dingbats'] = array (32 => 278, 33 => 974, 34 => 961, 35 => 974, 36 => 980, + 37 => 719, 38 => 789, 39 => 790, 40 => 791, 41 => 690, + 42 => 960, 43 => 939, 44 => 549, 45 => 855, 46 => 911, + 47 => 933, 48 => 911, 49 => 945, 50 => 974, 51 => 755, + 52 => 846, 53 => 762, 54 => 761, 55 => 571, 56 => 677, + 57 => 763, 58 => 760, 59 => 759, 60 => 754, 61 => 494, + 62 => 552, 63 => 537, 64 => 577, 65 => 692, 66 => 786, + 67 => 788, 68 => 788, 69 => 790, 70 => 793, 71 => 794, + 72 => 816, 73 => 823, 74 => 789, 75 => 841, 76 => 823, + 77 => 833, 78 => 816, 79 => 831, 80 => 923, 81 => 744, + 82 => 723, 83 => 749, 84 => 790, 85 => 792, 86 => 695, + 87 => 776, 88 => 768, 89 => 792, 90 => 759, 91 => 707, + 92 => 708, 93 => 682, 94 => 701, 95 => 826, 96 => 815, + 97 => 789, 98 => 789, 99 => 707, 100 => 687, 101 => 696, + 102 => 689, 103 => 786, 104 => 787, 105 => 713, 106 => 791, + 107 => 785, 108 => 791, 109 => 873, 110 => 761, 111 => 762, + 112 => 762, 113 => 759, 114 => 759, 115 => 892, 116 => 892, + 117 => 788, 118 => 784, 119 => 438, 120 => 138, 121 => 277, + 122 => 415, 123 => 392, 124 => 392, 125 => 668, 126 => 668, + 161 => 732, 162 => 544, 163 => 544, 164 => 910, 165 => 667, + 166 => 760, 167 => 760, 168 => 776, 169 => 595, 170 => 694, + 171 => 626, 172 => 788, 173 => 788, 174 => 788, 175 => 788, + 176 => 788, 177 => 788, 178 => 788, 179 => 788, 180 => 788, + 181 => 788, 182 => 788, 183 => 788, 184 => 788, 185 => 788, + 186 => 788, 187 => 788, 188 => 788, 189 => 788, 190 => 788, + 191 => 788, 192 => 788, 193 => 788, 194 => 788, 195 => 788, + 196 => 788, 197 => 788, 198 => 788, 199 => 788, 200 => 788, + 201 => 788, 202 => 788, 203 => 788, 204 => 788, 205 => 788, + 206 => 788, 207 => 788, 208 => 788, 209 => 788, 210 => 788, + 211 => 788, 212 => 894, 213 => 838, 214 => 1016, 215 => 458, + 216 => 748, 217 => 924, 218 => 748, 219 => 918, 220 => 927, + 221 => 928, 222 => 928, 223 => 834, 224 => 873, 225 => 828, + 226 => 924, 227 => 924, 228 => 917, 229 => 930, 230 => 931, + 231 => 463, 232 => 883, 233 => 836, 234 => 836, 235 => 867, + 236 => 867, 237 => 696, 238 => 696, 239 => 874, 241 => 874, + 242 => 760, 243 => 946, 244 => 771, 245 => 865, 246 => 771, + 247 => 888, 248 => 967, 249 => 888, 250 => 831, 251 => 873, + 252 => 927, 253 => 970, 254 => 918); +$this->widths['Helvetica-Bold'] = array (32 => 278, 33 => 333, 34 => 474, 35 => 556, + 36 => 556, 37 => 889, 38 => 722, 39 => 278, + 40 => 333, 41 => 333, 42 => 389, 43 => 584, + 44 => 278, 45 => 333, 46 => 278, 47 => 278, + 48 => 556, 49 => 556, 50 => 556, 51 => 556, + 52 => 556, 53 => 556, 54 => 556, 55 => 556, + 56 => 556, 57 => 556, 58 => 333, 59 => 333, + 60 => 584, 61 => 584, 62 => 584, 63 => 611, + 64 => 975, 65 => 722, 66 => 722, 67 => 722, + 68 => 722, 69 => 667, 70 => 611, 71 => 778, + 72 => 722, 73 => 278, 74 => 556, 75 => 722, + 76 => 611, 77 => 833, 78 => 722, 79 => 778, + 80 => 667, 81 => 778, 82 => 722, 83 => 667, + 84 => 611, 85 => 722, 86 => 667, 87 => 944, + 88 => 667, 89 => 667, 90 => 611, 91 => 333, + 92 => 278, 93 => 333, 94 => 584, 95 => 556, + 96 => 278, 97 => 556, 98 => 611, 99 => 556, + 100 => 611, 101 => 556, 102 => 333, 103 => 611, + 104 => 611, 105 => 278, 106 => 278, 107 => 556, + 108 => 278, 109 => 889, 110 => 611, 111 => 611, + 112 => 611, 113 => 611, 114 => 389, 115 => 556, + 116 => 333, 117 => 611, 118 => 556, 119 => 778, + 120 => 556, 121 => 556, 122 => 500, 123 => 389, + 124 => 280, 125 => 389, 126 => 584, 161 => 333, + 162 => 556, 163 => 556, 164 => 167, 165 => 556, + 166 => 556, 167 => 556, 168 => 556, 169 => 238, + 170 => 500, 171 => 556, 172 => 333, 173 => 333, + 174 => 611, 175 => 611, 177 => 556, 178 => 556, + 179 => 556, 180 => 278, 182 => 556, 183 => 350, + 184 => 278, 185 => 500, 186 => 500, 187 => 556, + 188 => 1000, 189 => 1000, 191 => 611, 193 => 333, + 194 => 333, 195 => 333, 196 => 333, 197 => 333, + 198 => 333, 199 => 333, 200 => 333, 202 => 333, + 203 => 333, 205 => 333, 206 => 333, 207 => 333, + 208 => 1000, 225 => 1000, 227 => 370, 232 => 611, + 233 => 778, 234 => 1000, 235 => 365, 241 => 889, + 245 => 278, 248 => 278, 249 => 611, 250 => 944, + 251 => 611 ); +$this->widths['Helvetica'] = array (32 => 278, 33 => 278, 34 => 355, 35 => 556, 36 => 556, + 37 => 889, 38 => 667, 39 => 222, 40 => 333, 41 => 333, + 42 => 389, 43 => 584, 44 => 278, 45 => 333, 46 => 278, + 47 => 278, 48 => 556, 49 => 556, 50 => 556, 51 => 556, + 52 => 556, 53 => 556, 54 => 556, 55 => 556, 56 => 556, + 57 => 556, 58 => 278, 59 => 278, 60 => 584, 61 => 584, + 62 => 584, 63 => 556, 64 => 1015, 65 => 667, 66 => 667, + 67 => 722, 68 => 722, 69 => 667, 70 => 611, 71 => 778, + 72 => 722, 73 => 278, 74 => 500, 75 => 667, 76 => 556, + 77 => 833, 78 => 722, 79 => 778, 80 => 667, 81 => 778, + 82 => 722, 83 => 667, 84 => 611, 85 => 722, 86 => 667, + 87 => 944, 88 => 667, 89 => 667, 90 => 611, 91 => 278, + 92 => 278, 93 => 278, 94 => 469, 95 => 556, 96 => 222, + 97 => 556, 98 => 556, 99 => 500, 100 => 556, 101 => 556, + 102 => 278, 103 => 556, 104 => 556, 105 => 222, 106 => 222, + 107 => 500, 108 => 222, 109 => 833, 110 => 556, 111 => 556, + 112 => 556, 113 => 556, 114 => 333, 115 => 500, 116 => 278, + 117 => 556, 118 => 500, 119 => 722, 120 => 500, 121 => 500, + 122 => 500, 123 => 334, 124 => 260, 125 => 334, 126 => 584, + 161 => 333, 162 => 556, 163 => 556, 164 => 167, 165 => 556, + 166 => 556, 167 => 556, 168 => 556, 169 => 191, 170 => 333, + 171 => 556, 172 => 333, 173 => 333, 174 => 500, 175 => 500, + 177 => 556, 178 => 556, 179 => 556, 180 => 278, 182 => 537, + 183 => 350, 184 => 222, 185 => 333, 186 => 333, 187 => 556, + 188 => 1000, 189 => 1000, 191 => 611, 193 => 333, 194 => 333, + 195 => 333, 196 => 333, 197 => 333, 198 => 333, 199 => 333, + 200 => 333, 202 => 333, 203 => 333, 205 => 333, 206 => 333, + 207 => 333, 208 => 1000, 225 => 1000, 227 => 370, 232 => 556, + 233 => 778, 234 => 1000, 235 => 365, 241 => 889, 245 => 278, + 248 => 222, 249 => 611, 250 => 944, 251 => 611 ); +$this->widths['Times'] = array (32 => 250, 33 => 333, 34 => 408, 35 => 500, 36 => 500, + 37 => 833, 38 => 778, 39 => 333, 40 => 333, 41 => 333, + 42 => 500, 43 => 564, 44 => 250, 45 => 333, 46 => 250, + 47 => 278, 48 => 500, 49 => 500, 50 => 500, 51 => 500, + 52 => 500, 53 => 500, 54 => 500, 55 => 500, 56 => 500, + 57 => 500, 58 => 278, 59 => 278, 60 => 564, 61 => 564, + 62 => 564, 63 => 444, 64 => 921, 65 => 722, 66 => 667, + 67 => 667, 68 => 722, 69 => 611, 70 => 556, 71 => 722, + 72 => 722, 73 => 333, 74 => 389, 75 => 722, 76 => 611, + 77 => 889, 78 => 722, 79 => 722, 80 => 556, 81 => 722, + 82 => 667, 83 => 556, 84 => 611, 85 => 722, 86 => 722, + 87 => 944, 88 => 722, 89 => 722, 90 => 611, 91 => 333, + 92 => 278, 93 => 333, 94 => 469, 95 => 500, 96 => 333, + 97 => 444, 98 => 500, 99 => 444, 100 => 500, 101 => 444, + 102 => 333, 103 => 500, 104 => 500, 105 => 278, 106 => 278, + 107 => 500, 108 => 278, 109 => 778, 110 => 500, 111 => 500, + 112 => 500, 113 => 500, 114 => 333, 115 => 389, 116 => 278, + 117 => 500, 118 => 500, 119 => 722, 120 => 500, 121 => 500, + 122 => 444, 123 => 480, 124 => 200, 125 => 480, 126 => 541, + 161 => 333, 162 => 500, 163 => 500, 164 => 167, 165 => 500, + 166 => 500, 167 => 500, 168 => 500, 169 => 180, 170 => 444, + 171 => 500, 172 => 333, 173 => 333, 174 => 556, 175 => 556, + 177 => 500, 178 => 500, 179 => 500, 180 => 250, 182 => 453, + 183 => 350, 184 => 333, 185 => 444, 186 => 444, 187 => 500, + 188 => 1000, 189 => 1000, 191 => 444, 193 => 333, 194 => 333, + 195 => 333, 196 => 333, 197 => 333, 198 => 333, 199 => 333, + 200 => 333, 202 => 333, 203 => 333, 205 => 333, 206 => 333, + 207 => 333, 208 => 1000, 225 => 889, 227 => 276, 232 => 611, + 233 => 722, 234 => 889, 235 => 310, 241 => 667, 245 => 278, + 248 => 278, 249 => 500, 250 => 722, 251 => 500); +$this->widths['Times-Bold'] = array (32 => 250, 33 => 333, 34 => 555, 35 => 500, 36 => 500, + 37 => 1000, 38 => 833, 39 => 333, 40 => 333, 41 => 333, + 42 => 500, 43 => 570, 44 => 250, 45 => 333, 46 => 250, + 47 => 278, 48 => 500, 49 => 500, 50 => 500, 51 => 500, + 52 => 500, 53 => 500, 54 => 500, 55 => 500, 56 => 500, + 57 => 500, 58 => 333, 59 => 333, 60 => 570, 61 => 570, + 62 => 570, 63 => 500, 64 => 930, 65 => 722, 66 => 667, + 67 => 722, 68 => 722, 69 => 667, 70 => 611, 71 => 778, + 72 => 778, 73 => 389, 74 => 500, 75 => 778, 76 => 667, + 77 => 944, 78 => 722, 79 => 778, 80 => 611, 81 => 778, + 82 => 722, 83 => 556, 84 => 667, 85 => 722, 86 => 722, + 87 => 1000, 88 => 722, 89 => 722, 90 => 667, 91 => 333, + 92 => 278, 93 => 333, 94 => 581, 95 => 500, 96 => 333, + 97 => 500, 98 => 556, 99 => 444, 100 => 556, 101 => 444, + 102 => 333, 103 => 500, 104 => 556, 105 => 278, 106 => 333, + 107 => 556, 108 => 278, 109 => 833, 110 => 556, 111 => 500, + 112 => 556, 113 => 556, 114 => 444, 115 => 389, 116 => 333, + 117 => 556, 118 => 500, 119 => 722, 120 => 500, 121 => 500, + 122 => 444, 123 => 394, 124 => 220, 125 => 394, 126 => 520, + 161 => 333, 162 => 500, 163 => 500, 164 => 167, 165 => 500, + 166 => 500, 167 => 500, 168 => 500, 169 => 278, 170 => 500, + 171 => 500, 172 => 333, 173 => 333, 174 => 556, 175 => 556, + 177 => 500, 178 => 500, 179 => 500, 180 => 250, 182 => 540, + 183 => 350, 184 => 333, 185 => 500, 186 => 500, 187 => 500, + 188 => 1000, 189 => 1000, 191 => 500, 193 => 333, 194 => 333, + 195 => 333, 196 => 333, 197 => 333, 198 => 333, 199 => 333, + 200 => 333, 202 => 333, 203 => 333, 205 => 333, 206 => 333, + 207 => 333, 208 => 1000, 225 => 1000, 227 => 300, 232 => 667, + 233 => 778, 234 => 1000, 235 => 330, 241 => 722, 245 => 278, + 248 => 278, 249 => 500, 250 => 722, 251 => 556); +$this->widths['Times-Italic'] = array (32 => 250, 33 => 333, 34 => 420, 35 => 500, 36 => 500, + 37 => 833, 38 => 778, 39 => 333, 40 => 333, 41 => 333, + 42 => 500, 43 => 675, 44 => 250, 45 => 333, 46 => 250, + 47 => 278, 48 => 500, 49 => 500, 50 => 500, 51 => 500, + 52 => 500, 53 => 500, 54 => 500, 55 => 500, 56 => 500, + 57 => 500, 58 => 333, 59 => 333, 60 => 675, 61 => 675, + 62 => 675, 63 => 500, 64 => 920, 65 => 611, 66 => 611, + 67 => 667, 68 => 722, 69 => 611, 70 => 611, 71 => 722, + 72 => 722, 73 => 333, 74 => 444, 75 => 667, 76 => 556, + 77 => 833, 78 => 667, 79 => 722, 80 => 611, 81 => 722, + 82 => 611, 83 => 500, 84 => 556, 85 => 722, 86 => 611, + 87 => 833, 88 => 611, 89 => 556, 90 => 556, 91 => 389, + 92 => 278, 93 => 389, 94 => 422, 95 => 500, 96 => 333, + 97 => 500, 98 => 500, 99 => 444, 100 => 500, 101 => 444, + 102 => 278, 103 => 500, 104 => 500, 105 => 278, 106 => 278, + 107 => 444, 108 => 278, 109 => 722, 110 => 500, 111 => 500, + 112 => 500, 113 => 500, 114 => 389, 115 => 389, 116 => 278, + 117 => 500, 118 => 444, 119 => 667, 120 => 444, 121 => 444, + 122 => 389, 123 => 400, 124 => 275, 125 => 400, 126 => 541, + 161 => 389, 162 => 500, 163 => 500, 164 => 167, 165 => 500, + 166 => 500, 167 => 500, 168 => 500, 169 => 214, 170 => 556, + 171 => 500, 172 => 333, 173 => 333, 174 => 500, 175 => 500, + 177 => 500, 178 => 500, 179 => 500, 180 => 250, 182 => 523, + 183 => 350, 184 => 333, 185 => 556, 186 => 556, 187 => 500, + 188 => 889, 189 => 1000, 191 => 500, 193 => 333, 194 => 333, + 195 => 333, 196 => 333, 197 => 333, 198 => 333, 199 => 333, + 200 => 333, 202 => 333, 203 => 333, 205 => 333, 206 => 333, + 207 => 333, 208 => 889, 225 => 889, 227 => 276, 232 => 556, + 233 => 722, 234 => 944, 235 => 310, 241 => 667, 245 => 278, + 248 => 278, 249 => 500, 250 => 667, 251 => 500); +$this->widths['Times-BoldItalic'] = array (32 => 250, 33 => 389, 34 => 555, 35 => 500, 36 => 500, + 37 => 833, 38 => 778, 39 => 333, 40 => 333, 41 => 333, + 42 => 500, 43 => 570, 44 => 250, 45 => 333, 46 => 250, + 47 => 278, 48 => 500, 49 => 500, 50 => 500, 51 => 500, + 52 => 500, 53 => 500, 54 => 500, 55 => 500, 56 => 500, + 57 => 500, 58 => 333, 59 => 333, 60 => 570, 61 => 570, + 62 => 570, 63 => 500, 64 => 832, 65 => 667, 66 => 667, + 67 => 667, 68 => 722, 69 => 667, 70 => 667, 71 => 722, + 72 => 778, 73 => 389, 74 => 500, 75 => 667, 76 => 611, + 77 => 889, 78 => 722, 79 => 722, 80 => 611, 81 => 722, + 82 => 667, 83 => 556, 84 => 611, 85 => 722, 86 => 667, + 87 => 889, 88 => 667, 89 => 611, 90 => 611, 91 => 333, + 92 => 278, 93 => 333, 94 => 570, 95 => 500, 96 => 333, + 97 => 500, 98 => 500, 99 => 444, 100 => 500, 101 => 444, + 102 => 333, 103 => 500, 104 => 556, 105 => 278, 106 => 278, + 107 => 500, 108 => 278, 109 => 778, 110 => 556, 111 => 500, + 112 => 500, 113 => 500, 114 => 389, 115 => 389, 116 => 278, + 117 => 556, 118 => 444, 119 => 667, 120 => 500, 121 => 444, + 122 => 389, 123 => 348, 124 => 220, 125 => 348, 126 => 570, + 161 => 389, 162 => 500, 163 => 500, 164 => 167, 165 => 500, + 166 => 500, 167 => 500, 168 => 500, 169 => 278, 170 => 500, + 171 => 500, 172 => 333, 173 => 333, 174 => 556, 175 => 556, + 177 => 500, 178 => 500, 179 => 500, 180 => 250, 182 => 500, + 183 => 350, 184 => 333, 185 => 500, 186 => 500, 187 => 500, + 188 => 1000, 189 => 1000, 191 => 500, 193 => 333, 194 => 333, + 195 => 333, 196 => 333, 197 => 333, 198 => 333, 199 => 333, + 200 => 333, 202 => 333, 203 => 333, 205 => 333, 206 => 333, + 207 => 333, 208 => 1000, 225 => 944, 227 => 266, 232 => 611, + 233 => 722, 234 => 944, 235 => 300, 241 => 722, 245 => 278, + 248 => 278, 249 => 500, 250 => 722, 251 => 500); + +?> \ No newline at end of file diff --git a/seed/galette/manual/image/postinstall/galette/includes/phppdflib/template.class.php b/seed/galette/manual/image/postinstall/galette/includes/phppdflib/template.class.php new file mode 100644 index 0000000..ac575f5 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/phppdflib/template.class.php @@ -0,0 +1,222 @@ +tid = 0; + } + + function create() + { + $temp = $this->nexttid; + // Stores the next object ID within this template + $this->templ[$temp]['next'] = 0; + $this->nexttid ++; + return $temp; + } + + function size($tid, $width, $height) + { + $this->templ[$tid]["height"] = $height; + $this->templ[$tid]["width"] = $width; + return true; + } + + function rectangle($tid, $bottom, $left, $top, $right, $attrib = array()) + { + $temp = $this->pdf->_resolve_param($attrib); + $temp["type"] = "rectangle"; + $temp["top"] = $top; + $temp["left"] = $left; + $temp["bottom"] = $bottom; + $temp["right"] = $right; + return $this->_add_object($temp, $tid); + } + + function circle($tid, $cenx, $ceny, $radius, $attrib = array()) + { + $temp = $this->pdf->_resolve_param($attrib); + $temp["type"] = "circle"; + $temp["x"] = $cenx; + $temp["y"] = $ceny; + $temp["radius"] = $radius; + return $this->_add_object($temp, $tid); + } + + function line($tid, $x, $y, $attrib = array()) + { + $temp = $this->pdf->_resolve_param($attrib); + $temp["type"] = "line"; + $temp["x"] = $x; + $temp["y"] = $y; + return $this->_add_object($temp, $tid); + } + + function image($tid, $left, $bottom, $width, $height, $image, $attrib = array()) + { + $this->ifield($tid, $left, $bottom, $width, $height, false, $image, $attrib); + } + + function ifield($tid, $left, $bottom, $width, $height, $name, $default = false, $attrib = array()) + { + $temp = $this->pdf->_resolve_param($attrib); + $temp['type'] = "ifield"; + $temp['left'] = $left; + $temp['bottom'] = $bottom; + $temp['name'] = $name; + $temp['default'] = $default; + $temp['width'] = $width; + $temp['height'] = $height; + return $this->_add_object($temp, $tid); + } + + function text($tid, $left, $bottom, $text, $attrib = array()) + { + return $this->field($tid, $left, $bottom, false, $text, $attrib); + } + + function field($tid, $left, $bottom, $name, $default = '', $attrib = array()) + { + $temp = $this->pdf->_resolve_param($attrib); + $temp["type"] = "field"; + $temp["left"] = $left; + $temp["bottom"] = $bottom; + $temp["name"] = $name; + $temp["default"] = $default; + return $this->_add_object($temp, $tid); + } + + function paragraph($tid, $bottom, $left, $top, $right, $text, $attrib = array()) + { + return $this->pfield($tid, $bottom, $left, $top, $right, false, $text, $attrib); + } + + function pfield($tid, $bottom, $left, $top, $right, $name, $default = '', $attrib = array()) + { + $temp = $this->pdf->_resolve_param($attrib); + $temp['type'] = 'pfield'; + $temp['left'] = $left; + $temp['bottom'] = $bottom; + $temp['top'] = $top; + $temp['right'] = $right; + $temp['name'] = $name; + $temp['default'] = $default; + return $this->_add_object($temp, $tid); + } + + function place($tid, $page, $left, $bottom, $data = array()) + { + $ok = true; + foreach( $this->templ[$tid]["objects"] as $o ) { + switch ($o['type']) { + case 'rectangle' : + $ok = $ok && $this->pdf->draw_rectangle($bottom + $o["top"], + $left + $o["left"], + $bottom + $o["bottom"], + $left + $o["right"], + $page, + $o); + break; + + case 'circle' : + $ok = $ok && $this->pdf->draw_circle($left + $o['x'], + $bottom + $o['y'], + $o['radius'], + $page, + $o); + break; + + case 'line' : + foreach ($o['x'] as $key => $value) { + $o['x'][$key] += $left; + $o['y'][$key] += $bottom; + } + $ok = $ok && $this->pdf->draw_line($o['x'], + $o['y'], + $page, + $o); + break; + + case 'field' : + $temp = ($o['name'] === false) || !isset($data[$o['name']]) || !strlen($data[$o['name']]) ? $o['default'] : $data[$o['name']]; + $ok = $ok && $this->pdf->draw_text($left + $o['left'], + $bottom + $o['bottom'], + $temp, + $page, + $o); + break; + + case 'pfield' : + $temp = ($o['name'] === false) || !isset($data[$o['name']]) || !strlen($data[$o['name']]) ? $o['default'] : $data[$o['name']]; + $t = $this->pdf->draw_paragraph($bottom + $o['top'], + $left + $o['left'], + $bottom + $o['bottom'], + $left + $o['right'], + $temp, + $page, + $o); + if (is_string($t)) { + $ok = false; + $this->pdf->_push_error(6013, "Text overflowed available area: $t"); + } + break; + + case 'ifield' : + $temp = ($o['name'] === false) || empty($data[$o['name']]) ? $o['default'] : $data[$o['name']]; + if ($temp === false) { + break; + } + $id = $this->pdf->get_image_size($temp); + unset($o['scale']); + $o['scale']['x'] = $o['width'] / $id['width']; + $o['scale']['y'] = $o['height'] / $id['height']; + $ok = $ok && $this->pdf->image_place($temp, + $o['bottom'] + $bottom, + $o['left'] + $left, + $page, + $o); + break; + } + } + return $ok; + } + + /* Private methods + */ + + function _add_object($objarray, $tid) + { + $oid = $this->templ[$tid]["next"]; + $this->templ[$tid]["next"] ++; + $this->templ[$tid]["objects"][$oid] = $objarray; + return $oid; + } + +} +?> diff --git a/seed/galette/manual/image/postinstall/galette/includes/session.inc.php b/seed/galette/manual/image/postinstall/galette/includes/session.inc.php new file mode 100644 index 0000000..c503a83 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/includes/session.inc.php @@ -0,0 +1,56 @@ + diff --git a/seed/galette/manual/image/postinstall/galette/index.php b/seed/galette/manual/image/postinstall/galette/index.php new file mode 100644 index 0000000..c824b08 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/index.php @@ -0,0 +1,125 @@ +Execute($requete); + if (!$resultat->EOF) + { + if ($resultat->fields[1]=="1") + $_SESSION["admin_status"]=1; + $_SESSION["logged_id_adh"]=$resultat->fields[0]; + $_SESSION["logged_status"]=1; + $_SESSION["logged_nom_adh"]=strtoupper($resultat->fields[2]) . " " . strtolower($resultat->fields[3]); + if ($_SESSION["admin_status"] == "1") + { + $_SESSION["sess_cuser"]='O:5:"tUser":3:{s:2:"id";s:1:"4";s:4:"name";s:5:"admin";s:4:"perm";s:3:"126";}'; + } else { + $_SESSION["sess_cuser"]='O:5:"tUser":3:{s:2:"id";s:1:"1";s:4:"name";s:9:"Anonymous";s:4:"perm";s:1:"0";}'; + } + + $_SESSION["sess_clogin"] = $_SESSION["logged_nom_adh"]; + $_SESSION["sess_sort"] = "258"; + $_SESSION["sess_grp"]="1"; + dblog(_T("Identification")); + } + else + dblog(_T("Echec authentification. Login :")." \"" . $_POST["login"] . "\""); + } + } + + if ($_SESSION["logged_status"]!=0) + header("location: gestion_adherents.php"); + else + { +?> + + + + +L’A.M.A.P. des Jardins de Virgile - Produits + + + + + + + +

    Partie privée de l'A.M.A.P.
    les Jardins de Virgile

    +

    :: L’A.M.A.P. des Jardins de Virgile des bourroches, Dijon en Côte d’Or ::

    +
    +
    +

    Accès à la partie privée

    +
    +
    + +

    +

    +

    " />

    +
    +
    +

    +
    +

    +:: Mise en page GARETTE Emmanuel :: +

    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + + + diff --git a/seed/galette/manual/image/postinstall/galette/lang/lang_english.php b/seed/galette/manual/image/postinstall/galette/lang/lang_english.php new file mode 100644 index 0000000..b04addd --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/lang/lang_english.php @@ -0,0 +1,383 @@ + members list :"; +$lang["Voulez-vous vraiment supprimer cet adhérent de la base, ceci supprimera aussi l'historique de ses cotisations. Pour éviter cela vous pouvez simplement désactiver le compte.\n\nVoulez-vous tout de même supprimer cet adhérent ?"]="Do you really want to delete this member from the database. This will also delete dues history. To avoid this, you can simply deactivate this account.\n\nDo you still want to delete this member ?"; +?> diff --git a/seed/galette/manual/image/postinstall/galette/lang/lang_french.php b/seed/galette/manual/image/postinstall/galette/lang/lang_french.php new file mode 100644 index 0000000..1329b80 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/lang/lang_french.php @@ -0,0 +1,428 @@ + liste des membres :"; +$lang["Voulez-vous vraiment supprimer cet adhérent de la base, ceci supprimera aussi l'historique de ses cotisations. Pour éviter cela vous pouvez simplement désactiver le compte.\n\nVoulez-vous tout de même supprimer cet adhérent ?"]="Voulez-vous vraiment supprimer cet adhérent de la base, ceci supprimera aussi l'historique de ses cotisations. Pour éviter cela vous pouvez simplement désactiver le compte.\n\nVoulez-vous tout de même supprimer cet adhérent ?"; + +$lang["Mes absences"]="Mes absences"; +$lang["Les absences"]="Les absences"; +$lang["[ Ajouter une absence ]"]="Ajouter une absence"; +$lang["absences"]="absences"; +$lang["absence"]="absence"; +$lang["Date absence :"]="Date absence :"; +$lang["- Date deja en absence !"]="- Date deja en absence !"; +$lang["- Vous ne pouvez pas modifier cette absence, faite une demande a l'administrateur (2)."]="- Vous ne pouvez pas modifier cette absence, faite une demande a l'administrateur (2)."; +$lang["- Pas apres le 20 du mois precedent !"]="- Pas apres le 20 du mois precedent !"; +$lang["- Cette date n'est pas un samedi !"]="- Cette date n'est pas un samedi !"; +$lang["Panier :"]="Panier :"; +$lang["Pain :"]="Pain :"; +$lang["pp"]="pp"; +$lang["GP"]="GP"; +$lang["5¿"]="5¿"; +$lang["3¿"]="3¿"; +$lang["7¿"]="7¿"; +$lang["9¿50"]="9¿50"; +$lang["Aucun"]="Aucun"; +$lang["Gestion des absences"]="Gestion des absences"; +$lang["Voulez-vous vraiment supprimer cette absence ?"]="Voulez-vous vraiment supprimer cette absence ?"; +$lang["Cotisation annuelle"]="Cotisation annuelle"; +$lang["Contrat"]="Contrat"; +$lang["Pain"]="Pain"; +$lang["Legumes"]="Legumes"; +$lang["Tous les paniers"]="Tous les paniers"; +$lang["Volaille :"]="Volaille :"; +$lang["Fromage de chèvre :"]="Fromage de chèvre :"; +$lang["Boeuf :"]="Boeuf :"; +$lang["Veau :"]="Veau :"; +$lang["Cochon :"]="Cochon :"; +$lang["oui"]="oui"; +$lang["non"]="non"; +$lang["Boeuf"]="Boeuf"; +$lang["Veau"]="Veau"; +$lang["Cochon"]="Cochon"; +$lang["Volaille"]="Volaille"; +$lang["Fromage de chèvre"]="Fromage de chèvre"; +$lang["Farine-Huile"]="Farine-Huile"; +$lang["Farine-Huile :"]="Farine-Huile :"; + +$lang["feuille emargement"]="feuille emargement"; +$lang["Feuille d'emargement"]="Feuille d'emargement"; + +?> diff --git a/seed/galette/manual/image/postinstall/galette/legumes.jpg b/seed/galette/manual/image/postinstall/galette/legumes.jpg new file mode 100644 index 0000000..fcd9ec6 Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/legumes.jpg differ diff --git a/seed/galette/manual/image/postinstall/galette/log.php b/seed/galette/manual/image/postinstall/galette/log.php new file mode 100644 index 0000000..1bebfeb --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/log.php @@ -0,0 +1,215 @@ +Execute($requete[0]); + dblog(_T("Réinitialisation de l'historique")); + } + + // Tri + if (isset($_GET["tri"])) + if (is_numeric($_GET["tri"])) + { + if ($_SESSION["tri_log"]==$_GET["tri"]) + $_SESSION["tri_log_sens"]=($_SESSION["tri_log_sens"]+1)%2; + else + { + $_SESSION["tri_log"]=$_GET["tri"]; + $_SESSION["tri_log_sens"]=0; + } + } + + $requete[0] = "SELECT date_log, adh_log, text_log, ip_log FROM ".PREFIX_DB."logs "; + $requete[1] = "SELECT count(id_log) FROM ".PREFIX_DB."logs"; + + // phase de tri + if ($_SESSION["tri_log_sens"]=="0") + $tri_log_sens_txt="ASC"; + else + $tri_log_sens_txt="DESC"; + + $requete[0] .= "ORDER BY "; + + // tri par date + if ($_SESSION["tri_log"]=="0") + $requete[0] .= "date_log ".$tri_log_sens_txt.","; + + // tri par ip + elseif ($_SESSION["tri_log"]=="1") + $requete[0] .= "ip_log ".$tri_log_sens_txt.","; + + // tri par adhérent + elseif ($_SESSION["tri_log"]=="2") + $requete[0] .= "adh_log ".$tri_log_sens_txt.","; + + // tri par description + elseif ($_SESSION["tri_log"]=="3") + $requete[0] .= "text_log ".$tri_log_sens_txt.","; + + $requete[0] .= "id_log ".$tri_log_sens_txt; + + $resultat = &$DB->SelectLimit($requete[0],PREF_NUMROWS,($page-1)*PREF_NUMROWS); + $nb_lines = &$DB->Execute($requete[1]); + + include("header.php"); + + if ($nb_lines->fields[0]%PREF_NUMROWS==0) + $nbpages = intval($nb_lines->fields[0]/PREF_NUMROWS); + else + $nbpages = intval($nb_lines->fields[0]/PREF_NUMROWS)+1; + $pagestring = ""; + if ($nbpages==0) + $pagestring = "1"; + else for ($i=1;$i<=$nbpages;$i++) + { + if ($i!=$page) + $pagestring .= "".$i." "; + else + $pagestring .= $i." "; + } + +?> +

    +
    +
    ">
    + +
    + + + + + +
    fields[0]." "; if ($nb_lines->fields[0]!=1) echo _T("lignes"); else echo _T("ligne"); ?>
    + + + + + + + + +EOF) + { +?> + +EOF) + { +?> + + + + + + + +MoveNext(); + $compteur++; + } + $resultat->Close(); +?> +
    # + + + + + + + + + + + + + + + +
    fields[0]; ?>fields[3]; ?>fields[1]; ?>fields[2])), ENT_QUOTES)); ?>
    +
    + diff --git a/seed/galette/manual/image/postinstall/galette/lostpasswd.php b/seed/galette/manual/image/postinstall/galette/lostpasswd.php new file mode 100644 index 0000000..713ed48 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/lostpasswd.php @@ -0,0 +1,149 @@ +Execute($req); + + if ($result->EOF) { + $GLOBALS["error_detected"] = ("login inexistant"); + dblog(("Login inexistant envoyé via le formulaire de récupération du mot de passe")." \"" . $login ."\""); + }else{ + $email=$result->fields[0]; + if( empty($email) ) { + $GLOBALS["error_detected"] = ("Ce compte ne contient pas d'adresse email, veuillez contacter un administrateur"); + dblog(("Demande d'envoi de mot de passe mais email vide. Login :")." \"" . $login . "\""); + }else + return $email; + } + } + } + + if( isset($_POST["login"]) ) { + $login_adh=$_POST['login']; + $email_adh=isEmail($login_adh); + + //send the password + if( $email_adh!="" ) + { + $req = "SELECT mdp_adh from ".PREFIX_DB."adherents where login_adh=".txt_sqls($login_adh); + $result = &$DB->Execute($req); + if (!$result->EOF) + $mdp_adh = $result->fields[0]; + $mail_subject = ("Vos identifiants Galette"); + $mail_text = ("Bonjour,")."\n"; + $mail_text .= "\n"; + $mail_text .= ("Quelqu'un (sûrement vous) a demandé que l'on vous renvoie votre mot de passe.")."\n"; + $mail_text .= "\n"; + $mail_text .= ("Veuillez vous identifier à cette adresse :")."\n"; + $mail_text .= "http://".$_SERVER["SERVER_NAME"].dirname($_SERVER["REQUEST_URI"])."\n"; + $mail_text .= "\n"; + $mail_text .= ("Identifiant :")." ".custom_html_entity_decode($login_adh, ENT_QUOTES)."\n"; + $mail_text .= ("Mot de passe :")." ".custom_html_entity_decode($mdp_adh, ENT_QUOTES)."\n"; + $mail_text .= "\n"; + $mail_text .= ("A très bientôt !")."\n"; + $mail_text .= "\n"; + $mail_text .= ("(ce mail est un envoi automatique)")."\n"; + $mail_headers = "From: ".PREF_EMAIL_NOM." <".PREF_EMAIL.">\n"; + if( mail($email_adh,$mail_subject,$mail_text, $mail_headers) ) { + dblog(("Mot de passe envoyé. Login :")." \"" . $login_adh . "\""); + $warning_detected = ("Mot de passe envoyé. Login :")." \"" . $login_adh . "\""; + $password_sent = true; + }else{ + dblog(("Un problème est survenu dans l'envoi du mot de passe pour le compte :")." \"" . $login_adh . "\""); + $warning_detected = ("Un problème est survenu dans l'envoi du mot de passe pour le compte :")." \"" . $login_adh . "\""; + } + } + } +?> + + + +L’A.M.A.P. des Jardins de Virgile - Produits + + + + + + + +

    Partie privée de l'A.M.A.P.
    les Jardins de Virgile

    +

    :: L’A.M.A.P. des Jardins de Virgile des bourroches, Dijon en Côte d’Or ::

    +
    +
    +

    Mot de passe perdu

    +
    +
    + + + +
    +

    +
    + + + +
    +

    +
    + + + +

    +

    " /> + +

    +
    +
    +Retour à l' . "'" . 'espace privée

    '; ?> + +
    +

    +:: Mise en page GARETTE Emmanuel :: +

    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + + + + diff --git a/seed/galette/manual/image/postinstall/galette/mailing_adherents.php b/seed/galette/manual/image/postinstall/galette/mailing_adherents.php new file mode 100644 index 0000000..25ebd81 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/mailing_adherents.php @@ -0,0 +1,949 @@ + "20") + $moiscour=date("m")+1; + else + $moiscour=date("m"); + + if (isset($_POST["mailing_go"])) + { + if ($mailing_objet=="") + $error_detected .= "
  • "._T("Veuillez indiquer un objet pour le message.")."
  • "; + + if ($mailing_corps=="") + $error_detected .= "
  • "._T("Veuillez saisir un message.")."
  • "; + + if (!isset($_POST["mailing_adh"])) + $error_detected .= "
  • "._T("Veuillez sélectionner au moins un adhérent.")."
  • "; + + if ($error_detected=="") + $etape = 1; + } + + include("header.php"); + + if ($etape==0) + { + + if (isset($_GET["filtre_2"])) + if (is_numeric($_GET["filtre_2"])) + $_SESSION["filtre_adh_2"]=$_GET["filtre_2"]; + + if (isset($_GET["filtre_3"])) + if (is_numeric($_GET["filtre_3"])) + $_SESSION["filtre_adh_3"]=$_GET["filtre_3"]; + if (isset($_GET["filtre"])) + if (is_numeric($_GET["filtre"])) + $_SESSION["filtre_adh"]=$_GET["filtre"]; + + // Tri + + if (isset($_GET["tri"])) + if (is_numeric($_GET["tri"])) + { + if ($_SESSION["tri_adh"]==$_GET["tri"]) + $_SESSION["tri_adh_sens"]=($_SESSION["tri_adh_sens"]+1)%2; + else + { + $_SESSION["tri_adh"]=$_GET["tri"]; + $_SESSION["tri_adh_sens"]=0; + } + } + + if (isset($_GET["etiquettes"])) + { +?> +

    + +

    + +
    +

    +
      + +
    +
    + ".$DB->DBDate(time())." OR bool_exempt_adh='1') "; + $requete[1] .= "AND (date_echeance > ".$DB->DBDate(time())." OR bool_exempt_adh='1') "; + } + + // filtre d'affichage des adherents retardataires + if ($_SESSION["filtre_adh"]=="2") + { + $requete[0] .= "AND date_echeance < ".$DB->DBDate(time())." "; + $requete[1] .= "AND date_echeance < ".$DB->DBDate(time())." "; + } + + // filtre d'affichage des adherents bientot a echeance + if ($_SESSION["filtre_adh"]=="1") + { + $requete[0] .= "AND date_echeance > ".$DB->DBDate(time())." + AND date_echeance < ".$DB->OffsetDate(30)." "; + $requete[1] .= "AND date_echeance > ".$DB->DBDate(time())." + AND date_echeance < ".$DB->OffsetDate(30)." "; + } + + // phase de tri + + if ($_SESSION["tri_adh_sens"]=="0") + $tri_adh_sens_txt="ASC"; + else + $tri_adh_sens_txt="DESC"; + + $requete[0] .= "ORDER BY "; + + // tri par pseudo + if ($_SESSION["tri_adh"]=="1") + $requete[0] .= "pseudo_adh ".$tri_adh_sens_txt.","; + + // tri par statut + elseif ($_SESSION["tri_adh"]=="2") + $requete[0] .= "priorite_statut ".$tri_adh_sens_txt.","; + + // tri par echeance + elseif ($_SESSION["tri_adh"]=="3") + $requete[0] .= "bool_exempt_adh ".$tri_adh_sens_txt.", date_echeance ".$tri_adh_sens_txt.","; + + // defaut : tri par nom, prenom + $requete[0] .= "nom_adh ".$tri_adh_sens_txt.", prenom_adh ".$tri_adh_sens_txt; + + $resultat = &$DB->Execute($requete[0]); + $nbadh = &$DB->Execute($requete[1]); +?> + + + + + + +
    fields[0]." "; if ($nbadh->fields[0]!=1) echo _T("adhérents"); else echo _T("adhérent"); ?> +
    +
    +   + + + + + "> +
    +
    +
    + +
    + + + + + + + + + + + + +EOF) + { +?> + + + +EOF) + { + // définition CSS pour adherent désactivé + if ($resultat->fields[4]=="1") + $row_class = "actif"; + else + $row_class = "inactif"; + + // temps d'adhésion + if($resultat->fields[6]) + { + $statut_cotis = _T("Exempt de cotisation"); + $row_class .= " cotis-exempt"; + } + else + { + if ($resultat->fields[10]=="") + { + $statut_cotis = _T("N'a jamais cotisé"); + $row_class .= " cotis-never"; + } + else + { + $date_fin = split("-",$resultat->fields[10]); + $ts_date_fin = mktime(0,0,0,$date_fin[1],$date_fin[2],$date_fin[0]); + $aujourdhui = time(); + + $difference = intval(($ts_date_fin - $aujourdhui)/(3600*24)); + if ($difference==0) + { + $statut_cotis = _T("Dernier jour !"); + $row_class .= " cotis-lastday"; + } + elseif ($difference<0) + { + $statut_cotis = _T("En retard de ").-$difference." "._T("jours")." ("._T("depuis le")." ".$date_fin[2]."/".$date_fin[1]."/".$date_fin[0].")"; + $row_class .= " cotis-late"; + } + else + { + $statut_cotis = $difference." "._T("jours restants")." ("._T("fin le")." ".$date_fin[2]."/".$date_fin[1]."/".$date_fin[0].")"; + if ($difference < 30) + $row_class .= " cotis-soon"; + else + $row_class .= " cotis-ok"; + } + } + } +?> + + + + + + + + +MoveNext(); + } + $resultat->Close(); +?> +
    # + + "; + else + echo "\"\""; + ?> + + + "; + else + echo "\"\""; + ?> + + + "; + else + echo "\"\""; + ?> + + + "; + else + echo "\"\""; + ?> + Actions
    + fields[0],$mailing_adh)) echo "CHECKED"; ?>> + +fields[7]=="1") { +?> + <?php echo _T(" align="middle" width="10" height="12"> + + <?php echo _T(" align="middle" width="9" height="12"> + +fields[9]=="1") { +?> + <?php echo _T(" align="middle" width="12" height="13"> + + + + ">fields[1])." ".htmlentities($resultat->fields[2], ENT_QUOTES, "ISO-8859-15"); ?> + + fields[8]!="") echo "fields[8], ENT_QUOTES, "ISO-8859-15")."\">".htmlentities($resultat->fields[8], ENT_QUOTES, "ISO-8859-15").""; ?>  + fields[5]) ?> + <?php echo _T(" border="0" width="12" height="13"> + <?php echo _T(" border="0" width="13" height="13"> + ')" href="gestion_adherents.php?sup=fields[0] ?>"><?php echo _T(" border="0" width="11" height="13"> +
    + +
    +
    + + Légume + Pain + +
    ">
    + +
    + + + + + + + + + + + + + + + + +
    " size="80">
    +
    + "> +
    +
    + + +
    +Execute($requete); + if (isset($_POST["mailing_confirmed"])) + $confirm_detected = _T("Pensez à contacter les adhérents ne disposant pas d'une adresse E-Mail par un autre moyen."); +?> +

    +
    "._T("- ATTENTION -")."
    " . $confirm_detected . "
    "; +?> +
    + + + + + + + + +EOF) + { +?> + + + +EOF) + { + if (isset($_POST["mailing_confirmed"])) + { + mail ($resultat->fields[8], $mailing_objet, $mailing_corps,"From: ".PREF_EMAIL_NOM." <".PREF_EMAIL.">\r\nContent-Type: text/plain; charset=utf8\r\nContent-Transfer-Encoding: 8bit\r\nMime-Version: 1.0"); + $concatmail = $concatmail . " " . $resultat->fields[8]; + $num_mails++; + } + + // définition CSS pour adherent désactivé + if ($resultat->fields[4]=="1") + $activity_class = ""; + else + $activity_class = " class=\"inactif\""; + + // temps d'adhésion + if($resultat->fields[6]) + { + $statut_cotis = _T("Exempt de cotisation"); + $color = "#DDFFDD"; + } + else + { + if ($resultat->fields[10]=="") + { + $statut_cotis = _T("N'a jamais cotisé"); + $color = "#EEEEEE"; + } + else + { + $date_fin = split("-",$resultat->fields[10]); + $ts_date_fin = mktime(0,0,0,$date_fin[1],$date_fin[2],$date_fin[0]); + $aujourdhui = time(); + + $difference = intval(($ts_date_fin - $aujourdhui)/(3600*24)); + if ($difference==0) + { + $statut_cotis = _T("Dernier jour !"); + $color = "#FFDDDD"; + } + elseif ($difference<0) + { + $statut_cotis = _T("En retard de ").-$difference." "._T("jours")." ("._T("depuis le")." ".$date_fin[2]."/".$date_fin[1]."/".$date_fin[0].")"; + $color = "#FFDDDD"; + } + else + { + $statut_cotis = $difference." "._T("jours restants")." ("._T("fin le")." ".$date_fin[2]."/".$date_fin[1]."/".$date_fin[0].")"; + if ($difference < 30) + $color = "#FFE9AB"; + else + $color = "#DDFFDD"; + } + } + } + +?> + + + + + + + +MoveNext(); + } + + if (isset($_POST["mailing_confirmed"])) + dblog(_T("Envoi d'un mailing intitulé :")." \"".$mailing_objet."\" - ".$num_mails." "._T("destinataires"), $concatmail."\n".$mailing_corps); + + $resultat->Close(); +?> +
    > +fields[7]=="1") { +?> + <?php echo _T(" align="middle" width="10" height="12"> + + <?php echo _T(" align="middle" width="9" height="12"> + +fields[9]=="1") { +?> + <?php echo _T(" align="middle" width="12" height="13"> + + + + ">fields[1]), ENT_QUOTES)." ".htmlentities($resultat->fields[2], ENT_QUOTES) ?> + > + fields[8]!="") echo "fields[8], ENT_QUOTES)."\">".htmlentities($resultat->fields[8], ENT_QUOTES).""; ?>  + > + fields[5]) ?> + > + +
    +
    + + + + + +
    +
    +
    + + + + + + + + + +
    +
    +"; + } +?> + "> + "> + ">    +
    +
    +
    +"; + } +?> + "> + "> + + +    "> +
    +
    +
    + "> +
    +
    +
    +
    + + + + + + + + +Execute($requete); + + if ($resultat->EOF) + { +?> + + + +EOF) + { + // définition CSS pour adherent désactivé + if ($resultat->fields[4]=="1") + $activity_class = ""; + else + $activity_class = " class=\"inactif\""; + + // temps d'adhésion + if($resultat->fields[6]) + { + $statut_cotis = _T("Exempt de cotisation"); + $color = "#DDFFDD"; + } + else + { + if ($resultat->fields[10]=="") + { + $statut_cotis = _T("N'a jamais cotisé"); + $color = "#EEEEEE"; + } + else + { + $date_fin = split("-",$resultat->fields[10]); + $ts_date_fin = mktime(0,0,0,$date_fin[1],$date_fin[2],$date_fin[0]); + $aujourdhui = time(); + + $difference = intval(($ts_date_fin - $aujourdhui)/(3600*24)); + if ($difference==0) + { + $statut_cotis = _T("Dernier jour !"); + $color = "#FFDDDD"; + } + elseif ($difference<0) + { + $statut_cotis = _T("En retard de ").-$difference." "._T("jours")." ("._T("depuis le")." ".$date_fin[2]."/".$date_fin[1]."/".$date_fin[0].")"; + $color = "#FFDDDD"; + } + else + { + $statut_cotis = $difference." "._T("jours restants")." ("._T("fin le")." ".$date_fin[2]."/".$date_fin[1]."/".$date_fin[0].")"; + if ($difference < 30) + $color = "#FFE9AB"; + else + $color = "#DDFFDD"; + } + } + } + +?> + + +"; + $adresse_adh = ""; + if ($resultat->fields[3]!="") + $adresse_adh .= htmlentities($resultat->fields[3], ENT_QUOTES); + if ($resultat->fields[8]!="") + { + if ($adresse_adh!="") + $adresse_adh .= "
    "; + $adresse_adh .= htmlentities($resultat->fields[8], ENT_QUOTES); + } + if ($resultat->fields[11]!="") + { + if ($adresse_adh!="") + $adresse_adh .= "
    "; + $adresse_adh .= htmlentities($resultat->fields[11], ENT_QUOTES); + } + if ($resultat->fields[16]!="") + { + if ($adresse_adh!="") + $adresse_adh .= "
    "; + $adresse_adh .= htmlentities($resultat->fields[16], ENT_QUOTES); + } + if ($resultat->fields[18]!="") + { + if ($adresse_adh!="") + $adresse_adh .= "
    "; + $adresse_adh .= htmlentities($resultat->fields[18], ENT_QUOTES); + } + if ($adresse_adh!="") + $coord_adh .= ""; + if ($resultat->fields[12]!="") + $coord_adh .= ""; + if ($resultat->fields[13]!="") + $coord_adh .= ""; + if ($resultat->fields[15]!="") + $coord_adh .= ""; + if ($resultat->fields[17]!="") + $coord_adh .= ""; + if ($resultat->fields[14]!="") + $coord_adh .= ""; + $coord_adh .= "
    > +fields[7]=="1") { +?> + <?php echo _T(" align="middle" width="10" height="12"> + + <?php echo _T(" align="middle" width="9" height="12"> + +fields[9]=="1") { +?> + <?php echo _T(" align="middle" width="12" height="13"> + + + + ">fields[1]), ENT_QUOTES)." ".htmlentities($resultat->fields[2], ENT_QUOTES); ?> +
    ".str_replace(" "," ",_T("Adresse :"))." ".$adresse_adh."
    ".str_replace(" "," ",_T("Tel :"))." ".htmlentities($resultat->fields[12], ENT_QUOTES)."
    ".str_replace(" "," ",_T("GSM :"))." ".htmlentities($resultat->fields[13], ENT_QUOTES)."
    ".str_replace(" "," ",_T("ICQ :"))." ".htmlentities($resultat->fields[15], ENT_QUOTES)."
    ".str_replace(" "," ",_T("Jabber :"))." ".htmlentities($resultat->fields[17], ENT_QUOTES)."
    ".str_replace(" "," ",_T("MSN :"))." ".htmlentities($resultat->fields[14], ENT_QUOTES)."
    "; +?> + "> + >fields[5]) ?> + > + + +fields[0]; + $resultat->MoveNext(); + } + $resultat->Close(); + + +?> + +
    +
    + + + + + + + + + +
    +
    +"; + } +?> + "> + "> + ">    +
    +
    +
    + "> +
    +
    +
    +"; + } +?> +    "> +
    + +
    +
    + diff --git a/seed/galette/manual/image/postinstall/galette/paysage.jpg b/seed/galette/manual/image/postinstall/galette/paysage.jpg new file mode 100644 index 0000000..cb4b0f2 Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/paysage.jpg differ diff --git a/seed/galette/manual/image/postinstall/galette/point.png b/seed/galette/manual/image/postinstall/galette/point.png new file mode 100644 index 0000000..9e3f6b5 Binary files /dev/null and b/seed/galette/manual/image/postinstall/galette/point.png differ diff --git a/seed/galette/manual/image/postinstall/galette/preferences.php b/seed/galette/manual/image/postinstall/galette/preferences.php new file mode 100644 index 0000000..03268b0 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/preferences.php @@ -0,0 +1,518 @@ + modif ou création + + // variables d'erreur (pour affichage) + $error_detected = ""; + $warning_detected = ""; + + // + // DEBUT parametrage des champs + // on initialise des valeurs par defaut + + // recup des donnees + $requete = "SELECT nom_pref + FROM ".PREFIX_DB."preferences"; + $result = &$DB->Execute($requete); + while (!$result->EOF) + { + $fieldname = $result->fields["nom_pref"]; + $$fieldname = ""; + + // declaration des champs obligatoires + $fieldreq = $fieldname."_req"; + if ($fieldname=="pref_nom" || + $fieldname=="pref_lang" || + $fieldname=="pref_numrows" || + $fieldname=="pref_log" || + $fieldname=="pref_email_nom" || + $fieldname=="pref_email" || + $fieldname=="pref_etiq_marges" || + $fieldname=="pref_etiq_hspace" || + $fieldname=="pref_etiq_vspace" || + $fieldname=="pref_etiq_hsize" || + $fieldname=="pref_etiq_vsize" || + $fieldname=="pref_etiq_cols" || + $fieldname=="pref_etiq_rows" || + $fieldname=="pref_etiq_corps" || + $fieldname=="pref_admin_login" || + $fieldname=="pref_admin_pass") + $$fieldreq = " style=\"color: #FF0000;\""; + else + $$fieldreq = ""; + + $result->MoveNext(); + } + $result->Close(); + + // + // FIN parametrage des champs + // + + // + // Validation du formulaire + // + + if (isset($_POST["valid"])) + { + // verification de champs + $insert_values = array(); + + // recuperation de la liste de champs de la table + $requete = "SELECT nom_pref + FROM ".PREFIX_DB."preferences"; + $result=&$DB->Execute($requete); + while (!$result->EOF) + { + $fieldname = $result->fields["nom_pref"]; + $fieldreq = $fieldname."_req"; + + if (isset($_POST[$fieldname])) + $post_value=trim($_POST[$fieldname]); + else + $post_value=""; + + // on declare les variables pour la présaisie en cas d'erreur + $$fieldname=htmlentities(stripslashes($post_value),ENT_QUOTES); + + // vérification de la présence des champs obligatoires + $req = $$fieldreq; + if ($req!="" && $post_value=="") + $error_detected .= "
  • "._T("- Champ obligatoire non renseigné.")."
  • "; + else + { + // validation de la langue + if ($fieldname=="pref_lang") + { + if (file_exists(WEB_ROOT . "lang/lang_" . $post_value . ".php")) + $value = $DB->qstr($post_value, true); + else + $error_detected .= "
  • "._T("- Langue non valide !")."
  • "; + } + // validation des adresses mail + elseif ($fieldname=="pref_email") + { + $post_value=strtolower($post_value); + if (!is_valid_email($post_value) && $post_value!="") + $error_detected .= "
  • "._T("- Adresse E-mail non valide !")."
  • "; + else + $value = $DB->qstr($post_value, true); + } + // validation login + elseif ($fieldname=="pref_admin_login") + { + if (strlen($post_value)<4) + $error_detected .= "
  • "._T("- L'identifiant doit être composé d'au moins 4 caractères !")."
  • "; + else + { + // on vérifie que le login n'est pas déjà utilisé + $requete = "SELECT id_adh + FROM ".PREFIX_DB."adherents + WHERE login_adh=". $DB->qstr($post_value, true); + if (isset($id_adh)) + $requete .= " AND id_adh!=" . $DB->qstr($id_adh, true); + + $result2 = &$DB->Execute($requete); + if (!$result2->EOF) + $error_detected .= "
  • "._T("- Cet identifiant est déjà utilisé par un adhérent !")."
  • "; + else + $value = $DB->qstr($post_value, true); + } + } + // validation des entiers + elseif ($fieldname=="pref_numrows" || + $fieldname=="pref_etiq_marges" || + $fieldname=="pref_etiq_hspace" || + $fieldname=="pref_etiq_vspace" || + $fieldname=="pref_etiq_hsize" || + $fieldname=="pref_etiq_vsize" || + $fieldname=="pref_etiq_cols" || + $fieldname=="pref_etiq_rows" || + $fieldname=="pref_etiq_corps") + { + // évitons la divison par zero + if ($fieldname=="pref_numrows" && $post_value=="0") + $post_value="1"; + + if ((is_numeric($post_value) && $post_value >=0) || $post_value=="") + $value=$DB->qstr($post_value,ENT_QUOTES); + else + $error_detected .= "
  • "._T("- Les nombres et mesures doivent être des entiers !")."
  • "; + } + // validation mot de passe + elseif ($fieldname=="pref_admin_pass") + { + if (strlen($post_value)<4) + $error_detected .= "
  • "._T("- Le mot de passe doit être composé d'au moins 4 caractères !")."
  • "; + else + $value = $DB->qstr($post_value, true); + } + else + { + // on se contente d'escaper le html et les caracteres speciaux + $value = $DB->qstr($post_value, true); + } + + // mise a jour des chaines d'insertion + if ($value=="''") + $value="NULL"; + $insert_values[$fieldname] = $value; + } + $result->MoveNext(); + } + $result->Close(); + + // modif ou ajout + if ($error_detected=="") + { + // vidage des preferences + $requete = "DELETE FROM ".PREFIX_DB."preferences"; + $DB->Execute($requete); + + // insertion des nouvelles preferences + while (list($champ,$valeur)=each($insert_values)) + { + $requete = "INSERT INTO ".PREFIX_DB."preferences + (nom_pref, val_pref) + VALUES (".$DB->qstr($champ).",".$valeur.");"; + $DB->Execute($requete); + } + + // ajout photo + if (isset($_FILES["photo"]["tmp_name"])) + if ($_FILES["photo"]["tmp_name"]!="none" && + $_FILES["photo"]["tmp_name"]!="") + { + + if ($_FILES['photo']['type']=="image/jpeg" || + (function_exists("ImageCreateFromGif") && $_FILES['photo']['type']=="image/gif") || + $_FILES['photo']['type']=="image/png" || + $_FILES['photo']['type']=="image/x-png") + { + $tmp_name = $HTTP_POST_FILES["photo"]["tmp_name"]; + + // extension du fichier (en fonction du type mime) + if ($_FILES['photo']['type']=="image/jpeg") + $ext_image = ".jpg"; + if ($_FILES['photo']['type']=="image/png" || $_FILES['photo']['type']=="image/x-png") + $ext_image = ".png"; + if ($_FILES['photo']['type']=="image/gif") + $ext_image = ".gif"; + + // suppression ancienne photo + // NB : une verification sur le type de $id_adh permet d'eviter une faille + // du style $id_adh = "../../../image" + @unlink(WEB_ROOT . "photos/logo.jpg"); + @unlink(WEB_ROOT . "photos/logo.gif"); + @unlink(WEB_ROOT . "photos/logo.jpg"); + @unlink(WEB_ROOT . "photos/tn_logo.jpg"); + @unlink(WEB_ROOT . "photos/tn_logo.gif"); + @unlink(WEB_ROOT . "photos/tn_logo.jpg"); + + // copie fichier temporaire + if (!@move_uploaded_file($tmp_name,WEB_ROOT . "photos/logo".$ext_image)) + $warning_detected .= "
  • "._T("- La photo semble ne pas avoir été transmise correstement. L'enregistrement a cependant été effectué.")."
  • "; + else + resizeimage(WEB_ROOT . "photos/logo".$ext_image,WEB_ROOT . "photos/tn_logo".$ext_image,130,130); + + } + else + { + if (function_exists("ImageCreateFromGif")) + $warning_detected .= "
  • "._T("- Le fichier transmis n'est pas une image valide (GIF, PNG ou JPEG). L'enregistrement a cependant été effectué.")."
  • "; + else + $warning_detected .= "
  • "._T("- Le fichier transmis n'est pas une image valide (PNG ou JPEG). L'enregistrement a cependant été effectué.")."
  • "; + } + } + + // retour à l'accueil + if ($warning_detected=="") + { + header("location: index.php"); + die(); + } + } + } + + // suppression photo + if (isset($_POST["del_photo"])) + { + @unlink(WEB_ROOT . "photos/logo.jpg"); + @unlink(WEB_ROOT . "photos/logo.png"); + @unlink(WEB_ROOT . "photos/logo.gif"); + @unlink(WEB_ROOT . "photos/tn_logo.jpg"); + @unlink(WEB_ROOT . "photos/tn_logo.png"); + @unlink(WEB_ROOT . "photos/tn_logo.gif"); + } + + // + // Pré-remplissage des champs + // avec des valeurs issues de la base + // -> donc uniquement si l'enregistrement existe et que le formulaire + // n'a pas déja été posté avec des erreurs (pour pouvoir corriger) + + if (!isset($_POST["valid"]) || (isset($_POST["valid"]) && $error_detected=="")) + { + // recup des donnees + $requete = "SELECT * + FROM ".PREFIX_DB."preferences"; + $result = &$DB->Execute($requete); + if ($result->EOF) + { + header("location: index.php"); + die(); + } else + { + while (!$result->EOF) + { + $fieldname=$result->fields["nom_pref"]; + $$fieldname = htmlentities(stripslashes(addslashes($result->fields["val_pref"])), ENT_QUOTES); + $result->MoveNext(); + } + } + $result->Close(); + } + else + { + // initialisation des champs + } + + include("header.php"); + +?> +

    +
    + +
    +

    +
      + +
    +
    + +
    +

    +
      + +
    +
    + +
    +
    + + + + + + + + + + + + + + + id="libelle"> + + + + + + + + id="libelle"> + + + + id="libelle"> + + + + + + + id="libelle"> + + + + id="libelle"> + + + + id="libelle"> + + + + + + + id="libelle"> + + + + id="libelle"> + + + + + + + id="libelle"> + + + + id="libelle"> + + + + id="libelle"> + + + + id="libelle"> + + + + id="libelle"> + + + + id="libelle"> + + + + id="libelle"> + + + + id="libelle"> + + + + + + + + + + + + + + + + +
    id="libelle">
    + + <?php echo _T(" width="" height="">
    + "> + + + +
     

    + +
    + +


    mm
    mm
    mm
    mm
    mm

    id="libelle">
    id="libelle">

    ">
    +
    +
    + . +
    +
    + diff --git a/seed/galette/manual/image/postinstall/galette/style.css b/seed/galette/manual/image/postinstall/galette/style.css new file mode 100644 index 0000000..ccc8f30 --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/style.css @@ -0,0 +1,170 @@ +body { + font-family: Verdana, Arial, Helvetica, sans-serif; + background: url('legumes.jpg') top right no-repeat; + margin : 0; + padding : 0; +} +#accueil { + background: none; +} +ul.menu { + text-align: center; + font-size: 13px; +} + +ul.menu li { + display: inline; + margin: 0px; + color: green; +} +ul.menu a:link, ul.menu a:visited, ul.menu a:hover, ul.menu a:active { + color: green; + text-decoration: none; +} + +h1 { + font-family: Verdana, Arial, Helvetica, sans-serif; + text-align: center; + color: green; + padding: 50px; + padding-right: 400px; + margin: 0px; +} + +h2 { + font: italic 22px Georgia, "Times New Roman", Times, serif; + color: red; + text-align: center; + padding-top: 15px; + padding-bottom: 5px; +/* padding-left: 180px;*/ +} + +#body { + margin-left: 120px; + width: 630px; + background: url('paysage.jpg') bottom right no-repeat; +} + +#bodyaccueil ul a:link, #bodyaccueil ul a:visited, #bodyaccueil ul a:hover, #bodyaccueil ul a:active { + font: italic 1em Georgia, "Times New Roman", Times, serif; + color: red; + font-weight: bold; +} + +.legume { + float: left; + clear: left; + margin: 0 3em 0 0; +} + +#content { + padding: 10px; + border-left: 1px solid #b6fe76; + border-right: 1px solid #b6fe76; +} + +#content p, #content blockquote { + text-align: justify; +} +#content blockquote { + padding-left: 50px; +} +#content ul { + text-align: justify; +} +#content li { + list-style-image: url(point.png); +} +#soustitre { + color: green; + font-weight: bold; + margin-bottom: 50px; + padding-left: 150px; + font-size: 14px; +} +#licencewikipedia { + text-align: center; + font-style: italic; + color: red; + margin: 2em 4em 0 4em; +} +#pieddepage { + margin-top: 80px; + padding-bottom: 20px; + text-align: center; + color: green; + font-size: x-small; + font-weight: bold; +} +#pieddepage a:link, #pieddepage a:visited, #pieddepage a:hover, #pieddepage a:active { + color: green; +} + +fieldset { + border: 1px solid #FFA3A3; + margin-top: 1em; + margin-bottom: 2em; + padding: 1em; +} +fieldset textarea, fieldset input, fieldset legend { + border: 1px solid #FFA3A3; + background-color: #F3FFE8; +} + +fieldset legend { + background: url(point.png) center left no-repeat; + padding: 2px 6px; + padding-left: 15px; +} + +fieldset input.text { + width: 360px; +} + +fieldset textarea { + width: 560px; +} + +fieldset label { + font-style: italic; + display: inline; + float: left; + width: 200px; +} + +#bodyaccueil ul li { + margin-bottom: 1.5em; +} + +* html .hauteur225 {height: 225px} +.hauteur225 {min-height: 225px;} + +* html .hauteur167 {height: 167px} +.hauteur167 {min-height: 167px;} + +.cartedevisite { + color: green; + background: url('carte_visite.jpg') top right no-repeat; + height: 210px; + width: 330px; +} +.cartedevisite div { + text-align: left; + padding: 50px 30px 0 75px; +} +#openlayers { + padding: 0; + margin: 0; + position: absolute; + left: 10px; + right: 10px; + top: 70px; + bottom: 10px; +} +#map { + border: 1px solid black; + margin: 5px; +} +.olControlAttribution { bottom: 10px!important; left: 10px;} + diff --git a/seed/galette/manual/image/postinstall/galette/voir_adherent.php b/seed/galette/manual/image/postinstall/galette/voir_adherent.php new file mode 100644 index 0000000..e0a4fbf --- /dev/null +++ b/seed/galette/manual/image/postinstall/galette/voir_adherent.php @@ -0,0 +1,331 @@ + modif ou création + if (isset($_GET["id_adh"])) + if (is_numeric($_GET["id_adh"])) + $id_adh = $_GET["id_adh"]; + + if ($_SESSION["admin_status"]==0) + $id_adh = $_SESSION["logged_id_adh"]; + if ($id_adh=="") + { + header("location: index.php"); + die(); + } + + // + // Pré-remplissage des champs + // avec des valeurs issues de la base + // + + $requete = "SELECT * + FROM ".PREFIX_DB."adherents + WHERE id_adh=$id_adh"; + $result = $DB->Execute($requete); + if ($result->EOF) + { + header("location: index.php"); + die(); + } + + // recuperation de la liste de champs de la table + $values = Array(); + $fields = $DB->MetaColumns(PREFIX_DB."adherents"); + foreach ($fields as $champ => $proprietes) + { + $val=""; + $proprietes_arr = get_object_vars($proprietes); + // on obtient name, max_length, type, not_null, has_default, primary_key, + + // déclaration des variables correspondant aux champs + // et reformatage des dates. + + // on doit faire cette verif pour une enventuelle valeur "NULL" + // non renvoyée -> ex: pas de tel + // sinon on obtient un warning + if (isset($result->fields[$proprietes_arr["name"]])) + $val = $result->fields[$proprietes_arr["name"]]; + + if($proprietes_arr["type"]=="date" && $val!="") + { + list($a,$m,$j)=explode("-",$val); + $val="$j/$m/$a"; + } + $values[$proprietes_arr["name"]] = htmlentities(stripslashes(addslashes($val)), ENT_QUOTES); + } + reset($fields); + include("header.php"); +?> +

    +
    +
    + + + + + +\""._T("Photo")."\""; + } + else + $photo_adh = _T("[ pas de photo ]"); + + if ($_SESSION["admin_status"]!=0) + $rowspan_photo = "8"; + else + $rowspan_photo = "5"; +?> + + + + + + + + + + + + +Execute($requete); + if (!$result->EOF) + $libelle_statut = _T($result->fields["libelle_statut"]); + $result->Close(); + } else { + $libelle_statut = ''; + } +?> + + + + + + + + + + + + + + + + + / + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +"._T("[ Ajouter une contribution ]").""; + } +?> + + + + + + + +
     
     
     
     
     
     
     
      
      
      
      
      
     
      
     

       
    +
    +
    +
    + diff --git a/seed/galette/manual/image/preinstall/galette.sh b/seed/galette/manual/image/preinstall/galette.sh new file mode 100644 index 0000000..4d8628f --- /dev/null +++ b/seed/galette/manual/image/preinstall/galette.sh @@ -0,0 +1 @@ +PKG="$PKG php-mysqlnd" diff --git a/seed/galette/templates/config.inc.php b/seed/galette/templates/config.inc.php new file mode 100644 index 0000000..96c4f88 --- /dev/null +++ b/seed/galette/templates/config.inc.php @@ -0,0 +1,9 @@ + diff --git a/seed/galette/templates/galette.nginx.conf b/seed/galette/templates/galette.nginx.conf new file mode 100644 index 0000000..b2dcbb5 --- /dev/null +++ b/seed/galette/templates/galette.nginx.conf @@ -0,0 +1,34 @@ +# To allow POST on static pages +error_page 405 =200 $uri; +add_header X-Frame-Options "SAMEORIGIN"; +add_header X-Content-Type-Options nosniff; +add_header X-XSS-Protection "1; mode=block"; +add_header X-Robots-Tag none; +add_header X-Download-Options noopen; +add_header X-Permitted-Cross-Domain-Policies none; +add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains;'; +add_header Referrer-Policy no-referrer always; + +%set %%locations = [] +%for %%revprox in %%revprox_client_external_domainnames + %set %%location = %%revprox.revprox_client_location + %if %%location in %%locations + %continue + %end if + %%locations.append(%%location) +location %%location { + %if %%location == '/' + root %slurp + %else + alias %slurp + %end if +/usr/local/share/galette/; + index index.php; + location ~ ^(?.+?\.php)(?/.*)?$ { + fastcgi_pass php-fpm; + fastcgi_index index.php; + fastcgi_param SCRIPT_FILENAME $request_filename; + include fastcgi_params; + } +} +%end for