__DIR__ was not replaced into scripts dir

This commit is contained in:
Laurent Destailleur 2019-05-15 13:20:02 +02:00
parent f94b9e5a12
commit a9b3748006
23 changed files with 2523 additions and 3015 deletions

View File

@ -1,7 +1,7 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/* /*
* Copyright (C) 2013 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2013 Laurent Destailleur <eldy@users.sourceforge.net>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -10,7 +10,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -18,200 +18,160 @@
*/ */
/** /**
* \file scripts/bank/export-bank-receipts.php * \file scripts/bank/export-bank-receipts.php
* \ingroup bank * \ingroup bank
* \brief Script file to export bank receipts into Excel files * \brief Script file to export bank receipts into Excel files
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
require_once $path."../../htdocs/master.inc.php"; require_once $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/bank.lib.php';
require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php'; require_once DOL_DOCUMENT_ROOT . '/compta/sociales/class/chargesociales.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; require_once DOL_DOCUMENT_ROOT . '/compta/tva/class/tva.class.php';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; require_once DOL_DOCUMENT_ROOT . '/fourn/class/paiementfourn.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; require_once DOL_DOCUMENT_ROOT . '/compta/tva/class/tva.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/paymentsocialcontribution.class.php'; require_once DOL_DOCUMENT_ROOT . '/compta/sociales/class/paymentsocialcontribution.class.php';
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
if (! isset($argv[3]) || ! $argv[3]) { if (! isset($argv[3]) || ! $argv[3]) {
print "Usage: ".$script_file." bank_ref [bank_receipt_number|all] (csv|tsv|excel|excel2007) [lang=xx_XX]\n"; print "Usage: " . $script_file . " bank_ref [bank_receipt_number|all] (csv|tsv|excel|excel2007) [lang=xx_XX]\n";
exit(-1); exit(- 1);
} }
$bankref=$argv[1]; $bankref = $argv[1];
$num=$argv[2]; $num = $argv[2];
$model=$argv[3]; $model = $argv[3];
$newlangid='en_EN'; // To force a new lang id $newlangid = 'en_EN'; // To force a new lang id
$invoicestatic=new Facture($db);
$invoicesupplierstatic=new FactureFournisseur($db);
$societestatic=new Societe($db);
$chargestatic=new ChargeSociales($db);
$memberstatic=new Adherent($db);
$paymentstatic=new Paiement($db);
$paymentsupplierstatic=new PaiementFourn($db);
$paymentsocialcontributionstatic=new PaymentSocialContribution($db);
$paymentvatstatic=new Tva($db);
$bankstatic=new Account($db);
$banklinestatic=new AccountLine($db);
$invoicestatic = new Facture($db);
$invoicesupplierstatic = new FactureFournisseur($db);
$societestatic = new Societe($db);
$chargestatic = new ChargeSociales($db);
$memberstatic = new Adherent($db);
$paymentstatic = new Paiement($db);
$paymentsupplierstatic = new PaiementFourn($db);
$paymentsocialcontributionstatic = new PaymentSocialContribution($db);
$paymentvatstatic = new Tva($db);
$bankstatic = new Account($db);
$banklinestatic = new AccountLine($db);
// Parse parameters // Parse parameters
foreach ($argv as $key => $value) foreach ($argv as $key => $value) {
{ $found = false;
$found=false;
// Define options // Define options
if (preg_match('/^lang=/i', $value)) if (preg_match('/^lang=/i', $value)) {
{ $found = true;
$found=true; $valarray = explode('=', $value);
$valarray=explode('=', $value); $newlangid = $valarray[1];
$newlangid=$valarray[1]; print 'Use language ' . $newlangid . ".\n";
print 'Use language '.$newlangid.".\n";
} }
} }
$outputlangs = $langs; $outputlangs = $langs;
if (! empty($newlangid)) if (! empty($newlangid)) {
{ if ($outputlangs->defaultlang != $newlangid) {
if ($outputlangs->defaultlang != $newlangid)
{
$outputlangs = new Translate("", $conf); $outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlangid); $outputlangs->setDefaultLang($newlangid);
} }
} }
// Load translation files required by the page // Load translation files required by the page
$outputlangs->loadLangs(array("main", "companies", "bills", "banks", "members", "compta")); $outputlangs->loadLangs(array("main","companies","bills","banks","members","compta"));
$acct=new Account($db); $acct = new Account($db);
$result=$acct->fetch('', $bankref); $result = $acct->fetch('', $bankref);
if ($result <= 0) if ($result <= 0) {
{ print "Failed to find bank account with ref " . $bankref . ".\n";
print "Failed to find bank account with ref ".$bankref.".\n"; exit(- 1);
exit(-1); } else {
print "Export for bank account " . $acct->ref . " (" . $acct->label . ").\n";
} }
else
{
print "Export for bank account ".$acct->ref." (".$acct->label.").\n";
}
// Creation de la classe d'export du model ExportXXX // Creation de la classe d'export du model ExportXXX
$dir = DOL_DOCUMENT_ROOT . "/core/modules/export/"; $dir = DOL_DOCUMENT_ROOT . "/core/modules/export/";
$file = "export_".$model.".modules.php"; $file = "export_" . $model . ".modules.php";
$classname = "Export".$model; $classname = "Export" . $model;
if (! dol_is_file($dir.$file)) if (! dol_is_file($dir . $file)) {
{ print "No driver to export with format " . $model . "\n";
print "No driver to export with format ".$model."\n"; exit(- 1);
exit(-1);
} }
require_once $dir.$file; require_once $dir . $file;
$objmodel = new $classname($db); $objmodel = new $classname($db);
// Define target path // Define target path
$dirname = $conf->bank->dir_temp; $dirname = $conf->bank->dir_temp;
$filename = 'export-bank-receipts-'.$bankref.'-'.$num.'.'.$objmodel->extension; $filename = 'export-bank-receipts-' . $bankref . '-' . $num . '.' . $objmodel->extension;
$array_fields=array(
'bankreceipt'=>$outputlangs->transnoentitiesnoconv("AccountStatementShort"), 'bankaccount'=>$outputlangs->transnoentitiesnoconv("BankAccount"),
'dateop'=>$outputlangs->transnoentitiesnoconv("DateOperationShort"),'dateval'=>$outputlangs->transnoentitiesnoconv("DateValueShort"),'type'=>$outputlangs->transnoentitiesnoconv("Type"),
'description'=>$outputlangs->transnoentitiesnoconv("Description"), 'thirdparty'=>$outputlangs->transnoentitiesnoconv("Tiers"), 'accountelem'=>$outputlangs->transnoentitiesnoconv("Piece"),
'debit'=>$outputlangs->transnoentitiesnoconv("Debit"), 'credit'=>$outputlangs->transnoentitiesnoconv("Credit"),
'soldbefore'=>$outputlangs->transnoentitiesnoconv("BankBalanceBefore"), 'soldafter'=>$outputlangs->transnoentitiesnoconv("BankBalanceAfter"),
'comment'=>$outputlangs->transnoentitiesnoconv("Comment")
);
$array_selected=array(
'bankreceipt'=>'bankreceipt', 'bankaccount'=>'bankaccount',
'dateop'=>'dateop','dateval'=>'dateval','type'=>'type',
'description'=>'description', 'thirdparty'=>'thirdparty', 'accountelem'=>'accountelem',
'debit'=>'debit', 'credit'=>'credit',
'soldbefore'=>'soldbefore','soldafter'=>'soldafter',
'comment'=>'comment'
);
$array_export_TypeFields=array(
'bankreceipt'=>'Text', 'bankaccount'=>'Text',
'dateop'=>'Date','dateval'=>'Date','type'=>'Text',
'description'=>'Text', 'thirdparty'=>'Text', 'accountelem'=>'Text',
'debit'=>'Number', 'credit'=>'Number',
'soldbefore'=>'Number','soldafter'=>'Number',
'comment'=>'Text'
);
$array_fields = array('bankreceipt' => $outputlangs->transnoentitiesnoconv("AccountStatementShort"),'bankaccount' => $outputlangs->transnoentitiesnoconv("BankAccount"),'dateop' => $outputlangs->transnoentitiesnoconv("DateOperationShort"),'dateval' => $outputlangs->transnoentitiesnoconv("DateValueShort"),'type' => $outputlangs->transnoentitiesnoconv("Type"),'description' => $outputlangs->transnoentitiesnoconv("Description"),'thirdparty' => $outputlangs->transnoentitiesnoconv("Tiers"),'accountelem' => $outputlangs->transnoentitiesnoconv("Piece"),'debit' => $outputlangs->transnoentitiesnoconv("Debit"),'credit' => $outputlangs->transnoentitiesnoconv("Credit"),'soldbefore' => $outputlangs->transnoentitiesnoconv("BankBalanceBefore"),'soldafter' => $outputlangs->transnoentitiesnoconv("BankBalanceAfter"),'comment' => $outputlangs->transnoentitiesnoconv("Comment"));
$array_selected = array('bankreceipt' => 'bankreceipt','bankaccount' => 'bankaccount','dateop' => 'dateop','dateval' => 'dateval','type' => 'type','description' => 'description','thirdparty' => 'thirdparty','accountelem' => 'accountelem','debit' => 'debit','credit' => 'credit','soldbefore' => 'soldbefore','soldafter' => 'soldafter','comment' => 'comment');
$array_export_TypeFields = array('bankreceipt' => 'Text','bankaccount' => 'Text','dateop' => 'Date','dateval' => 'Date','type' => 'Text','description' => 'Text','thirdparty' => 'Text','accountelem' => 'Text','debit' => 'Number','credit' => 'Number','soldbefore' => 'Number','soldafter' => 'Number','comment' => 'Text');
// Build request to find records for a bank account/receipt // Build request to find records for a bank account/receipt
$listofnum=""; $listofnum = "";
if (! empty($num) && $num != "all") if (! empty($num) && $num != "all") {
{ $listofnum .= "'";
$listofnum.="'"; $arraynum = explode(',', $num);
$arraynum=explode(',', $num); foreach ($arraynum as $val) {
foreach($arraynum as $val) if ($listofnum != "'")
{ $listofnum .= "','";
if ($listofnum != "'") $listofnum.="','"; $listofnum .= $val;
$listofnum.=$val;
} }
$listofnum.="'"; $listofnum .= "'";
} }
$sql = "SELECT b.rowid, b.dateo as do, b.datev as dv,"; $sql = "SELECT b.rowid, b.dateo as do, b.datev as dv,";
$sql.= " b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type,"; $sql .= " b.amount, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type,";
$sql.= " ba.rowid as bankid, ba.ref as bankref, ba.label as banklabel"; $sql .= " ba.rowid as bankid, ba.ref as bankref, ba.label as banklabel";
$sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba"; $sql .= " FROM " . MAIN_DB_PREFIX . "bank_account as ba";
$sql.= ", ".MAIN_DB_PREFIX."bank as b"; $sql .= ", " . MAIN_DB_PREFIX . "bank as b";
$sql.= " WHERE b.fk_account = ".$acct->id; $sql .= " WHERE b.fk_account = " . $acct->id;
if ($listofnum) $sql.= " AND b.num_releve IN (".$listofnum.")"; if ($listofnum)
if (!isset($num)) $sql.= " OR b.num_releve is null"; $sql .= " AND b.num_releve IN (" . $listofnum . ")";
$sql.= " AND b.fk_account = ba.rowid"; if (! isset($num))
$sql.= $db->order("b.num_releve, b.datev, b.datec", "ASC"); // We add date of creation to have correct order when everything is done the same day $sql .= " OR b.num_releve is null";
//print $sql; $sql .= " AND b.fk_account = ba.rowid";
$sql .= $db->order("b.num_releve, b.datev, b.datec", "ASC"); // We add date of creation to have correct order when everything is done the same day
// print $sql;
$resql=$db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{ $balancebefore = array();
$balancebefore=array();
$numrows = $db->num_rows($resql); $numrows = $db->num_rows($resql);
if ($numrows > 0) if ($numrows > 0) {
{
// Open file // Open file
print 'Open file '.$filename.' into directory '.$dirname."\n"; print 'Open file ' . $filename . ' into directory ' . $dirname . "\n";
dol_mkdir($dirname); dol_mkdir($dirname);
$result=$objmodel->open_file($dirname."/".$filename, $outputlangs); $result = $objmodel->open_file($dirname . "/" . $filename, $outputlangs);
if ($result < 0) if ($result < 0) {
{ print 'Failed to create file ' . $filename . ' into dir ' . $dirname . '.' . "\n";
print 'Failed to create file '.$filename.' into dir '.$dirname.'.'."\n"; return - 1;
return -1;
} }
// Genere en-tete // Genere en-tete
@ -221,35 +181,30 @@ if ($resql)
$objmodel->write_title($array_fields, $array_selected, $outputlangs, $array_export_TypeFields); $objmodel->write_title($array_fields, $array_selected, $outputlangs, $array_export_TypeFields);
} }
$i=0; $i = 0;
while ($i < $numrows) while ($i < $numrows) {
{ $thirdparty = '';
$thirdparty=''; $accountelem = '';
$accountelem=''; $comment = '';
$comment='';
$objp = $db->fetch_object($resql); $objp = $db->fetch_object($resql);
// Calculate start balance // Calculate start balance
if (! isset($balancebefore[$objp->num_releve])) if (! isset($balancebefore[$objp->num_releve])) {
{ print 'Calculate start balance for receipt ' . $objp->num_releve . "\n";
print 'Calculate start balance for receipt '.$objp->num_releve."\n";
$sql2 = "SELECT sum(b.amount) as amount"; $sql2 = "SELECT sum(b.amount) as amount";
$sql2.= " FROM ".MAIN_DB_PREFIX."bank as b"; $sql2 .= " FROM " . MAIN_DB_PREFIX . "bank as b";
$sql2.= " WHERE b.num_releve < '".$db->escape($objp->num_releve)."'"; $sql2 .= " WHERE b.num_releve < '" . $db->escape($objp->num_releve) . "'";
$sql2.= " AND b.fk_account = ".$objp->bankid; $sql2 .= " AND b.fk_account = " . $objp->bankid;
$resql2=$db->query($sql2); $resql2 = $db->query($sql2);
if ($resql2) if ($resql2) {
{ $obj2 = $db->fetch_object($resql2);
$obj2=$db->fetch_object($resql2); $balancebefore[$objp->num_releve] = ($obj2->amount ? $obj2->amount : 0);
$balancebefore[$objp->num_releve] = ($obj2->amount?$obj2->amount:0);
$db->free($resql2); $db->free($resql2);
} } else {
else
{
dol_print_error($db); dol_print_error($db);
exit(-1); exit(- 1);
} }
$total = $balancebefore[$objp->num_releve]; $total = $balancebefore[$objp->num_releve];
@ -258,168 +213,153 @@ if ($resql)
$totalbefore = $total; $totalbefore = $total;
$total = $total + $objp->amount; $total = $total + $objp->amount;
// Date operation // Date operation
$dateop=$db->jdate($objp->do); $dateop = $db->jdate($objp->do);
// Date de valeur // Date de valeur
$datevalue=$db->jdate($objp->dv); $datevalue = $db->jdate($objp->dv);
// Num cheque // Num cheque
$numchq=($objp->num_chq?$objp->num_chq:''); $numchq = ($objp->num_chq ? $objp->num_chq : '');
// Libelle // Libelle
$reg=array(); $reg = array();
preg_match('/\((.+)\)/i', $objp->label, $reg); // Si texte entoure de parenthese on tente recherche de traduction preg_match('/\((.+)\)/i', $objp->label, $reg); // Si texte entoure de parenthese on tente recherche de traduction
if ($reg[1] && $langs->transnoentitiesnoconv($reg[1])!=$reg[1]) $description=$langs->transnoentitiesnoconv($reg[1]); if ($reg[1] && $langs->transnoentitiesnoconv($reg[1]) != $reg[1])
else $description=$objp->label; $description = $langs->transnoentitiesnoconv($reg[1]);
else
$description = $objp->label;
/* /*
* Ajout les liens (societe, company...) * Ajout les liens (societe, company...)
*/ */
$links = $acct->get_url($objp->rowid); $links = $acct->get_url($objp->rowid);
foreach($links as $key=>$val) foreach ($links as $key => $val) {
{ if ($links[$key]['type'] == 'payment') {
if ($links[$key]['type']=='payment')
{
$paymentstatic->fetch($links[$key]['url_id']); $paymentstatic->fetch($links[$key]['url_id']);
$tmparray=$paymentstatic->getBillsArray(''); $tmparray = $paymentstatic->getBillsArray('');
if (is_array($tmparray)) if (is_array($tmparray)) {
{ foreach ($tmparray as $key => $val) {
foreach($tmparray as $key => $val)
{
$invoicestatic->fetch($val); $invoicestatic->fetch($val);
if ($accountelem) $accountelem.= ', '; if ($accountelem)
$accountelem.=$invoicestatic->ref; $accountelem .= ', ';
$accountelem .= $invoicestatic->ref;
} }
} }
} } elseif ($links[$key]['type'] == 'payment_supplier') {
elseif ($links[$key]['type']=='payment_supplier')
{
$paymentsupplierstatic->fetch($links[$key]['url_id']); $paymentsupplierstatic->fetch($links[$key]['url_id']);
$tmparray=$paymentsupplierstatic->getBillsArray(''); $tmparray = $paymentsupplierstatic->getBillsArray('');
if (is_array($tmparray)) if (is_array($tmparray)) {
{ foreach ($tmparray as $key => $val) {
foreach($tmparray as $key => $val)
{
$invoicesupplierstatic->fetch($val); $invoicesupplierstatic->fetch($val);
if ($accountelem) $accountelem.= ', '; if ($accountelem)
$accountelem.=$invoicesupplierstatic->ref; $accountelem .= ', ';
$accountelem .= $invoicesupplierstatic->ref;
} }
} }
} } elseif ($links[$key]['type'] == 'payment_sc') {
elseif ($links[$key]['type']=='payment_sc')
{
$paymentsocialcontributionstatic->fetch($links[$key]['url_id']); $paymentsocialcontributionstatic->fetch($links[$key]['url_id']);
if ($accountelem) $accountelem.= ', '; if ($accountelem)
$accountelem.=$langs->transnoentitiesnoconv("SocialContribution").' '.$paymentsocialcontributionstatic->ref; $accountelem .= ', ';
} $accountelem .= $langs->transnoentitiesnoconv("SocialContribution") . ' ' . $paymentsocialcontributionstatic->ref;
elseif ($links[$key]['type']=='payment_vat') } elseif ($links[$key]['type'] == 'payment_vat') {
{
$paymentvatstatic->fetch($links[$key]['url_id']); $paymentvatstatic->fetch($links[$key]['url_id']);
if ($accountelem) $accountelem.= ', '; if ($accountelem)
$accountelem.=$langs->transnoentitiesnoconv("VATPayments").' '.$paymentvatstatic->ref; $accountelem .= ', ';
} $accountelem .= $langs->transnoentitiesnoconv("VATPayments") . ' ' . $paymentvatstatic->ref;
elseif ($links[$key]['type']=='banktransfert') } elseif ($links[$key]['type'] == 'banktransfert') {
{ $comment = $outputlangs->transnoentitiesnoconv("Transfer");
$comment=$outputlangs->transnoentitiesnoconv("Transfer"); if ($objp->amount > 0) {
if ($objp->amount > 0) if ($comment)
{ $comment .= ' ';
if ($comment) $comment.= ' ';
$banklinestatic->fetch($links[$key]['url_id']); $banklinestatic->fetch($links[$key]['url_id']);
$bankstatic->id=$banklinestatic->fk_account; $bankstatic->id = $banklinestatic->fk_account;
$bankstatic->label=$banklinestatic->bank_account_label; $bankstatic->label = $banklinestatic->bank_account_label;
$comment.= ' ('.$langs->transnoentitiesnoconv("from").' '; $comment .= ' (' . $langs->transnoentitiesnoconv("from") . ' ';
$comment.= $bankstatic->getNomUrl(1, 'transactions'); $comment .= $bankstatic->getNomUrl(1, 'transactions');
$comment.= ' '.$langs->transnoentitiesnoconv("toward").' '; $comment .= ' ' . $langs->transnoentitiesnoconv("toward") . ' ';
$bankstatic->id=$objp->bankid; $bankstatic->id = $objp->bankid;
$bankstatic->label=$objp->bankref; $bankstatic->label = $objp->bankref;
$comment.= $bankstatic->getNomUrl(1, ''); $comment .= $bankstatic->getNomUrl(1, '');
$comment.= ')'; $comment .= ')';
} } else {
else if ($comment)
{ $comment .= ' ';
if ($comment) $comment.= ' '; $bankstatic->id = $objp->bankid;
$bankstatic->id=$objp->bankid; $bankstatic->label = $objp->bankref;
$bankstatic->label=$objp->bankref; $comment .= ' (' . $langs->transnoentitiesnoconv("from") . ' ';
$comment.= ' ('.$langs->transnoentitiesnoconv("from").' '; $comment .= $bankstatic->getNomUrl(1, '');
$comment.= $bankstatic->getNomUrl(1, ''); $comment .= ' ' . $langs->transnoentitiesnoconv("toward") . ' ';
$comment.= ' '.$langs->transnoentitiesnoconv("toward").' ';
$banklinestatic->fetch($links[$key]['url_id']); $banklinestatic->fetch($links[$key]['url_id']);
$bankstatic->id=$banklinestatic->fk_account; $bankstatic->id = $banklinestatic->fk_account;
$bankstatic->label=$banklinestatic->bank_account_label; $bankstatic->label = $banklinestatic->bank_account_label;
$comment.= $bankstatic->getNomUrl(1, 'transactions'); $comment .= $bankstatic->getNomUrl(1, 'transactions');
$comment.= ')'; $comment .= ')';
} }
} elseif ($links[$key]['type'] == 'company') {
if ($thirdparty)
$thirdparty .= ', ';
$thirdparty .= dol_trunc($links[$key]['label'], 24);
$newline = 0;
} elseif ($links[$key]['type'] == 'member') {
if ($thirdparty)
$accountelem .= ', ';
$thirdparty .= $links[$key]['label'];
$newline = 0;
} }
elseif ($links[$key]['type']=='company') /*
{ * elseif ($links[$key]['type']=='sc')
if ($thirdparty) $thirdparty.= ', '; * {
$thirdparty.= dol_trunc($links[$key]['label'], 24); * if ($accountelem) $accountelem.= ', ';
$newline=0; * //$accountelem.= '<a href="'.DOL_URL_ROOT.'/compta/sociales/card.php?id='.$links[$key]['url_id'].'">';
} * //$accountelem.= img_object($langs->transnoentitiesnoconv('ShowBill'),'bill').' ';
elseif ($links[$key]['type']=='member') * $accountelem.= $langs->transnoentitiesnoconv("SocialContribution");
{ * //$accountelem.= '</a>';
if ($thirdparty) $accountelem.= ', '; * $newline=0;
$thirdparty.= $links[$key]['label']; * }
$newline=0; * else
} * {
/*elseif ($links[$key]['type']=='sc') * if ($accountelem) $accountelem.= ', ';
{ * //$accountelem.= '<a href="'.$links[$key]['url'].$links[$key]['url_id'].'">';
if ($accountelem) $accountelem.= ', '; * $accountelem.= $links[$key]['label'];
//$accountelem.= '<a href="'.DOL_URL_ROOT.'/compta/sociales/card.php?id='.$links[$key]['url_id'].'">'; * //$accountelem.= '</a>';
//$accountelem.= img_object($langs->transnoentitiesnoconv('ShowBill'),'bill').' '; * $newline=0;
$accountelem.= $langs->transnoentitiesnoconv("SocialContribution"); * }
//$accountelem.= '</a>'; */
$newline=0;
}
else
{
if ($accountelem) $accountelem.= ', ';
//$accountelem.= '<a href="'.$links[$key]['url'].$links[$key]['url_id'].'">';
$accountelem.= $links[$key]['label'];
//$accountelem.= '</a>';
$newline=0;
}*/
} }
$debit=$credit=''; $debit = $credit = '';
if ($objp->amount < 0) if ($objp->amount < 0) {
{
$totald = $totald + abs($objp->amount); $totald = $totald + abs($objp->amount);
$debit=price2num($objp->amount * -1); $debit = price2num($objp->amount * - 1);
} } else {
else
{
$totalc = $totalc + abs($objp->amount); $totalc = $totalc + abs($objp->amount);
$credit=price2num($objp->amount); $credit = price2num($objp->amount);
} }
$i++; $i ++;
$rec=new stdClass(); $rec = new stdClass();
$rec->bankreceipt=$objp->num_releve; $rec->bankreceipt = $objp->num_releve;
$rec->bankaccount=$objp->banklabel; $rec->bankaccount = $objp->banklabel;
$rec->dateop=dol_print_date($dateop, 'dayrfc'); $rec->dateop = dol_print_date($dateop, 'dayrfc');
$rec->dateval=dol_print_date($datevalue, 'dayrfc'); $rec->dateval = dol_print_date($datevalue, 'dayrfc');
$rec->type=$objp->fk_type.' '.($objp->num_chq?$objp->num_chq:''); $rec->type = $objp->fk_type . ' ' . ($objp->num_chq ? $objp->num_chq : '');
$rec->description=$description; $rec->description = $description;
$rec->thirdparty=$thirdparty; $rec->thirdparty = $thirdparty;
$rec->accountelem=$accountelem; $rec->accountelem = $accountelem;
$rec->debit=$debit; $rec->debit = $debit;
$rec->credit=$credit; $rec->credit = $credit;
$rec->comment=$comment; $rec->comment = $comment;
$rec->soldbefore=price2num($totalbefore); $rec->soldbefore = price2num($totalbefore);
$rec->soldafter=price2num($total); $rec->soldafter = price2num($total);
// end of special operation processing // end of special operation processing
$objmodel->write_record($array_selected, $rec, $outputlangs, $array_export_TypeFields); $objmodel->write_record($array_selected, $rec, $outputlangs, $array_export_TypeFields);
} }
if ($numrows > 0) if ($numrows > 0) {
{ print "Found " . $numrows . " records for receipt " . $num . "\n";
print "Found ".$numrows." records for receipt ".$num."\n";
// Genere en-tete // Genere en-tete
$objmodel->write_footer($outputlangs); $objmodel->write_footer($outputlangs);
@ -427,21 +367,17 @@ if ($resql)
// Close file // Close file
$objmodel->close_file(); $objmodel->close_file();
print 'File '.$filename.' was generated into dir '.$dirname.'.'."\n"; print 'File ' . $filename . ' was generated into dir ' . $dirname . '.' . "\n";
$ret=0; $ret = 0;
} } else {
else print "No records found for receipt " . $num . "\n";
{
print "No records found for receipt ".$num."\n";
$ret=0; $ret = 0;
} }
} } else {
else
{
dol_print_error($db); dol_print_error($db);
$ret=-1; $ret = - 1;
} }
$db->close(); $db->close();

View File

@ -1,8 +1,8 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/* /*
* Copyright (C) 2004 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2009-2013 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2009-2013 Laurent Destailleur <eldy@users.sourceforge.net>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -11,7 +11,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -19,52 +19,49 @@
*/ */
/** /**
* \file scripts/company/export-contacts-xls-example.php * \file scripts/company/export-contacts-xls-example.php
* \ingroup company * \ingroup company
* \brief Script file to export contacts into an Excel file * \brief Script file to export contacts into an Excel file
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
if (! isset($argv[1]) || ! $argv[1]) { if (! isset($argv[1]) || ! $argv[1]) {
print "Usage: $script_file now\n"; print "Usage: $script_file now\n";
exit(-1); exit(- 1);
} }
$now=$argv[1]; $now = $argv[1];
require_once $path . "../../htdocs/master.inc.php";
// require_once PHP_WRITEEXCEL_PATH."/class.writeexcel_workbook.inc.php";
// require_once PHP_WRITEEXCEL_PATH."/class.writeexcel_worksheet.inc.php";
require_once $path."../../htdocs/master.inc.php"; require_once PHPEXCEL_PATH . "/PHPExcel.php";
//require_once PHP_WRITEEXCEL_PATH."/class.writeexcel_workbook.inc.php"; // require_once PHPEXCEL_PATH."/PHPExcel/Writer/Excel2007.php";
//require_once PHP_WRITEEXCEL_PATH."/class.writeexcel_worksheet.inc.php"; require_once PHPEXCEL_PATH . "/PHPExcel/Writer/Excel5.php";
require_once PHPEXCEL_PATH."/PHPExcel.php";
//require_once PHPEXCEL_PATH."/PHPExcel/Writer/Excel2007.php";
require_once PHPEXCEL_PATH."/PHPExcel/Writer/Excel5.php";
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
$fname = DOL_DATA_ROOT.'/export-contacts.xls'; $fname = DOL_DATA_ROOT . '/export-contacts.xls';
//$objPHPExcel = new writeexcel_workbook($fname); // $objPHPExcel = new writeexcel_workbook($fname);
$objPHPExcel = new PHPExcel(); $objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("Dolibarr script"); $objPHPExcel->getProperties()->setCreator("Dolibarr script");
$objPHPExcel->getProperties()->setLastModifiedBy("Dolibarr script"); $objPHPExcel->getProperties()->setLastModifiedBy("Dolibarr script");
@ -72,23 +69,21 @@ $objPHPExcel->getProperties()->setTitle("Test Document");
$objPHPExcel->getProperties()->setSubject("Test Document"); $objPHPExcel->getProperties()->setSubject("Test Document");
$objPHPExcel->getProperties()->setDescription("Test document, generated using PHP classes."); $objPHPExcel->getProperties()->setDescription("Test document, generated using PHP classes.");
// $page = &$objPHPExcel->addworksheet('Export Dolibarr');
//$page = &$objPHPExcel->addworksheet('Export Dolibarr');
$objPHPExcel->setActiveSheetIndex(0); $objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setTitle('Contacts'); $objPHPExcel->getActiveSheet()->setTitle('Contacts');
//$page->set_column(0,4,18); // A // $page->set_column(0,4,18); // A
$sql = "SELECT distinct c.lastname, c.firstname, c.email, s.nom as name"; $sql = "SELECT distinct c.lastname, c.firstname, c.email, s.nom as name";
$sql.= " FROM ".MAIN_DB_PREFIX."socpeople as c"; $sql .= " FROM " . MAIN_DB_PREFIX . "socpeople as c";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = c.fk_soc"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as s on s.rowid = c.fk_soc";
$resql=$db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
print "Lines ".$num."\n"; print "Lines " . $num . "\n";
$i = 0; $i = 0;
$j = 1; $j = 1;
@ -98,27 +93,25 @@ if ($resql)
$objPHPExcel->getActiveSheet()->SetCellValue('C1', $langs->trans("Email")); $objPHPExcel->getActiveSheet()->SetCellValue('C1', $langs->trans("Email"));
$objPHPExcel->getActiveSheet()->SetCellValue('D1', $langs->trans("ThirdPart")); $objPHPExcel->getActiveSheet()->SetCellValue('D1', $langs->trans("ThirdPart"));
while ($i < $num) while ($i < $num) {
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$objPHPExcel->getActiveSheet()->SetCellValue('A'.($i+2), $obj->firstname); $objPHPExcel->getActiveSheet()->SetCellValue('A' . ($i + 2), $obj->firstname);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.($i+2), $obj->lastname); $objPHPExcel->getActiveSheet()->SetCellValue('B' . ($i + 2), $obj->lastname);
$objPHPExcel->getActiveSheet()->SetCellValue('C'.($i+2), $obj->email); $objPHPExcel->getActiveSheet()->SetCellValue('C' . ($i + 2), $obj->email);
$objPHPExcel->getActiveSheet()->SetCellValue('D'.($i+2), $obj->name); $objPHPExcel->getActiveSheet()->SetCellValue('D' . ($i + 2), $obj->name);
$j++; $j ++;
$i++; $i ++;
} }
} }
// $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
//$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel); $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
$objWriter->save($fname); $objWriter->save($fname);
//$objPHPExcel->close(); // $objPHPExcel->close();
print 'File '.$fname.' was generated.'."\n"; print 'File ' . $fname . ' was generated.' . "\n";
exit(0); exit(0);

View File

@ -1,8 +1,8 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/* /*
* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2006-2009 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2006-2009 Laurent Destailleur <eldy@users.sourceforge.net>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -11,7 +11,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -19,74 +19,70 @@
*/ */
/** /**
* \file scripts/company/sync_contacts_dolibarr2ldap.php * \file scripts/company/sync_contacts_dolibarr2ldap.php
* \ingroup ldap company * \ingroup ldap company
* \brief Script to update all contacts from Dolibarr into a LDAP database * \brief Script to update all contacts from Dolibarr into a LDAP database
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
require_once $path . "../../htdocs/master.inc.php";
require_once $path."../../htdocs/master.inc.php"; require_once DOL_DOCUMENT_ROOT . "/contact/class/contact.class.php";
require_once DOL_DOCUMENT_ROOT."/contact/class/contact.class.php"; require_once DOL_DOCUMENT_ROOT . "/user/class/user.class.php";
require_once DOL_DOCUMENT_ROOT."/user/class/user.class.php"; require_once DOL_DOCUMENT_ROOT . "/core/class/ldap.class.php";
require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php";
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
$confirmed=0; $confirmed = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
if (! isset($argv[1]) || ! $argv[1]) { if (! isset($argv[1]) || ! $argv[1]) {
print "Usage: $script_file now [-y]\n"; print "Usage: $script_file now [-y]\n";
exit(-1); exit(- 1);
} }
foreach($argv as $key => $val) foreach ($argv as $key => $val) {
{ if (preg_match('/-y$/', $val, $reg))
if (preg_match('/-y$/', $val, $reg)) $confirmed=1; $confirmed = 1;
} }
$now=$argv[1]; $now = $argv[1];
print "Mails sending disabled (useless in batch mode)\n"; print "Mails sending disabled (useless in batch mode)\n";
$conf->global->MAIN_DISABLE_ALL_MAILS=1; // On bloque les mails $conf->global->MAIN_DISABLE_ALL_MAILS = 1; // On bloque les mails
print "\n"; print "\n";
print "----- Synchronize all records from Dolibarr database:\n"; print "----- Synchronize all records from Dolibarr database:\n";
print "type=".$conf->db->type."\n"; print "type=" . $conf->db->type . "\n";
print "host=".$conf->db->host."\n"; print "host=" . $conf->db->host . "\n";
print "port=".$conf->db->port."\n"; print "port=" . $conf->db->port . "\n";
print "login=".$conf->db->user."\n"; print "login=" . $conf->db->user . "\n";
//print "pass=".preg_replace('/./i','*',$conf->db->password)."\n"; // Not defined for security reasons // print "pass=".preg_replace('/./i','*',$conf->db->password)."\n"; // Not defined for security reasons
print "database=".$conf->db->name."\n"; print "database=" . $conf->db->name . "\n";
print "\n"; print "\n";
print "----- To LDAP database:\n"; print "----- To LDAP database:\n";
print "host=".$conf->global->LDAP_SERVER_HOST."\n"; print "host=" . $conf->global->LDAP_SERVER_HOST . "\n";
print "port=".$conf->global->LDAP_SERVER_PORT."\n"; print "port=" . $conf->global->LDAP_SERVER_PORT . "\n";
print "login=".$conf->global->LDAP_ADMIN_DN."\n"; print "login=" . $conf->global->LDAP_ADMIN_DN . "\n";
print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n"; print "pass=" . preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS) . "\n";
print "DN target=".$conf->global->LDAP_CONTACT_DN."\n"; print "DN target=" . $conf->global->LDAP_CONTACT_DN . "\n";
print "\n"; print "\n";
if (! $confirmed) if (! $confirmed) {
{
print "Press a key to confirm...\n"; print "Press a key to confirm...\n";
$input = trim(fgets(STDIN)); $input = trim(fgets(STDIN));
print "Warning, this operation may result in data loss if it failed.\n"; print "Warning, this operation may result in data loss if it failed.\n";
@ -96,28 +92,26 @@ if (! $confirmed)
} }
/* /*
if (! $conf->global->LDAP_CONTACT_ACTIVE) * if (! $conf->global->LDAP_CONTACT_ACTIVE)
{ * {
print $langs->trans("LDAPSynchronizationNotSetupInDolibarr"); * print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
exit(-1); * exit(-1);
} * }
*/ */
$sql = "SELECT rowid"; $sql = "SELECT rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."socpeople"; $sql .= " FROM " . MAIN_DB_PREFIX . "socpeople";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
$ldap=new Ldap(); $ldap = new Ldap();
$ldap->connect_bind(); $ldap->connect_bind();
while ($i < $num) while ($i < $num) {
{ $ldap->error = "";
$ldap->error="";
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
@ -125,37 +119,32 @@ if ($resql)
$contact->id = $obj->rowid; $contact->id = $obj->rowid;
$contact->fetch($contact->id); $contact->fetch($contact->id);
print $langs->trans("UpdateContact")." rowid=".$contact->id." ".$contact->getFullName($langs); print $langs->trans("UpdateContact") . " rowid=" . $contact->id . " " . $contact->getFullName($langs);
$oldobject=$contact; $oldobject = $contact;
$oldinfo=$oldobject->_load_ldap_info(); $oldinfo = $oldobject->_load_ldap_info();
$olddn=$oldobject->_load_ldap_dn($oldinfo); $olddn = $oldobject->_load_ldap_dn($oldinfo);
$info=$contact->_load_ldap_info(); $info = $contact->_load_ldap_info();
$dn=$contact->_load_ldap_dn($info); $dn = $contact->_load_ldap_dn($info);
$result=$ldap->add($dn, $info, $user); // Wil fail if already exists $result = $ldap->add($dn, $info, $user); // Wil fail if already exists
$result=$ldap->update($dn, $info, $user, $olddn); $result = $ldap->update($dn, $info, $user, $olddn);
if ($result > 0) if ($result > 0) {
{ print " - " . $langs->trans("OK");
print " - ".$langs->trans("OK"); } else {
} $error ++;
else print " - " . $langs->trans("KO") . ' - ' . $ldap->error;
{
$error++;
print " - ".$langs->trans("KO").' - '.$ldap->error;
} }
print "\n"; print "\n";
$i++; $i ++;
} }
$ldap->unbind(); $ldap->unbind();
$ldap->close(); $ldap->close();
} } else {
else
{
dol_print_error($db); dol_print_error($db);
} }

View File

@ -1,9 +1,9 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/* /*
* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2013 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2013 Juanjo Menent <jmenent@2byte.es>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -12,7 +12,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -20,297 +20,283 @@
*/ */
/** /**
* \file scripts/contracts/email_expire_services_to_customers.php * \file scripts/contracts/email_expire_services_to_customers.php
* \ingroup facture * \ingroup facture
* \brief Script to send a mail to customers with services to expire * \brief Script to send a mail to customers with services to expire
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test si mode batch // Test si mode batch
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
if (! isset($argv[1]) || ! $argv[1] || ! in_array($argv[1], array('test','confirm')) || ! in_array($argv[2], array('thirdparties','contacts'))) if (! isset($argv[1]) || ! $argv[1] || ! in_array($argv[1], array('test','confirm')) || ! in_array($argv[2], array('thirdparties','contacts'))) {
{
print "Usage: $script_file (test|confirm) (thirdparties|contacts) [delay] [after]\n"; print "Usage: $script_file (test|confirm) (thirdparties|contacts) [delay] [after]\n";
print "\n"; print "\n";
print "Send an email to customers to remind all contracts services to expire or expired.\n"; print "Send an email to customers to remind all contracts services to expire or expired.\n";
print "If you choose 'test' mode, no emails are sent.\n"; print "If you choose 'test' mode, no emails are sent.\n";
print "If you add param delay (nb of days), only services with expired date < today + delay are included.\n"; print "If you add param delay (nb of days), only services with expired date < today + delay are included.\n";
print "If you add param after (nb of days), only services with expired date >= today + delay are included.\n"; print "If you add param after (nb of days), only services with expired date >= today + delay are included.\n";
exit(-1); exit(- 1);
} }
$mode=$argv[1]; $mode = $argv[1];
$targettype=$argv[2]; $targettype = $argv[2];
require $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT . "/core/class/CMailFile.class.php";
require $path."../../htdocs/master.inc.php"; $langs->loadLangs(array('main','contracts'));
require_once DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php";
$langs->loadLangs(array('main', 'contracts'));
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
$now=dol_now('tzserver'); $now = dol_now('tzserver');
$duration_value=isset($argv[3])?$argv[3]:'none'; $duration_value = isset($argv[3]) ? $argv[3] : 'none';
$duration_value2=isset($argv[4])?$argv[4]:'none'; $duration_value2 = isset($argv[4]) ? $argv[4] : 'none';
$error = 0; $error = 0;
print $script_file." launched with mode ".$mode." default lang=".$langs->defaultlang.(is_numeric($duration_value)?" delay=".$duration_value:"").(is_numeric($duration_value2)?" after=".$duration_value2:"")."\n"; print $script_file . " launched with mode " . $mode . " default lang=" . $langs->defaultlang . (is_numeric($duration_value) ? " delay=" . $duration_value : "") . (is_numeric($duration_value2) ? " after=" . $duration_value2 : "") . "\n";
if ($mode != 'confirm') $conf->global->MAIN_DISABLE_ALL_MAILS=1; if ($mode != 'confirm')
$conf->global->MAIN_DISABLE_ALL_MAILS = 1;
$sql = "SELECT c.ref, cd.date_fin_validite, cd.total_ttc, cd.description as description, p.label as plabel,"; $sql = "SELECT c.ref, cd.date_fin_validite, cd.total_ttc, cd.description as description, p.label as plabel,";
$sql.= " s.rowid as sid, s.nom as name, s.email, s.default_lang"; $sql .= " s.rowid as sid, s.nom as name, s.email, s.default_lang";
if ($targettype == 'contacts') $sql.= ", sp.rowid as cid, sp.firstname as cfirstname, sp.lastname as clastname, sp.email as cemail"; if ($targettype == 'contacts')
$sql .= " FROM ".MAIN_DB_PREFIX."societe AS s"; $sql .= ", sp.rowid as cid, sp.firstname as cfirstname, sp.lastname as clastname, sp.email as cemail";
if ($targettype == 'contacts') $sql.= ", ".MAIN_DB_PREFIX."socpeople as sp"; $sql .= " FROM " . MAIN_DB_PREFIX . "societe AS s";
$sql .= ", ".MAIN_DB_PREFIX."contrat AS c"; if ($targettype == 'contacts')
$sql .= ", ".MAIN_DB_PREFIX."contratdet AS cd"; $sql .= ", " . MAIN_DB_PREFIX . "socpeople as sp";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product AS p ON p.rowid = cd.fk_product"; $sql .= ", " . MAIN_DB_PREFIX . "contrat AS c";
$sql .= ", " . MAIN_DB_PREFIX . "contratdet AS cd";
$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product AS p ON p.rowid = cd.fk_product";
$sql .= " WHERE s.rowid = c.fk_soc AND c.rowid = cd.fk_contrat AND c.statut > 0 AND cd.statut < 5"; $sql .= " WHERE s.rowid = c.fk_soc AND c.rowid = cd.fk_contrat AND c.statut > 0 AND cd.statut < 5";
if (is_numeric($duration_value2)) $sql.= " AND cd.date_fin_validite >= '".$db->idate(dol_time_plus_duree($now, $duration_value2, "d"))."'"; if (is_numeric($duration_value2))
if (is_numeric($duration_value)) $sql.= " AND cd.date_fin_validite < '".$db->idate(dol_time_plus_duree($now, $duration_value, "d"))."'"; $sql .= " AND cd.date_fin_validite >= '" . $db->idate(dol_time_plus_duree($now, $duration_value2, "d")) . "'";
if ($targettype == 'contacts') $sql.= " AND s.rowid = sp.fk_soc"; if (is_numeric($duration_value))
$sql.= " ORDER BY"; $sql .= " AND cd.date_fin_validite < '" . $db->idate(dol_time_plus_duree($now, $duration_value, "d")) . "'";
if ($targettype == 'contacts') $sql.= " sp.email, sp.rowid,"; if ($targettype == 'contacts')
$sql.= " s.email ASC, s.rowid ASC, cd.date_fin_validite ASC"; // Order by email to allow one message per email $sql .= " AND s.rowid = sp.fk_soc";
$sql .= " ORDER BY";
if ($targettype == 'contacts')
$sql .= " sp.email, sp.rowid,";
$sql .= " s.email ASC, s.rowid ASC, cd.date_fin_validite ASC"; // Order by email to allow one message per email
//print $sql; // print $sql;
$resql=$db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{ $num = $db->num_rows($resql);
$num = $db->num_rows($resql); $i = 0;
$i = 0; $oldemail = 'none';
$oldemail = 'none'; $oldsid = 0; $oldcid = 0; $oldlang=''; $oldsid = 0;
$total = 0; $foundtoprocess = 0; $oldcid = 0;
$trackthirdpartiessent = array(); $oldlang = '';
$total = 0;
$foundtoprocess = 0;
$trackthirdpartiessent = array();
print "We found ".$num." couples (services to expire-".$targettype.") qualified\n"; print "We found " . $num . " couples (services to expire-" . $targettype . ") qualified\n";
dol_syslog("We found ".$num." couples (services to expire-".$targettype.") qualified"); dol_syslog("We found " . $num . " couples (services to expire-" . $targettype . ") qualified");
$message=''; $message = '';
if ($num) if ($num) {
{ while ($i < $num) {
while ($i < $num) $obj = $db->fetch_object($resql);
{
$obj = $db->fetch_object($resql);
$newemail=empty($obj->cemail)?$obj->email:$obj->cemail; $newemail = empty($obj->cemail) ? $obj->email : $obj->cemail;
// Check if this record is a break after previous one // Check if this record is a break after previous one
$startbreak=false; $startbreak = false;
if ($newemail <> $oldemail || $oldemail == 'none') $startbreak=true; if ($newemail != $oldemail || $oldemail == 'none')
if ($obj->sid && $obj->sid <> $oldsid) $startbreak=true; $startbreak = true;
if ($obj->cid && $obj->cid <> $oldcid) $startbreak=true; if ($obj->sid && $obj->sid != $oldsid)
$startbreak = true;
if ($obj->cid && $obj->cid != $oldcid)
$startbreak = true;
if ($startbreak) if ($startbreak) {
{ // Break onto sales representative (new email or cid)
// Break onto sales representative (new email or cid) if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid . '|' . $oldemail])) {
if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget, $duration_value);
{ $trackthirdpartiessent[$oldsid . '|' . $oldemail] = 'contact id ' . $oldcid;
envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget, $duration_value); } else {
$trackthirdpartiessent[$oldsid.'|'.$oldemail]='contact id '.$oldcid; if ($oldemail != 'none') {
} if (empty($trackthirdpartiessent[$oldsid . '|' . $oldemail]))
else print "- No email sent for '" . $oldtarget . "', total: " . $total . "\n";
{ else
if ($oldemail != 'none') print "- No email sent for '" . $oldtarget . "', total: " . $total . " (already sent to " . $trackthirdpartiessent[$oldsid . '|' . $oldemail] . ")\n";
{ }
if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) print "- No email sent for '".$oldtarget."', total: ".$total."\n"; }
else print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n"; $oldemail = $newemail;
} $oldsid = $obj->sid;
} $oldcid = $obj->cid;
$oldemail = $newemail; $oldlang = $obj->lang;
$oldsid = $obj->sid; $oldtarget = (empty($obj->cfirstname) && empty($obj->clastname)) ? $obj->name : ($obj->clastname . " " . $obj->cfirstname);
$oldcid = $obj->cid; $message = '';
$oldlang = $obj->lang; $total = 0;
$oldtarget=(empty($obj->cfirstname) && empty($obj->clastname))?$obj->name:($obj->clastname." ".$obj->cfirstname); $foundtoprocess = 0;
$message = ''; $target = (empty($obj->cfirstname) && empty($obj->clastname)) ? $obj->name : ($obj->clastname . " " . $obj->cfirstname);
$total = 0; // if (empty($newemail)) print "Warning: Customer ".$target." has no email. Notice disabled.\n";
$foundtoprocess = 0; }
$target=(empty($obj->cfirstname) && empty($obj->clastname))?$obj->name:($obj->clastname." ".$obj->cfirstname);
//if (empty($newemail)) print "Warning: Customer ".$target." has no email. Notice disabled.\n";
}
// Define line content // Define line content
$outputlangs=new Translate('', $conf); $outputlangs = new Translate('', $conf);
$outputlangs->setDefaultLang(empty($obj->default_lang)?$langs->defaultlang:$obj->default_lang); // By default language of customer $outputlangs->setDefaultLang(empty($obj->default_lang) ? $langs->defaultlang : $obj->default_lang); // By default language of customer
// Load translation files required by the page // Load translation files required by the page
$outputlangs->loadLangs(array("main", "contracts", "bills", "products")); $outputlangs->loadLangs(array("main","contracts","bills","products"));
if (dol_strlen($newemail)) if (dol_strlen($newemail)) {
{ $message .= $outputlangs->trans("Contract") . " " . $obj->ref . ": " . $outputlangs->trans("Service") . " " . dol_concatdesc($obj->plabel, $obj->description) . " (" . price($obj->total_ttc, 0, $outputlangs, 0, 0, - 1, $conf->currency) . "), " . $outputlangs->trans("DateEndPlannedShort") . " " . dol_print_date($db->jdate($obj->date_fin_validite), 'day') . "\n\n";
$message .= $outputlangs->trans("Contract")." ".$obj->ref.": ".$outputlangs->trans("Service")." ".dol_concatdesc($obj->plabel, $obj->description)." (".price($obj->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency)."), ".$outputlangs->trans("DateEndPlannedShort")." ".dol_print_date($db->jdate($obj->date_fin_validite), 'day')."\n\n"; dol_syslog("email_expire_services_to_customers.php: " . $newemail . " " . $message);
dol_syslog("email_expire_services_to_customers.php: ".$newemail." ".$message); $foundtoprocess ++;
$foundtoprocess++; }
} print "Service to expire " . $obj->ref . ", label " . dol_concatdesc($obj->plabel, $obj->description) . ", due date " . dol_print_date($db->jdate($obj->date_fin_validite), 'day') . ", customer id " . $obj->sid . " " . $obj->name . ", " . ($obj->cid ? "contact id " . $obj->cid . " " . $obj->clastname . " " . $obj->cfirstname . ", " : "") . "email " . $newemail . ", lang " . $outputlangs->defaultlang . ": ";
print "Service to expire ".$obj->ref.", label ".dol_concatdesc($obj->plabel, $obj->description).", due date ".dol_print_date($db->jdate($obj->date_fin_validite), 'day').", customer id ".$obj->sid." ".$obj->name.", ".($obj->cid?"contact id ".$obj->cid." ".$obj->clastname." ".$obj->cfirstname.", ":"")."email ".$newemail.", lang ".$outputlangs->defaultlang.": "; if (dol_strlen($newemail))
if (dol_strlen($newemail)) print "qualified."; print "qualified.";
else print "disqualified (no email)."; else
print "disqualified (no email).";
print "\n"; print "\n";
unset($outputlangs); unset($outputlangs);
$total += $obj->total_ttc; $total += $obj->total_ttc;
$i++; $i ++;
} }
// Si il reste des envois en buffer // Si il reste des envois en buffer
if ($foundtoprocess) if ($foundtoprocess) {
{ if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid . '|' . $oldemail])) // Break onto email (new email)
if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) // Break onto email (new email)
{
envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget, $duration_value);
$trackthirdpartiessent[$oldsid.'|'.$oldemail]='contact id '.$oldcid;
}
else
{ {
if ($oldemail != 'none') envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget, $duration_value);
{ $trackthirdpartiessent[$oldsid . '|' . $oldemail] = 'contact id ' . $oldcid;
if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) print "- No email sent for '".$oldtarget."', total: ".$total."\n"; } else {
else print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n"; if ($oldemail != 'none') {
} if (empty($trackthirdpartiessent[$oldsid . '|' . $oldemail]))
} print "- No email sent for '" . $oldtarget . "', total: " . $total . "\n";
} else
} print "- No email sent for '" . $oldtarget . "', total: " . $total . " (already sent to " . $trackthirdpartiessent[$oldsid . '|' . $oldemail] . ")\n";
else }
{ }
print "No services to expire found\n"; }
} } else {
print "No services to expire found\n";
}
exit(0); exit(0);
} else {
dol_print_error($db);
dol_syslog("email_expire_services_to_customers.php: Error");
exit(- 1);
} }
else
{
dol_print_error($db);
dol_syslog("email_expire_services_to_customers.php: Error");
exit(-1);
}
/** /**
* Send email * Send email
* *
* @param string $mode Mode (test | confirm) * @param string $mode
* @param string $oldemail Target email * Mode (test | confirm)
* @param string $message Message to send * @param string $oldemail
* @param string $total Total amount of unpayed invoices * Target email
* @param string $userlang Code lang to use for email output. * @param string $message
* @param string $oldtarget Target name * Message to send
* @param int $duration_value duration value * @param string $total
* @return int <0 if KO, >0 if OK * Total amount of unpayed invoices
* @param string $userlang
* Code lang to use for email output.
* @param string $oldtarget
* Target name
* @param int $duration_value
* duration value
* @return int <0 if KO, >0 if OK
*/ */
function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget, $duration_value) function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget, $duration_value)
{ {
global $conf,$langs; global $conf, $langs;
if (getenv('DOL_FORCE_EMAIL_TO')) $oldemail=getenv('DOL_FORCE_EMAIL_TO'); if (getenv('DOL_FORCE_EMAIL_TO'))
$oldemail = getenv('DOL_FORCE_EMAIL_TO');
$newlangs=new Translate('', $conf); $newlangs = new Translate('', $conf);
$newlangs->setDefaultLang(empty($userlang)?(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT):$userlang); $newlangs->setDefaultLang(empty($userlang) ? (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT) : $userlang);
$newlangs->load("main"); $newlangs->load("main");
$newlangs->load("contracts"); $newlangs->load("contracts");
if ($duration_value) if ($duration_value) {
{ if ($duration_value > 0)
if ($duration_value > 0) $title=$newlangs->transnoentities("ListOfServicesToExpireWithDuration", $duration_value); $title = $newlangs->transnoentities("ListOfServicesToExpireWithDuration", $duration_value);
else $title=$newlangs->transnoentities("ListOfServicesToExpireWithDurationNeg", $duration_value); else
} $title = $newlangs->transnoentities("ListOfServicesToExpireWithDurationNeg", $duration_value);
else } else
$title= $newlangs->transnoentities("ListOfServicesToExpire"); $title = $newlangs->transnoentities("ListOfServicesToExpire");
$subject = (empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT)?$title:$conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT); $subject = (empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT) ? $title : $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT);
$sendto = $oldemail; $sendto = $oldemail;
$from = $conf->global->MAIN_MAIL_EMAIL_FROM; $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
$errorsto = $conf->global->MAIN_MAIL_ERRORS_TO; $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
$msgishtml = -1; $msgishtml = - 1;
print "- Send email to '".$oldtarget."' (".$oldemail."), total: ".$total."\n"; print "- Send email to '" . $oldtarget . "' (" . $oldemail . "), total: " . $total . "\n";
dol_syslog("email_expire_services_to_customers.php: send mail to ".$oldemail); dol_syslog("email_expire_services_to_customers.php: send mail to " . $oldemail);
$usehtml=0; $usehtml = 0;
if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) $usehtml+=1; if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER))
if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER)) $usehtml+=1; $usehtml += 1;
if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER))
$usehtml += 1;
$allmessage=''; $allmessage = '';
if (! empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER)) if (! empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER)) {
{ $allmessage .= $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER;
$allmessage.=$conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER; } else {
} $allmessage .= "Dear customer" . ($usehtml ? "<br>\n" : "\n") . ($usehtml ? "<br>\n" : "\n");
else $allmessage .= "Please, find a summary of the services contracted by you that are about to expire." . ($usehtml ? "<br>\n" : "\n") . ($usehtml ? "<br>\n" : "\n");
{ }
$allmessage.= "Dear customer".($usehtml?"<br>\n":"\n").($usehtml?"<br>\n":"\n"); $allmessage .= $message . ($usehtml ? "<br>\n" : "\n");
$allmessage.= "Please, find a summary of the services contracted by you that are about to expire.".($usehtml?"<br>\n":"\n").($usehtml?"<br>\n":"\n"); // $allmessage.= $langs->trans("Total")." = ".price($total,0,$userlang,0,0,-1,$conf->currency).($usehtml?"<br>\n":"\n");
} if (! empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) {
$allmessage.= $message.($usehtml?"<br>\n":"\n"); $allmessage .= $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER;
//$allmessage.= $langs->trans("Total")." = ".price($total,0,$userlang,0,0,-1,$conf->currency).($usehtml?"<br>\n":"\n"); if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER))
if (! empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) $usehtml += 1;
{ }
$allmessage.=$conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER;
if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) $usehtml+=1;
}
$mail = new CMailFile( $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
$subject,
$sendto,
$from,
$allmessage,
array(),
array(),
array(),
'',
'',
0,
$msgishtml
);
$mail->errors_to = $errorsto; $mail->errors_to = $errorsto;
// Send or not email // Send or not email
if ($mode == 'confirm') if ($mode == 'confirm') {
{ $result = $mail->sendfile();
$result=$mail->sendfile(); if (! $result) {
if (! $result) print "Error sending email " . $mail->error . "\n";
{ dol_syslog("Error sending email " . $mail->error . "\n");
print "Error sending email ".$mail->error."\n"; }
dol_syslog("Error sending email ".$mail->error."\n"); } else {
} print "No email sent (test mode)\n";
} dol_syslog("No email sent (test mode)");
else $mail->dump_mail();
{ $result = 1;
print "No email sent (test mode)\n"; }
dol_syslog("No email sent (test mode)");
$mail->dump_mail();
$result=1;
}
unset($newlangs); unset($newlangs);
if ($result) if ($result) {
{ return 1;
return 1; } else {
} return - 1;
else }
{
return -1;
}
} }

View File

@ -1,9 +1,9 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/* /*
* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2013 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2013 Juanjo Menent <jmenent@2byte.es>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -12,7 +12,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -20,263 +20,241 @@
*/ */
/** /**
* \file scripts/contracts/email_expire_services_to_representatives.php * \file scripts/contracts/email_expire_services_to_representatives.php
* \ingroup contracts * \ingroup contracts
* \brief Script to send a mail to dolibarr users linked to companies with services to expire * \brief Script to send a mail to dolibarr users linked to companies with services to expire
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test si mode batch // Test si mode batch
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
if (! isset($argv[1]) || ! $argv[1] || ! in_array($argv[1], array('test','confirm'))) if (! isset($argv[1]) || ! $argv[1] || ! in_array($argv[1], array('test','confirm'))) {
{
print "Usage: $script_file (test|confirm) [delay]\n"; print "Usage: $script_file (test|confirm) [delay]\n";
print "\n"; print "\n";
print "Send an email to remind all contracts services to expire, to users that are sale representative for.\n"; print "Send an email to remind all contracts services to expire, to users that are sale representative for.\n";
print "If you choose 'test' mode, no emails are sent.\n"; print "If you choose 'test' mode, no emails are sent.\n";
print "If you add a delay (nb of days), only services with expired date < today + delay are included.\n"; print "If you add a delay (nb of days), only services with expired date < today + delay are included.\n";
exit(-1); exit(- 1);
} }
$mode=$argv[1]; $mode = $argv[1];
require $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT . "/core/class/CMailFile.class.php";
require $path."../../htdocs/master.inc.php"; $langs->loadLangs(array('main','contracts'));
require_once DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php";
$langs->loadLangs(array('main', 'contracts'));
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
$now=dol_now('tzserver'); $now = dol_now('tzserver');
$duration_value=isset($argv[2])?$argv[2]:'none'; $duration_value = isset($argv[2]) ? $argv[2] : 'none';
print $script_file." launched with mode ".$mode." default lang=".$langs->defaultlang.(is_numeric($duration_value)?" delay=".$duration_value:"")."\n"; print $script_file . " launched with mode " . $mode . " default lang=" . $langs->defaultlang . (is_numeric($duration_value) ? " delay=" . $duration_value : "") . "\n";
if ($mode != 'confirm') $conf->global->MAIN_DISABLE_ALL_MAILS=1; if ($mode != 'confirm')
$conf->global->MAIN_DISABLE_ALL_MAILS = 1;
$sql = "SELECT DISTINCT c.ref, c.fk_soc, cd.date_fin_validite, cd.total_ttc, cd.description as description, p.label as plabel, s.rowid, s.nom as name, s.email, s.default_lang,"; $sql = "SELECT DISTINCT c.ref, c.fk_soc, cd.date_fin_validite, cd.total_ttc, cd.description as description, p.label as plabel, s.rowid, s.nom as name, s.email, s.default_lang,";
$sql.= " u.rowid as uid, u.lastname, u.firstname, u.email, u.lang"; $sql .= " u.rowid as uid, u.lastname, u.firstname, u.email, u.lang";
$sql.= " FROM ".MAIN_DB_PREFIX."societe AS s, ".MAIN_DB_PREFIX."contrat AS c, ".MAIN_DB_PREFIX."contratdet AS cd"; $sql .= " FROM " . MAIN_DB_PREFIX . "societe AS s, " . MAIN_DB_PREFIX . "contrat AS c, " . MAIN_DB_PREFIX . "contratdet AS cd";
$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product AS p ON p.rowid = cd.fk_product, ".MAIN_DB_PREFIX."societe_commerciaux AS sc, ".MAIN_DB_PREFIX."user AS u"; $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product AS p ON p.rowid = cd.fk_product, " . MAIN_DB_PREFIX . "societe_commerciaux AS sc, " . MAIN_DB_PREFIX . "user AS u";
$sql.= " WHERE s.rowid = c.fk_soc AND c.rowid = cd.fk_contrat AND c.statut > 0 AND cd.statut<5"; $sql .= " WHERE s.rowid = c.fk_soc AND c.rowid = cd.fk_contrat AND c.statut > 0 AND cd.statut<5";
if (is_numeric($duration_value)) $sql .= " AND cd.date_fin_validite < '".$db->idate(dol_time_plus_duree($now, $duration_value, "d"))."'"; if (is_numeric($duration_value))
$sql.= " AND sc.fk_soc = s.rowid AND sc.fk_user = u.rowid"; $sql .= " AND cd.date_fin_validite < '" . $db->idate(dol_time_plus_duree($now, $duration_value, "d")) . "'";
$sql .= " ORDER BY u.email ASC, s.rowid ASC, c.ref ASC"; // Order by email to allow one message per email $sql .= " AND sc.fk_soc = s.rowid AND sc.fk_user = u.rowid";
$sql .= " ORDER BY u.email ASC, s.rowid ASC, c.ref ASC"; // Order by email to allow one message per email
//print $sql; // print $sql;
$resql=$db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{ $num = $db->num_rows($resql);
$num = $db->num_rows($resql); $i = 0;
$i = 0; $oldemail = 'none';
$oldemail = 'none'; $olduid = 0; $oldlang=''; $olduid = 0;
$total = 0; $foundtoprocess = 0; $oldlang = '';
print "We found ".$num." couples (services to expire - sale representative) qualified\n"; $total = 0;
dol_syslog("We found ".$num." couples (services to expire - sale representative) qualified"); $foundtoprocess = 0;
$message=''; print "We found " . $num . " couples (services to expire - sale representative) qualified\n";
dol_syslog("We found " . $num . " couples (services to expire - sale representative) qualified");
$message = '';
if ($num) if ($num) {
{ while ($i < $num) {
while ($i < $num) $obj = $db->fetch_object($resql);
{
$obj = $db->fetch_object($resql);
if (($obj->email <> $oldemail || $obj->uid <> $olduid) || $oldemail == 'none') if (($obj->email != $oldemail || $obj->uid != $olduid) || $oldemail == 'none') {
{ // Break onto sales representative (new email or uid)
// Break onto sales representative (new email or uid) if (dol_strlen($oldemail) && $oldemail != 'none') {
if (dol_strlen($oldemail) && $oldemail != 'none') envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative, $duration_value);
{ } else {
envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative, $duration_value); if ($oldemail != 'none')
} print "- No email sent for " . $oldsalerepresentative . ", total: " . $total . "\n";
else }
{ $oldemail = $obj->email;
if ($oldemail != 'none') print "- No email sent for ".$oldsalerepresentative.", total: ".$total."\n"; $olduid = $obj->uid;
} $oldlang = $obj->lang;
$oldemail = $obj->email; $oldsalerepresentative = dolGetFirstLastname($obj->firstname, $obj->lastname);
$olduid = $obj->uid; $message = '';
$oldlang = $obj->lang; $total = 0;
$oldsalerepresentative=dolGetFirstLastname($obj->firstname, $obj->lastname); $foundtoprocess = 0;
$message = ''; $salerepresentative = dolGetFirstLastname($obj->firstname, $obj->lastname);
$total = 0; if (empty($obj->email))
$foundtoprocess = 0; print "Warning: Sale representative " . $salerepresentative . " has no email. Notice disabled.\n";
$salerepresentative=dolGetFirstLastname($obj->firstname, $obj->lastname); }
if (empty($obj->email)) print "Warning: Sale representative ".$salerepresentative." has no email. Notice disabled.\n";
}
// Define line content // Define line content
$outputlangs=new Translate('', $conf); $outputlangs = new Translate('', $conf);
$outputlangs->setDefaultLang(empty($obj->lang)?$langs->defaultlang:$obj->lang); // By default language of sale representative $outputlangs->setDefaultLang(empty($obj->lang) ? $langs->defaultlang : $obj->lang); // By default language of sale representative
// Load translation files required by the page // Load translation files required by the page
$outputlangs->loadLangs(array("main", "contracts", "bills", "products")); $outputlangs->loadLangs(array("main","contracts","bills","products"));
if (dol_strlen($obj->email)) if (dol_strlen($obj->email)) {
{ $message .= $outputlangs->trans("Contract") . " " . $obj->ref . ": " . $langs->trans("Service") . " " . dol_concatdesc($obj->plabel, $obj->description) . " (" . price($obj->total_ttc, 0, $outputlangs, 0, 0, - 1, $conf->currency) . ") " . $obj->name . ", " . $outputlangs->trans("DateEndPlannedShort") . " " . dol_print_date($db->jdate($obj->date_fin_validite), 'day') . "\n\n";
$message .= $outputlangs->trans("Contract")." ".$obj->ref.": ".$langs->trans("Service")." ".dol_concatdesc($obj->plabel, $obj->description)." (".price($obj->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency).") ".$obj->name.", ".$outputlangs->trans("DateEndPlannedShort")." ".dol_print_date($db->jdate($obj->date_fin_validite), 'day')."\n\n"; dol_syslog("email_expire_services_to_representatives.php: " . $obj->email);
dol_syslog("email_expire_services_to_representatives.php: ".$obj->email); $foundtoprocess ++;
$foundtoprocess++; }
} print "Service to expire " . $obj->ref . ", label " . dol_concatdesc($obj->plabel, $obj->description) . ", due date " . dol_print_date($db->jdate($obj->date_fin_validite), 'day') . " (linked to company " . $obj->name . ", sale representative " . dolGetFirstLastname($obj->firstname, $obj->lastname) . ", email " . $obj->email . "): ";
print "Service to expire ".$obj->ref.", label ".dol_concatdesc($obj->plabel, $obj->description).", due date ".dol_print_date($db->jdate($obj->date_fin_validite), 'day')." (linked to company ".$obj->name.", sale representative ".dolGetFirstLastname($obj->firstname, $obj->lastname).", email ".$obj->email."): "; if (dol_strlen($obj->email))
if (dol_strlen($obj->email)) print "qualified."; print "qualified.";
else print "disqualified (no email)."; else
print "disqualified (no email).";
print "\n"; print "\n";
unset($outputlangs); unset($outputlangs);
$total += $obj->total_ttc; $total += $obj->total_ttc;
$i++; $i ++;
} }
// Si il reste des envois en buffer // Si il reste des envois en buffer
if ($foundtoprocess) if ($foundtoprocess) {
{ if (dol_strlen($oldemail) && $oldemail != 'none') // Break onto email (new email)
if (dol_strlen($oldemail) && $oldemail != 'none') // Break onto email (new email)
{
envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative, $duration_value);
}
else
{ {
if ($oldemail != 'none') print "- No email sent for ".$oldsalerepresentative.", total: ".$total."\n"; envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative, $duration_value);
} } else {
} if ($oldemail != 'none')
} print "- No email sent for " . $oldsalerepresentative . ", total: " . $total . "\n";
else }
{ }
print "No services to expire (for companies linked to a particular commercial dolibarr user) found\n"; } else {
} print "No services to expire (for companies linked to a particular commercial dolibarr user) found\n";
}
exit(0); exit(0);
} else {
dol_print_error($db);
dol_syslog("email_expire_services_to_representatives.php: Error");
exit(- 1);
} }
else
{
dol_print_error($db);
dol_syslog("email_expire_services_to_representatives.php: Error");
exit(-1);
}
/** /**
* Send email * Send email
* *
* @param string $mode Mode (test | confirm) * @param string $mode
* @param string $oldemail Old email * Mode (test | confirm)
* @param string $message Message to send * @param string $oldemail
* @param string $total Total amount of unpayed invoices * Old email
* @param string $userlang Code lang to use for email output. * @param string $message
* @param string $oldsalerepresentative Old sale representative * Message to send
* @param int $duration_value duration value * @param string $total
* @return int <0 if KO, >0 if OK * Total amount of unpayed invoices
* @param string $userlang
* Code lang to use for email output.
* @param string $oldsalerepresentative
* Old sale representative
* @param int $duration_value
* duration value
* @return int <0 if KO, >0 if OK
*/ */
function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldsalerepresentative, $duration_value) function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldsalerepresentative, $duration_value)
{ {
global $conf,$langs; global $conf, $langs;
if (getenv('DOL_FORCE_EMAIL_TO')) $oldemail=getenv('DOL_FORCE_EMAIL_TO'); if (getenv('DOL_FORCE_EMAIL_TO'))
$oldemail = getenv('DOL_FORCE_EMAIL_TO');
$newlangs=new Translate('', $conf); $newlangs = new Translate('', $conf);
$newlangs->setDefaultLang(empty($userlang)?(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT):$userlang); $newlangs->setDefaultLang(empty($userlang) ? (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT) : $userlang);
$newlangs->load("main"); $newlangs->load("main");
$newlangs->load("contracts"); $newlangs->load("contracts");
if ($duration_value) if ($duration_value) {
{ if ($duration_value > 0)
if ($duration_value > 0) $title=$newlangs->transnoentities("ListOfServicesToExpireWithDuration", $duration_value); $title = $newlangs->transnoentities("ListOfServicesToExpireWithDuration", $duration_value);
else $title=$newlangs->transnoentities("ListOfServicesToExpireWithDurationNeg", $duration_value); else
} $title = $newlangs->transnoentities("ListOfServicesToExpireWithDurationNeg", $duration_value);
else } else
$title= $newlangs->transnoentities("ListOfServicesToExpire"); $title = $newlangs->transnoentities("ListOfServicesToExpire");
$subject = (empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_SUBJECT)?$title:$conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_SUBJECT); $subject = (empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_SUBJECT) ? $title : $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_SUBJECT);
$sendto = $oldemail; $sendto = $oldemail;
$from = $conf->global->MAIN_MAIL_EMAIL_FROM; $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
$errorsto = $conf->global->MAIN_MAIL_ERRORS_TO; $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
$msgishtml = -1; $msgishtml = - 1;
print "- Send email for ".$oldsalerepresentative." (".$oldemail."), total: ".$total."\n"; print "- Send email for " . $oldsalerepresentative . " (" . $oldemail . "), total: " . $total . "\n";
dol_syslog("email_expire_services_to_representatives.php: send mail to ".$oldemail); dol_syslog("email_expire_services_to_representatives.php: send mail to " . $oldemail);
$usehtml=0; $usehtml = 0;
if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER)) $usehtml+=1; if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER))
if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER)) $usehtml+=1; $usehtml += 1;
if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER))
$usehtml += 1;
$allmessage=''; $allmessage = '';
if (! empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER)) if (! empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER)) {
{ $allmessage .= $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER;
$allmessage.=$conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER; } else {
} $allmessage .= $title . ($usehtml ? "<br>\n" : "\n") . ($usehtml ? "<br>\n" : "\n");
else $allmessage .= $newlangs->transnoentities("NoteListOfYourExpiredServices") . ($usehtml ? "<br>\n" : "\n") . ($usehtml ? "<br>\n" : "\n");
{ }
$allmessage.= $title.($usehtml?"<br>\n":"\n").($usehtml?"<br>\n":"\n"); $allmessage .= $message . ($usehtml ? "<br>\n" : "\n");
$allmessage.= $newlangs->transnoentities("NoteListOfYourExpiredServices").($usehtml?"<br>\n":"\n").($usehtml?"<br>\n":"\n"); $allmessage .= $langs->trans("Total") . " = " . price($total, 0, $userlang, 0, 0, - 1, $conf->currency) . ($usehtml ? "<br>\n" : "\n");
} if (! empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER)) {
$allmessage.= $message.($usehtml?"<br>\n":"\n"); $allmessage .= $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER;
$allmessage.= $langs->trans("Total")." = ".price($total, 0, $userlang, 0, 0, -1, $conf->currency).($usehtml?"<br>\n":"\n"); if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER))
if (! empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER)) $usehtml += 1;
{ }
$allmessage.=$conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER;
if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER)) $usehtml+=1;
}
$mail = new CMailFile( $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
$subject,
$sendto,
$from,
$allmessage,
array(),
array(),
array(),
'',
'',
0,
$msgishtml
);
$mail->errors_to = $errorsto; $mail->errors_to = $errorsto;
// Send or not email // Send or not email
if ($mode == 'confirm') if ($mode == 'confirm') {
{ $result = $mail->sendfile();
$result=$mail->sendfile(); if (! $result) {
if (! $result) print "Error sending email " . $mail->error . "\n";
{ dol_syslog("Error sending email " . $mail->error . "\n");
print "Error sending email ".$mail->error."\n"; }
dol_syslog("Error sending email ".$mail->error."\n"); } else {
} print "No email sent (test mode)\n";
} dol_syslog("No email sent (test mode)");
else $mail->dump_mail();
{ $result = 1;
print "No email sent (test mode)\n"; }
dol_syslog("No email sent (test mode)");
$mail->dump_mail();
$result=1;
}
if ($result) if ($result) {
{ return 1;
return 1; } else {
} return - 1;
else }
{
return -1;
}
} }

View File

@ -1,7 +1,8 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/* Copyright (C) 2012 Nicolas Villa aka Boyquotes http://informetic.fr /*
* Copyright (C) 2013 Florian Henry <forian.henry@open-concept.pro * Copyright (C) 2012 Nicolas Villa aka Boyquotes http://informetic.fr
* Copyright (C) 2013 Florian Henry <forian.henry@open-concept.pro
* Copyright (C) 2013-2015 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2013-2015 Laurent Destailleur <eldy@users.sourceforge.net>
* *
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
@ -11,7 +12,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -19,255 +20,231 @@
*/ */
/** /**
* \file scripts/cron/cron_run_jobs.php * \file scripts/cron/cron_run_jobs.php
* \ingroup cron * \ingroup cron
* \brief Execute pendings jobs * \brief Execute pendings jobs
*/ */
if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal if (! defined('NOTOKENRENEWAL'))
if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); define('NOTOKENRENEWAL', '1'); // Disables token renewal
if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); if (! defined('NOREQUIREMENU'))
if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); define('NOREQUIREMENU', '1');
if (! defined('NOLOGIN')) define('NOLOGIN', '1'); if (! defined('NOREQUIREHTML'))
//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); define('NOREQUIREHTML', '1');
if (! defined('NOREQUIREAJAX'))
define('NOREQUIREAJAX', '1');
if (! defined('NOLOGIN'))
define('NOLOGIN', '1');
// if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1');
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Error if Web mode // Error if Web mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
require_once $path."../../htdocs/master.inc.php"; require_once $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT."/cron/class/cronjob.class.php"; require_once DOL_DOCUMENT_ROOT . "/cron/class/cronjob.class.php";
require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
// Check parameters // Check parameters
if (! isset($argv[1]) || ! $argv[1]) { if (! isset($argv[1]) || ! $argv[1]) {
usage($path, $script_file); usage($path, $script_file);
exit(-1); exit(- 1);
} }
$key=$argv[1]; $key = $argv[1];
if (! isset($argv[2]) || ! $argv[2]) { if (! isset($argv[2]) || ! $argv[2]) {
usage($path, $script_file); usage($path, $script_file);
exit(-1); exit(- 1);
} }
$userlogin=$argv[2]; $userlogin = $argv[2];
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
/* /*
* Main * Main
*/ */
$langs->loadLangs(array('main', 'dict')); $langs->loadLangs(array('main','dict'));
// current date // current date
$now=dol_now(); $now = dol_now();
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." ***** userlogin=" . $userlogin . " ***** " . dol_print_date($now, 'dayhourrfc') . " *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " ***** userlogin=" . $userlogin . " ***** " . dol_print_date($now, 'dayhourrfc') . " *****\n";
// Check module cron is activated // Check module cron is activated
if (empty($conf->cron->enabled)) if (empty($conf->cron->enabled)) {
{
print "Error: module Scheduled jobs (cron) not activated\n"; print "Error: module Scheduled jobs (cron) not activated\n";
exit(-1); exit(- 1);
} }
// Check module cron is activated // Check module cron is activated
if (empty($conf->cron->enabled)) if (empty($conf->cron->enabled)) {
{
print "Error: module Scheduled jobs (cron) not activated\n"; print "Error: module Scheduled jobs (cron) not activated\n";
exit(-1); exit(- 1);
} }
// Check security key // Check security key
if ($key != $conf->global->CRON_KEY) if ($key != $conf->global->CRON_KEY) {
{
print "Error: securitykey is wrong\n"; print "Error: securitykey is wrong\n";
exit(-1); exit(- 1);
} }
// If param userlogin is reserved word 'firstadmin' // If param userlogin is reserved word 'firstadmin'
if ($userlogin == 'firstadmin') if ($userlogin == 'firstadmin') {
{ $sql = 'SELECT login, entity from ' . MAIN_DB_PREFIX . 'user WHERE admin = 1 and statut = 1 ORDER BY entity LIMIT 1';
$sql='SELECT login, entity from '.MAIN_DB_PREFIX.'user WHERE admin = 1 and statut = 1 ORDER BY entity LIMIT 1'; $resql = $db->query($sql);
$resql=$db->query($sql); if ($resql) {
if ($resql) $obj = $db->fetch_object($resql);
{ if ($obj) {
$obj=$db->fetch_object($resql); $userlogin = $obj->login;
if ($obj) echo "First admin user found is login '" . $userlogin . "', entity " . $obj->entity . "\n";
{ }
$userlogin = $obj->login; } else
echo "First admin user found is login '".$userlogin."', entity ".$obj->entity."\n"; dol_print_error($db);
}
}
else dol_print_error($db);
} }
// Check user login // Check user login
$user=new User($db); $user = new User($db);
$result=$user->fetch('', $userlogin); $result = $user->fetch('', $userlogin);
if ($result < 0) if ($result < 0) {
{ echo "User Error: " . $user->error;
echo "User Error: ".$user->error; dol_syslog("cron_run_jobs.php:: User Error:" . $user->error, LOG_ERR);
dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR); exit(- 1);
exit(-1); } else {
} if (empty($user->id)) {
else echo "User login: " . $userlogin . " does not exists";
{ dol_syslog("User login:" . $userlogin . " does not exists", LOG_ERR);
if (empty($user->id)) exit(- 1);
{
echo "User login: ".$userlogin." does not exists";
dol_syslog("User login:".$userlogin." does not exists", LOG_ERR);
exit(-1);
} }
} }
$user->getrights(); $user->getrights();
if (isset($argv[3]) || $argv[3]) if (isset($argv[3]) || $argv[3]) {
{
$id = $argv[3]; $id = $argv[3];
} }
// create a jobs object // create a jobs object
$object = new Cronjob($db); $object = new Cronjob($db);
$filter=array(); $filter = array();
if (! empty($id)) { if (! empty($id)) {
if (! is_numeric($id)) if (! is_numeric($id)) {
{
echo "Error: Bad value for parameter job id"; echo "Error: Bad value for parameter job id";
dol_syslog("cron_run_jobs.php Bad value for parameter job id", LOG_WARNING); dol_syslog("cron_run_jobs.php Bad value for parameter job id", LOG_WARNING);
exit; exit();
} }
$filter['t.rowid']=$id; $filter['t.rowid'] = $id;
} }
$result = $object->fetch_all('ASC,ASC,ASC', 't.priority,t.entity,t.rowid', 0, 0, 1, $filter, 0); $result = $object->fetch_all('ASC,ASC,ASC', 't.priority,t.entity,t.rowid', 0, 0, 1, $filter, 0);
if ($result<0) if ($result < 0) {
{ echo "Error: " . $object->error;
echo "Error: ".$object->error; dol_syslog("cron_run_jobs.php:: fetch Error " . $object->error, LOG_ERR);
dol_syslog("cron_run_jobs.php:: fetch Error ".$object->error, LOG_ERR); exit(- 1);
exit(-1);
} }
$qualifiedjobs = array(); $qualifiedjobs = array();
foreach($object->lines as $val) foreach ($object->lines as $val) {
{ if (! verifCond($val->test))
if (! verifCond($val->test)) continue; continue;
$qualifiedjobs[] = $val; $qualifiedjobs[] = $val;
} }
// TODO Duplicate. This sequence of code must be shared with code into public/cron/cron_run_jobs.php php page. // TODO Duplicate. This sequence of code must be shared with code into public/cron/cron_run_jobs.php php page.
$nbofjobs=count($qualifiedjobs); $nbofjobs = count($qualifiedjobs);
$nbofjobslaunchedok=0; $nbofjobslaunchedok = 0;
$nbofjobslaunchedko=0; $nbofjobslaunchedko = 0;
if (is_array($qualifiedjobs) && (count($qualifiedjobs)>0)) if (is_array($qualifiedjobs) && (count($qualifiedjobs) > 0)) {
{
// Loop over job // Loop over job
foreach($qualifiedjobs as $line) foreach ($qualifiedjobs as $line) {
{ dol_syslog("cron_run_jobs.php cronjobid: " . $line->id . " priority=" . $line->priority . " entity=" . $line->entity . " label=" . $line->label, LOG_DEBUG);
dol_syslog("cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label, LOG_DEBUG);
echo "cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label; echo "cron_run_jobs.php cronjobid: " . $line->id . " priority=" . $line->priority . " entity=" . $line->entity . " label=" . $line->label;
//If date_next_jobs is less of current date, execute the program, and store the execution time of the next execution in database // If date_next_jobs is less of current date, execute the program, and store the execution time of the next execution in database
if (($line->datenextrun < $now) && (empty($line->datestart) || $line->datestart <= $now) && (empty($line->dateend) || $line->dateend >= $now)) if (($line->datenextrun < $now) && (empty($line->datestart) || $line->datestart <= $now) && (empty($line->dateend) || $line->dateend >= $now)) {
{
echo " - qualified"; echo " - qualified";
dol_syslog("cron_run_jobs.php line->datenextrun:".dol_print_date($line->datenextrun, 'dayhourrfc')." line->datestart:".dol_print_date($line->datestart, 'dayhourrfc')." line->dateend:".dol_print_date($line->dateend, 'dayhourrfc')." now:".dol_print_date($now, 'dayhourrfc')); dol_syslog("cron_run_jobs.php line->datenextrun:" . dol_print_date($line->datenextrun, 'dayhourrfc') . " line->datestart:" . dol_print_date($line->datestart, 'dayhourrfc') . " line->dateend:" . dol_print_date($line->dateend, 'dayhourrfc') . " now:" . dol_print_date($now, 'dayhourrfc'));
$cronjob=new Cronjob($db); $cronjob = new Cronjob($db);
$result=$cronjob->fetch($line->id); $result = $cronjob->fetch($line->id);
if ($result < 0) if ($result < 0) {
{ echo "Error cronjobid: " . $line->id . " cronjob->fetch: " . $cronjob->error . "\n";
echo "Error cronjobid: ".$line->id." cronjob->fetch: ".$cronjob->error."\n"; echo "Failed to fetch job " . $line->id . "\n";
echo "Failed to fetch job ".$line->id."\n"; dol_syslog("cron_run_jobs.php::fetch Error " . $cronjob->error, LOG_ERR);
dol_syslog("cron_run_jobs.php::fetch Error ".$cronjob->error, LOG_ERR); exit(- 1);
exit(-1);
} }
// Execute job // Execute job
$result=$cronjob->run_jobs($userlogin); $result = $cronjob->run_jobs($userlogin);
if ($result < 0) if ($result < 0) {
{ echo "Error cronjobid: " . $line->id . " cronjob->run_job: " . $cronjob->error . "\n";
echo "Error cronjobid: ".$line->id." cronjob->run_job: ".$cronjob->error."\n";
echo "At least one job failed. Go on menu Home-Setup-Admin tools to see result for each job.\n"; echo "At least one job failed. Go on menu Home-Setup-Admin tools to see result for each job.\n";
echo "You can also enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n"; echo "You can also enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
dol_syslog("cron_run_jobs.php::run_jobs Error ".$cronjob->error, LOG_ERR); dol_syslog("cron_run_jobs.php::run_jobs Error " . $cronjob->error, LOG_ERR);
$nbofjobslaunchedko++; $nbofjobslaunchedko ++;
} } else {
else $nbofjobslaunchedok ++;
{
$nbofjobslaunchedok++;
} }
echo " - result of run_jobs = ".$result; echo " - result of run_jobs = " . $result;
// we re-program the next execution and stores the last execution time for this job // we re-program the next execution and stores the last execution time for this job
$result=$cronjob->reprogram_jobs($userlogin, $now); $result = $cronjob->reprogram_jobs($userlogin, $now);
if ($result<0) if ($result < 0) {
{ echo "Error cronjobid: " . $line->id . " cronjob->reprogram_job: " . $cronjob->error . "\n";
echo "Error cronjobid: ".$line->id." cronjob->reprogram_job: ".$cronjob->error."\n";
echo "Enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n"; echo "Enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
dol_syslog("cron_run_jobs.php::reprogram_jobs Error ".$cronjob->error, LOG_ERR); dol_syslog("cron_run_jobs.php::reprogram_jobs Error " . $cronjob->error, LOG_ERR);
exit(-1); exit(- 1);
} }
echo " - reprogrammed\n"; echo " - reprogrammed\n";
} } else {
else
{
echo " - not qualified\n"; echo " - not qualified\n";
dol_syslog("cron_run_jobs.php job not qualified line->datenextrun:".dol_print_date($line->datenextrun, 'dayhourrfc')." line->datestart:".dol_print_date($line->datestart, 'dayhourrfc')." line->dateend:".dol_print_date($line->dateend, 'dayhourrfc')." now:".dol_print_date($now, 'dayhourrfc')); dol_syslog("cron_run_jobs.php job not qualified line->datenextrun:" . dol_print_date($line->datenextrun, 'dayhourrfc') . " line->datestart:" . dol_print_date($line->datestart, 'dayhourrfc') . " line->dateend:" . dol_print_date($line->dateend, 'dayhourrfc') . " now:" . dol_print_date($now, 'dayhourrfc'));
} }
} }
} } else {
else
{
echo "cron_run_jobs.php no qualified job found\n"; echo "cron_run_jobs.php no qualified job found\n";
} }
$db->close(); $db->close();
if ($nbofjobslaunchedko) exit(1); if ($nbofjobslaunchedko)
exit(1);
exit(0); exit(0);
/** /**
* script cron usage * script cron usage
* *
* @param string $path path * @param string $path
* @param string $script_file filename * path
* @param string $script_file
* filename
* @return void * @return void
*/ */
function usage($path, $script_file) function usage($path, $script_file)
{ {
global $conf; global $conf;
print "Usage: ".$script_file." securitykey userlogin|'firstadmin' [cronjobid]\n"; print "Usage: " . $script_file . " securitykey userlogin|'firstadmin' [cronjobid]\n";
print "The script return 0 when everything worked successfully.\n"; print "The script return 0 when everything worked successfully.\n";
print "\n"; print "\n";
print "On Linux system, you can have cron jobs ran automatically by adding an entry into cron.\n"; print "On Linux system, you can have cron jobs ran automatically by adding an entry into cron.\n";
print "For example, to run pending tasks each day at 3:30, you can add this line:\n"; print "For example, to run pending tasks each day at 3:30, you can add this line:\n";
print "30 3 * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n"; print "30 3 * * * " . $path . $script_file . " securitykey userlogin > " . DOL_DATA_ROOT . "/" . $script_file . ".log\n";
print "For example, to run pending tasks every 5mn, you can add this line:\n"; print "For example, to run pending tasks every 5mn, you can add this line:\n";
print "*/5 * * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n"; print "*/5 * * * * " . $path . $script_file . " securitykey userlogin > " . DOL_DATA_ROOT . "/" . $script_file . ".log\n";
} }

View File

@ -1,9 +1,9 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/* /*
* Copyright (C) 2004 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2005-2016 Regis Houssin <regis.houssin@inodbox.com> * Copyright (C) 2005-2016 Regis Houssin <regis.houssin@inodbox.com>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -12,386 +12,347 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
/** /**
* \file scripts/emailings/mailing-send.php * \file scripts/emailings/mailing-send.php
* \ingroup mailing * \ingroup mailing
* \brief Script d'envoi d'un mailing prepare et valide * \brief Script d'envoi d'un mailing prepare et valide
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
if (! isset($argv[1]) || ! $argv[1]) { if (! isset($argv[1]) || ! $argv[1]) {
print "Usage: ".$script_file." (ID_MAILING|all)\n"; print "Usage: " . $script_file . " (ID_MAILING|all)\n";
exit(-1); exit(- 1);
} }
$id=$argv[1]; $id = $argv[1];
if (isset($argv[2]) || !empty($argv[2])) $login = $argv[2]; if (isset($argv[2]) || ! empty($argv[2]))
else $login = ''; $login = $argv[2];
else
require_once $path."../../htdocs/master.inc.php"; $login = '';
require_once DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php";
require_once DOL_DOCUMENT_ROOT."/comm/mailing/class/mailing.class.php";
require_once $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT . "/core/class/CMailFile.class.php";
require_once DOL_DOCUMENT_ROOT . "/comm/mailing/class/mailing.class.php";
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
if ($conf->global->MAILING_LIMIT_SENDBYCLI == '-1') if ($conf->global->MAILING_LIMIT_SENDBYCLI == '-1') {}
{
}
$user = new User($db); $user = new User($db);
// for signature, we use user send as parameter // for signature, we use user send as parameter
if (! empty($login)) $user->fetch('', $login); if (! empty($login))
$user->fetch('', $login);
// We get list of emailing id to process // We get list of emailing id to process
$sql = "SELECT m.rowid"; $sql = "SELECT m.rowid";
$sql.= " FROM ".MAIN_DB_PREFIX."mailing as m"; $sql .= " FROM " . MAIN_DB_PREFIX . "mailing as m";
$sql.= " WHERE m.statut IN (1,2)"; $sql .= " WHERE m.statut IN (1,2)";
if ($id != 'all') if ($id != 'all') {
{ $sql .= " AND m.rowid= " . $id;
$sql.= " AND m.rowid= ".$id; $sql .= " LIMIT 1";
$sql.= " LIMIT 1";
} }
$resql=$db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$j = 0; $j = 0;
if ($num) if ($num) {
{ for ($j = 0; $j < $num; $j ++) {
for ($j=0; $j<$num; $j++)
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
dol_syslog("Process mailing with id ".$obj->rowid); dol_syslog("Process mailing with id " . $obj->rowid);
print "Process mailing with id ".$obj->rowid."\n"; print "Process mailing with id " . $obj->rowid . "\n";
$emailing = new Mailing($db); $emailing = new Mailing($db);
$emailing->fetch($obj->rowid); $emailing->fetch($obj->rowid);
$id = $emailing->id; $id = $emailing->id;
$subject = $emailing->sujet; $subject = $emailing->sujet;
$message = $emailing->body; $message = $emailing->body;
$from = $emailing->email_from; $from = $emailing->email_from;
$replyto = $emailing->email_replyto; $replyto = $emailing->email_replyto;
$errorsto = $emailing->email_errorsto; $errorsto = $emailing->email_errorsto;
// Le message est-il en html // Le message est-il en html
$msgishtml=-1; // Unknown by default $msgishtml = - 1; // Unknown by default
if (preg_match('/[\s\t]*<html>/i', $message)) $msgishtml=1; if (preg_match('/[\s\t]*<html>/i', $message))
$msgishtml = 1;
$nbok=0; $nbko=0; $nbok = 0;
$nbko = 0;
// On choisit les mails non deja envoyes pour ce mailing (statut=0) // On choisit les mails non deja envoyes pour ce mailing (statut=0)
// ou envoyes en erreur (statut=-1) // ou envoyes en erreur (statut=-1)
$sql2 = "SELECT mc.rowid, mc.fk_mailing, mc.lastname, mc.firstname, mc.email, mc.other, mc.source_url, mc.source_id, mc.source_type, mc.tag"; $sql2 = "SELECT mc.rowid, mc.fk_mailing, mc.lastname, mc.firstname, mc.email, mc.other, mc.source_url, mc.source_id, mc.source_type, mc.tag";
$sql2.= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc"; $sql2 .= " FROM " . MAIN_DB_PREFIX . "mailing_cibles as mc";
$sql2.= " WHERE mc.statut < 1 AND mc.fk_mailing = ".$id; $sql2 .= " WHERE mc.statut < 1 AND mc.fk_mailing = " . $id;
if ($conf->global->MAILING_LIMIT_SENDBYCLI > 0) if ($conf->global->MAILING_LIMIT_SENDBYCLI > 0) {
{ $sql2 .= " LIMIT " . $conf->global->MAILING_LIMIT_SENDBYCLI;
$sql2.= " LIMIT ".$conf->global->MAILING_LIMIT_SENDBYCLI;
} }
$resql2=$db->query($sql2); $resql2 = $db->query($sql2);
if ($resql2) if ($resql2) {
{
$num2 = $db->num_rows($resql2); $num2 = $db->num_rows($resql2);
dol_syslog("Nb of targets = ".$num2, LOG_DEBUG); dol_syslog("Nb of targets = " . $num2, LOG_DEBUG);
print "Nb of targets = ".$num2."\n"; print "Nb of targets = " . $num2 . "\n";
if ($num2) if ($num2) {
{ $now = dol_now();
$now=dol_now();
// Positionne date debut envoi // Positionne date debut envoi
$sqlstartdate="UPDATE ".MAIN_DB_PREFIX."mailing SET date_envoi='".$db->idate($now)."' WHERE rowid=".$id; $sqlstartdate = "UPDATE " . MAIN_DB_PREFIX . "mailing SET date_envoi='" . $db->idate($now) . "' WHERE rowid=" . $id;
$resqlstartdate=$db->query($sqlstartdate); $resqlstartdate = $db->query($sqlstartdate);
if (! $resqlstartdate) if (! $resqlstartdate) {
{
dol_print_error($db); dol_print_error($db);
$error++; $error ++;
} }
// Look on each email and sent message // Look on each email and sent message
$i = 0; $i = 0;
while ($i < $num2) while ($i < $num2) {
{
// Here code is common with same loop ino card.php // Here code is common with same loop ino card.php
$res=1; $res = 1;
$now=dol_now(); $now = dol_now();
$obj = $db->fetch_object($resql2); $obj = $db->fetch_object($resql2);
// sendto en RFC2822 // sendto en RFC2822
$sendto = str_replace(',', ' ', dolGetFirstLastname($obj->firstname, $obj->lastname) ." <".$obj->email.">"); $sendto = str_replace(',', ' ', dolGetFirstLastname($obj->firstname, $obj->lastname) . " <" . $obj->email . ">");
// Make subtsitutions on topic and body // Make subtsitutions on topic and body
$other=explode(';', $obj->other); $other = explode(';', $obj->other);
$tmpfield=explode('=', $other[0], 2); $other1=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); $tmpfield = explode('=', $other[0], 2);
$tmpfield=explode('=', $other[1], 2); $other2=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); $other1 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]);
$tmpfield=explode('=', $other[2], 2); $other3=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); $tmpfield = explode('=', $other[1], 2);
$tmpfield=explode('=', $other[3], 2); $other4=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); $other2 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]);
$tmpfield=explode('=', $other[4], 2); $other5=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]); $tmpfield = explode('=', $other[2], 2);
$signature = ((!empty($user->signature) && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$user->signature:''); $other3 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]);
$tmpfield = explode('=', $other[3], 2);
$other4 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]);
$tmpfield = explode('=', $other[4], 2);
$other5 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]);
$signature = ((! empty($user->signature) && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? $user->signature : '');
$object = null; // Not defined with mass emailing $object = null; // Not defined with mass emailing
$parameters=array('mode'=>'emailing'); $parameters = array('mode' => 'emailing');
$substitutionarray=getCommonSubstitutionArray($langs, 0, array('object','objectamount'), $object); // Note: On mass emailing, this is null because we don't know object $substitutionarray = getCommonSubstitutionArray($langs, 0, array('object','objectamount'), $object); // Note: On mass emailing, this is null because we don't know object
// Array of possible substitutions (See also file mailing-send.php that should manage same substitutions) // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
$substitutionarray['__ID__'] = $obj->source_id; $substitutionarray['__ID__'] = $obj->source_id;
$substitutionarray['__EMAIL__'] = $obj->email; $substitutionarray['__EMAIL__'] = $obj->email;
$substitutionarray['__LASTNAME__'] = $obj->lastname; $substitutionarray['__LASTNAME__'] = $obj->lastname;
$substitutionarray['__FIRSTNAME__'] = $obj->firstname; $substitutionarray['__FIRSTNAME__'] = $obj->firstname;
$substitutionarray['__MAILTOEMAIL__'] = '<a href="mailto:'.$obj->email.'">'.$obj->email.'</a>'; $substitutionarray['__MAILTOEMAIL__'] = '<a href="mailto:' . $obj->email . '">' . $obj->email . '</a>';
$substitutionarray['__OTHER1__'] = $other1; $substitutionarray['__OTHER1__'] = $other1;
$substitutionarray['__OTHER2__'] = $other2; $substitutionarray['__OTHER2__'] = $other2;
$substitutionarray['__OTHER3__'] = $other3; $substitutionarray['__OTHER3__'] = $other3;
$substitutionarray['__OTHER4__'] = $other4; $substitutionarray['__OTHER4__'] = $other4;
$substitutionarray['__OTHER5__'] = $other5; $substitutionarray['__OTHER5__'] = $other5;
$substitutionarray['__USER_SIGNATURE__'] = $signature; // Signature is empty when ran from command line or taken from user in parameter) $substitutionarray['__USER_SIGNATURE__'] = $signature; // Signature is empty when ran from command line or taken from user in parameter)
$substitutionarray['__SIGNATURE__'] = $signature; // For backward compatibility $substitutionarray['__SIGNATURE__'] = $signature; // For backward compatibility
$substitutionarray['__CHECK_READ__'] = '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$obj->tag.'&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" width="1" height="1" style="width:1px;height:1px" border="0"/>'; $substitutionarray['__CHECK_READ__'] = '<img src="' . DOL_MAIN_URL_ROOT . '/public/emailing/mailing-read.php?tag=' . $obj->tag . '&securitykey=' . urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY) . '" width="1" height="1" style="width:1px;height:1px" border="0"/>';
$substitutionarray['__UNSUBSCRIBE__'] = '<a href="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-unsubscribe.php?tag='.$obj->tag.'&unsuscrib=1&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" target="_blank">'.$langs->trans("MailUnsubcribe").'</a>'; $substitutionarray['__UNSUBSCRIBE__'] = '<a href="' . DOL_MAIN_URL_ROOT . '/public/emailing/mailing-unsubscribe.php?tag=' . $obj->tag . '&unsuscrib=1&securitykey=' . urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY) . '" target="_blank">' . $langs->trans("MailUnsubcribe") . '</a>';
$onlinepaymentenabled = 0; $onlinepaymentenabled = 0;
if (! empty($conf->paypal->enabled)) $onlinepaymentenabled++; if (! empty($conf->paypal->enabled))
if (! empty($conf->paybox->enabled)) $onlinepaymentenabled++; $onlinepaymentenabled ++;
if (! empty($conf->stripe->enabled)) $onlinepaymentenabled++; if (! empty($conf->paybox->enabled))
if ($onlinepaymentenabled && ! empty($conf->global->PAYMENT_SECURITY_TOKEN)) $onlinepaymentenabled ++;
{ if (! empty($conf->stripe->enabled))
$substitutionarray['__SECUREKEYPAYMENT__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); $onlinepaymentenabled ++;
if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) if ($onlinepaymentenabled && ! empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
{ $substitutionarray['__SECUREKEYPAYMENT__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
$substitutionarray['__SECUREKEYPAYMENT_MEMBER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
$substitutionarray['__SECUREKEYPAYMENT_ORDER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
$substitutionarray['__SECUREKEYPAYMENT_INVOICE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
$substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
} $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
else } else {
{ $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'membersubscription' . $obj->source_id, 2);
$substitutionarray['__SECUREKEYPAYMENT_MEMBER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'membersubscription' . $obj->source_id, 2); $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'order' . $obj->source_id, 2);
$substitutionarray['__SECUREKEYPAYMENT_ORDER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'order' . $obj->source_id, 2); $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'invoice' . $obj->source_id, 2);
$substitutionarray['__SECUREKEYPAYMENT_INVOICE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'invoice' . $obj->source_id, 2); $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'contractline' . $obj->source_id, 2);
$substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'contractline' . $obj->source_id, 2);
} }
} }
/* For backward compatibility */ /* For backward compatibility */
if (! empty($conf->paypal->enabled) && ! empty($conf->global->PAYPAL_SECURITY_TOKEN)) if (! empty($conf->paypal->enabled) && ! empty($conf->global->PAYPAL_SECURITY_TOKEN)) {
{ $substitutionarray['__SECUREKEYPAYPAL__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
$substitutionarray['__SECUREKEYPAYPAL__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_MEMBER__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE))
else $substitutionarray['__SECUREKEYPAYPAL_MEMBER__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'membersubscription' . $obj->source_id, 2); $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
else
$substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'membersubscription' . $obj->source_id, 2);
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_ORDER__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE))
else $substitutionarray['__SECUREKEYPAYPAL_ORDER__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'order' . $obj->source_id, 2); $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
else
$substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'order' . $obj->source_id, 2);
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_INVOICE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE))
else $substitutionarray['__SECUREKEYPAYPAL_INVOICE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'invoice' . $obj->source_id, 2); $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
else
$substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'invoice' . $obj->source_id, 2);
if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE))
else $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'contractline' . $obj->source_id, 2); $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
else
$substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'contractline' . $obj->source_id, 2);
} }
complete_substitutions_array($substitutionarray, $langs); complete_substitutions_array($substitutionarray, $langs);
$newsubject=make_substitutions($subject, $substitutionarray); $newsubject = make_substitutions($subject, $substitutionarray);
$newmessage=make_substitutions($message, $substitutionarray); $newmessage = make_substitutions($message, $substitutionarray);
$substitutionisok=true; $substitutionisok = true;
// Fabrication du mail // Fabrication du mail
$trackid='emailing-'.$obj->fk_mailing.'-'.$obj->rowid; $trackid = 'emailing-' . $obj->fk_mailing . '-' . $obj->rowid;
$mail = new CMailFile( $mail = new CMailFile($newsubject, $sendto, $from, $newmessage, array(), array(), array(), '', '', 0, $msgishtml, $errorsto, '', $trackid, '', 'emailing');
$newsubject,
$sendto,
$from,
$newmessage,
array(),
array(),
array(),
'',
'',
0,
$msgishtml,
$errorsto,
'',
$trackid,
'',
'emailing'
);
if ($mail->error) if ($mail->error) {
{ $res = 0;
$res=0;
} }
if (! $substitutionisok) if (! $substitutionisok) {
{ $mail->error = 'Some substitution failed';
$mail->error='Some substitution failed'; $res = 0;
$res=0;
} }
// Send Email // Send Email
if ($res) if ($res) {
{ $res = $mail->sendfile();
$res=$mail->sendfile();
} }
if ($res) if ($res) {
{
// Mail successful // Mail successful
$nbok++; $nbok ++;
dol_syslog("ok for emailing id ".$id." #".$i.($mail->error?' - '.$mail->error:''), LOG_DEBUG); dol_syslog("ok for emailing id " . $id . " #" . $i . ($mail->error ? ' - ' . $mail->error : ''), LOG_DEBUG);
// Note: If emailing is 100 000 targets, 100 000 entries are added, so we don't enter events for each target here // Note: If emailing is 100 000 targets, 100 000 entries are added, so we don't enter events for each target here
// We must union table llx_mailing_taget for event tab OR enter 1 event with a special table link (id of email in event) // We must union table llx_mailing_taget for event tab OR enter 1 event with a special table link (id of email in event)
// Run trigger // Run trigger
/* /*
if ($obj->source_type == 'contact') * if ($obj->source_type == 'contact')
{ * {
$emailing->sendtoid = $obj->source_id; * $emailing->sendtoid = $obj->source_id;
} * }
if ($obj->source_type == 'thirdparty') * if ($obj->source_type == 'thirdparty')
{ * {
$emailing->socid = $obj->source_id; * $emailing->socid = $obj->source_id;
} * }
// Call trigger * // Call trigger
$result=$emailing->call_trigger('EMAILING_SENTBYMAIL',$user); * $result=$emailing->call_trigger('EMAILING_SENTBYMAIL',$user);
if ($result < 0) $error++; * if ($result < 0) $error++;
// End call triggers * // End call triggers
*/ */
$sqlok ="UPDATE ".MAIN_DB_PREFIX."mailing_cibles"; $sqlok = "UPDATE " . MAIN_DB_PREFIX . "mailing_cibles";
$sqlok.=" SET statut=1, date_envoi='".$db->idate($now)."' WHERE rowid=".$obj->rowid; $sqlok .= " SET statut=1, date_envoi='" . $db->idate($now) . "' WHERE rowid=" . $obj->rowid;
$resqlok=$db->query($sqlok); $resqlok = $db->query($sqlok);
if (! $resqlok) if (! $resqlok) {
{
dol_print_error($db); dol_print_error($db);
$error++; $error ++;
} } else {
else // if cheack read is use then update prospect contact status
{ if (strpos($message, '__CHECK_READ__') !== false) {
//if cheack read is use then update prospect contact status // Update status communication of thirdparty prospect
if (strpos($message, '__CHECK_READ__') !== false) $sqlx = "UPDATE " . MAIN_DB_PREFIX . "societe SET fk_stcomm=2 WHERE rowid IN (SELECT source_id FROM " . MAIN_DB_PREFIX . "mailing_cibles WHERE rowid=" . $obj->rowid . ")";
{
//Update status communication of thirdparty prospect
$sqlx = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=2 WHERE rowid IN (SELECT source_id FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE rowid=".$obj->rowid.")";
dol_syslog("card.php: set prospect thirdparty status", LOG_DEBUG); dol_syslog("card.php: set prospect thirdparty status", LOG_DEBUG);
$resqlx=$db->query($sqlx); $resqlx = $db->query($sqlx);
if (! $resqlx) if (! $resqlx) {
{
dol_print_error($db); dol_print_error($db);
$error++; $error ++;
} }
//Update status communication of contact prospect // Update status communication of contact prospect
$sqlx = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=2 WHERE rowid IN (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."socpeople AS sc INNER JOIN ".MAIN_DB_PREFIX."mailing_cibles AS mc ON mc.rowid=".$obj->rowid." AND mc.source_type = 'contact' AND mc.source_id = sc.rowid)"; $sqlx = "UPDATE " . MAIN_DB_PREFIX . "societe SET fk_stcomm=2 WHERE rowid IN (SELECT sc.fk_soc FROM " . MAIN_DB_PREFIX . "socpeople AS sc INNER JOIN " . MAIN_DB_PREFIX . "mailing_cibles AS mc ON mc.rowid=" . $obj->rowid . " AND mc.source_type = 'contact' AND mc.source_id = sc.rowid)";
dol_syslog("card.php: set prospect contact status", LOG_DEBUG); dol_syslog("card.php: set prospect contact status", LOG_DEBUG);
$resqlx=$db->query($sqlx); $resqlx = $db->query($sqlx);
if (! $resqlx) if (! $resqlx) {
{
dol_print_error($db); dol_print_error($db);
$error++; $error ++;
} }
} }
if (!empty($conf->global->MAILING_DELAY)) { if (! empty($conf->global->MAILING_DELAY)) {
sleep($conf->global->MAILING_DELAY); sleep($conf->global->MAILING_DELAY);
} }
} }
} } else {
else
{
// Mail failed // Mail failed
$nbko++; $nbko ++;
dol_syslog("error for emailing id ".$id." #".$i.($mail->error?' - '.$mail->error:''), LOG_DEBUG); dol_syslog("error for emailing id " . $id . " #" . $i . ($mail->error ? ' - ' . $mail->error : ''), LOG_DEBUG);
$sqlerror="UPDATE ".MAIN_DB_PREFIX."mailing_cibles"; $sqlerror = "UPDATE " . MAIN_DB_PREFIX . "mailing_cibles";
$sqlerror.=" SET statut=-1, date_envoi=".$db->idate($now)." WHERE rowid=".$obj->rowid; $sqlerror .= " SET statut=-1, date_envoi=" . $db->idate($now) . " WHERE rowid=" . $obj->rowid;
$resqlerror=$db->query($sqlerror); $resqlerror = $db->query($sqlerror);
if (! $resqlerror) if (! $resqlerror) {
{
dol_print_error($db); dol_print_error($db);
$error++; $error ++;
} }
} }
$i++; $i ++;
} }
} } else {
else $mesg = "Emailing id " . $id . " has no recipient to target";
{ print $mesg . "\n";
$mesg="Emailing id ".$id." has no recipient to target";
print $mesg."\n";
dol_syslog($mesg, LOG_ERR); dol_syslog($mesg, LOG_ERR);
} }
// Loop finished, set global statut of mail // Loop finished, set global statut of mail
$statut=2; $statut = 2;
if (! $nbko) $statut=3; if (! $nbko)
$statut = 3;
$sqlenddate="UPDATE ".MAIN_DB_PREFIX."mailing SET statut=".$statut." WHERE rowid=".$id; $sqlenddate = "UPDATE " . MAIN_DB_PREFIX . "mailing SET statut=" . $statut . " WHERE rowid=" . $id;
dol_syslog("update global status", LOG_DEBUG); dol_syslog("update global status", LOG_DEBUG);
print "Update status of emailing id ".$id." to ".$statut."\n"; print "Update status of emailing id " . $id . " to " . $statut . "\n";
$resqlenddate=$db->query($sqlenddate); $resqlenddate = $db->query($sqlenddate);
if (! $resqlenddate) if (! $resqlenddate) {
{
dol_print_error($db); dol_print_error($db);
$error++; $error ++;
} }
} } else {
else
{
dol_print_error($db); dol_print_error($db);
$error++; $error ++;
} }
} }
} } else {
else $mesg = "No validated emailing id to send found.";
{ print $mesg . "\n";
$mesg="No validated emailing id to send found.";
print $mesg."\n";
dol_syslog($mesg, LOG_ERR); dol_syslog($mesg, LOG_ERR);
$error++; $error ++;
} }
} } else {
else
{
dol_print_error($db); dol_print_error($db);
$error++; $error ++;
} }
exit($error); exit($error);

View File

@ -1,9 +1,9 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/* /*
* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2013 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2013 Juanjo Menent <jmenent@2byte.es>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -12,7 +12,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -20,288 +20,272 @@
*/ */
/** /**
* \file scripts/invoices/email_unpaid_invoices_to_customers.php * \file scripts/invoices/email_unpaid_invoices_to_customers.php
* \ingroup facture * \ingroup facture
* \brief Script to send a mail to customers with unpaid invoices * \brief Script to send a mail to customers with unpaid invoices
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test si mode batch // Test si mode batch
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
if (! isset($argv[2]) || ! $argv[2] || ! in_array($argv[1], array('test','confirm')) || ! in_array($argv[2], array('thirdparties','contacts'))) if (! isset($argv[2]) || ! $argv[2] || ! in_array($argv[1], array('test','confirm')) || ! in_array($argv[2], array('thirdparties','contacts'))) {
{
print "Usage: $script_file (test|confirm) (thirdparties|contacts) [delay] [after]\n"; print "Usage: $script_file (test|confirm) (thirdparties|contacts) [delay] [after]\n";
print "\n"; print "\n";
print "Send an email to customers to remind all unpaid customer invoices.\n"; print "Send an email to customers to remind all unpaid customer invoices.\n";
print "If you choose 'test' mode, no emails are sent.\n"; print "If you choose 'test' mode, no emails are sent.\n";
print "If you add param delay (nb of days), only invoice with due date < today + delay are included.\n"; print "If you add param delay (nb of days), only invoice with due date < today + delay are included.\n";
print "If you add param after (nb of days), only invoice with due date >= today + delay are included.\n"; print "If you add param after (nb of days), only invoice with due date >= today + delay are included.\n";
exit(-1); exit(- 1);
} }
$mode=$argv[1]; $mode = $argv[1];
$targettype=$argv[2]; $targettype = $argv[2];
require $path . "../../htdocs/master.inc.php";
require $path."../../htdocs/master.inc.php"; require_once DOL_DOCUMENT_ROOT . "/core/class/CMailFile.class.php";
require_once DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php";
$langs->load('main'); $langs->load('main');
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
$now=dol_now('tzserver'); $now = dol_now('tzserver');
$duration_value=isset($argv[3])?$argv[3]:'none'; $duration_value = isset($argv[3]) ? $argv[3] : 'none';
$duration_value2=isset($argv[4])?$argv[4]:'none'; $duration_value2 = isset($argv[4]) ? $argv[4] : 'none';
$error = 0; $error = 0;
print $script_file." launched with mode ".$mode." default lang=".$langs->defaultlang.(is_numeric($duration_value)?" delay=".$duration_value:"").(is_numeric($duration_value2)?" after=".$duration_value2:"")."\n"; print $script_file . " launched with mode " . $mode . " default lang=" . $langs->defaultlang . (is_numeric($duration_value) ? " delay=" . $duration_value : "") . (is_numeric($duration_value2) ? " after=" . $duration_value2 : "") . "\n";
if ($mode != 'confirm') $conf->global->MAIN_DISABLE_ALL_MAILS=1; if ($mode != 'confirm')
$conf->global->MAIN_DISABLE_ALL_MAILS = 1;
$sql = "SELECT f.ref, f.total_ttc, f.date_lim_reglement as due_date,"; $sql = "SELECT f.ref, f.total_ttc, f.date_lim_reglement as due_date,";
$sql.= " s.rowid as sid, s.nom as name, s.email, s.default_lang"; $sql .= " s.rowid as sid, s.nom as name, s.email, s.default_lang";
if ($targettype == 'contacts') $sql.= ", sp.rowid as cid, sp.firstname as cfirstname, sp.lastname as clastname, sp.email as cemail"; if ($targettype == 'contacts')
$sql.= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."societe as s"; $sql .= ", sp.rowid as cid, sp.firstname as cfirstname, sp.lastname as clastname, sp.email as cemail";
if ($targettype == 'contacts') $sql.= ", ".MAIN_DB_PREFIX."socpeople as sp"; $sql .= " FROM " . MAIN_DB_PREFIX . "facture as f, " . MAIN_DB_PREFIX . "societe as s";
$sql.= " WHERE f.fk_statut = 1 AND f.paye = 0"; if ($targettype == 'contacts')
$sql.= " AND f.fk_soc = s.rowid"; $sql .= ", " . MAIN_DB_PREFIX . "socpeople as sp";
if (is_numeric($duration_value2)) $sql.= " AND f.date_lim_reglement >= '".$db->idate(dol_time_plus_duree($now, $duration_value2, "d"))."'"; $sql .= " WHERE f.fk_statut = 1 AND f.paye = 0";
if (is_numeric($duration_value)) $sql.= " AND f.date_lim_reglement < '".$db->idate(dol_time_plus_duree($now, $duration_value, "d"))."'"; $sql .= " AND f.fk_soc = s.rowid";
if ($targettype == 'contacts') $sql.= " AND s.rowid = sp.fk_soc"; if (is_numeric($duration_value2))
$sql.= " ORDER BY"; $sql .= " AND f.date_lim_reglement >= '" . $db->idate(dol_time_plus_duree($now, $duration_value2, "d")) . "'";
if ($targettype == 'contacts') $sql.= " sp.email, sp.rowid,"; if (is_numeric($duration_value))
$sql.= " s.email ASC, s.rowid ASC, f.ref ASC"; // Order by email to allow one message per email $sql .= " AND f.date_lim_reglement < '" . $db->idate(dol_time_plus_duree($now, $duration_value, "d")) . "'";
if ($targettype == 'contacts')
$sql .= " AND s.rowid = sp.fk_soc";
$sql .= " ORDER BY";
if ($targettype == 'contacts')
$sql .= " sp.email, sp.rowid,";
$sql .= " s.email ASC, s.rowid ASC, f.ref ASC"; // Order by email to allow one message per email
//print $sql; // print $sql;
$resql=$db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{ $num = $db->num_rows($resql);
$num = $db->num_rows($resql); $i = 0;
$i = 0; $oldemail = 'none';
$oldemail = 'none'; $oldsid = 0; $oldcid = 0; $oldlang=''; $oldsid = 0;
$total = 0; $foundtoprocess = 0; $oldcid = 0;
$trackthirdpartiessent = array(); $oldlang = '';
$total = 0;
$foundtoprocess = 0;
$trackthirdpartiessent = array();
print "We found ".$num." couples (unpayed validated invoices-".$targettype.") qualified\n"; print "We found " . $num . " couples (unpayed validated invoices-" . $targettype . ") qualified\n";
dol_syslog("We found ".$num." couples (unpayed validated invoices-".$targettype.") qualified"); dol_syslog("We found " . $num . " couples (unpayed validated invoices-" . $targettype . ") qualified");
$message=''; $message = '';
if ($num) if ($num) {
{ while ($i < $num) {
while ($i < $num) $obj = $db->fetch_object($resql);
{
$obj = $db->fetch_object($resql);
$newemail=empty($obj->cemail)?$obj->email:$obj->cemail; $newemail = empty($obj->cemail) ? $obj->email : $obj->cemail;
// Check if this record is a break after previous one // Check if this record is a break after previous one
$startbreak=false; $startbreak = false;
if ($newemail <> $oldemail || $oldemail == 'none') $startbreak=true; if ($newemail != $oldemail || $oldemail == 'none')
if ($obj->sid && $obj->sid <> $oldsid) $startbreak=true; $startbreak = true;
if ($obj->cid && $obj->cid <> $oldcid) $startbreak=true; if ($obj->sid && $obj->sid != $oldsid)
$startbreak = true;
if ($obj->cid && $obj->cid != $oldcid)
$startbreak = true;
if ($startbreak) if ($startbreak) {
{ // Break onto sales representative (new email or cid)
// Break onto sales representative (new email or cid) if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid . '|' . $oldemail])) {
if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget);
{ $trackthirdpartiessent[$oldsid . '|' . $oldemail] = 'contact id ' . $oldcid;
envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget); } else {
$trackthirdpartiessent[$oldsid.'|'.$oldemail]='contact id '.$oldcid; if ($oldemail != 'none') {
} if (empty($trackthirdpartiessent[$oldsid . '|' . $oldemail]))
else print "- No email sent for '" . $oldtarget . "', total: " . $total . "\n";
{ else
if ($oldemail != 'none') print "- No email sent for '" . $oldtarget . "', total: " . $total . " (already sent to " . $trackthirdpartiessent[$oldsid . '|' . $oldemail] . ")\n";
{ }
if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) print "- No email sent for '".$oldtarget."', total: ".$total."\n"; }
else print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n"; $oldemail = $newemail;
} $oldsid = $obj->sid;
} $oldcid = $obj->cid;
$oldemail = $newemail; $oldlang = $obj->lang;
$oldsid = $obj->sid; $oldtarget = (empty($obj->cfirstname) && empty($obj->clastname)) ? $obj->name : ($obj->clastname . " " . $obj->cfirstname);
$oldcid = $obj->cid; $message = '';
$oldlang = $obj->lang; $total = 0;
$oldtarget=(empty($obj->cfirstname) && empty($obj->clastname))?$obj->name:($obj->clastname." ".$obj->cfirstname); $foundtoprocess = 0;
$message = ''; $target = (empty($obj->cfirstname) && empty($obj->clastname)) ? $obj->name : ($obj->clastname . " " . $obj->cfirstname);
$total = 0; // if (empty($newemail)) print "Warning: Customer ".$target." has no email. Notice disabled.\n";
$foundtoprocess = 0; }
$target=(empty($obj->cfirstname) && empty($obj->clastname))?$obj->name:($obj->clastname." ".$obj->cfirstname);
//if (empty($newemail)) print "Warning: Customer ".$target." has no email. Notice disabled.\n";
}
// Define line content // Define line content
$outputlangs=new Translate('', $conf); $outputlangs = new Translate('', $conf);
$outputlangs->setDefaultLang(empty($obj->default_lang)?$langs->defaultlang:$obj->default_lang); // By default language of customer $outputlangs->setDefaultLang(empty($obj->default_lang) ? $langs->defaultlang : $obj->default_lang); // By default language of customer
// Load translation files required by the page // Load translation files required by the page
$outputlangs->loadLangs(array("main", "bills")); $outputlangs->loadLangs(array("main","bills"));
if (dol_strlen($newemail)) if (dol_strlen($newemail)) {
{ $message .= $outputlangs->trans("Invoice") . " " . $obj->ref . " : " . price($obj->total_ttc, 0, $outputlangs, 0, 0, - 1, $conf->currency) . "\n";
$message .= $outputlangs->trans("Invoice")." ".$obj->ref." : ".price($obj->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency)."\n"; dol_syslog("email_unpaid_invoices_to_customers.php: " . $newemail . " " . $message);
dol_syslog("email_unpaid_invoices_to_customers.php: ".$newemail." ".$message); $foundtoprocess ++;
$foundtoprocess++; }
} print "Unpaid invoice " . $obj->ref . ", price " . price2num($obj->total_ttc) . ", due date " . dol_print_date($db->jdate($obj->due_date), 'day') . ", customer id " . $obj->sid . " " . $obj->name . ", " . ($obj->cid ? "contact id " . $obj->cid . " " . $obj->clastname . " " . $obj->cfirstname . ", " : "") . "email " . $newemail . ", lang " . $outputlangs->defaultlang . ": ";
print "Unpaid invoice ".$obj->ref.", price ".price2num($obj->total_ttc).", due date ".dol_print_date($db->jdate($obj->due_date), 'day').", customer id ".$obj->sid." ".$obj->name.", ".($obj->cid?"contact id ".$obj->cid." ".$obj->clastname." ".$obj->cfirstname.", ":"")."email ".$newemail.", lang ".$outputlangs->defaultlang.": "; if (dol_strlen($newemail))
if (dol_strlen($newemail)) print "qualified."; print "qualified.";
else print "disqualified (no email)."; else
print "\n"; print "disqualified (no email).";
print "\n";
unset($outputlangs); unset($outputlangs);
$total += $obj->total_ttc; $total += $obj->total_ttc;
$i++; $i ++;
} }
// Si il reste des envois en buffer // Si il reste des envois en buffer
if ($foundtoprocess) if ($foundtoprocess) {
{ if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid . '|' . $oldemail])) // Break onto email (new email)
if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) // Break onto email (new email)
{
envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget);
$trackthirdpartiessent[$oldsid.'|'.$oldemail]='contact id '.$oldcid;
}
else
{ {
if ($oldemail != 'none') envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget);
{ $trackthirdpartiessent[$oldsid . '|' . $oldemail] = 'contact id ' . $oldcid;
if (empty($trackthirdpartiessent[$oldsid.'|'.$oldemail])) print "- No email sent for '".$oldtarget."', total: ".$total."\n"; } else {
else print "- No email sent for '".$oldtarget."', total: ".$total." (already sent to ".$trackthirdpartiessent[$oldsid.'|'.$oldemail].")\n"; if ($oldemail != 'none') {
} if (empty($trackthirdpartiessent[$oldsid . '|' . $oldemail]))
} print "- No email sent for '" . $oldtarget . "', total: " . $total . "\n";
} else
} print "- No email sent for '" . $oldtarget . "', total: " . $total . " (already sent to " . $trackthirdpartiessent[$oldsid . '|' . $oldemail] . ")\n";
else }
{ }
print "No unpaid invoices found\n"; }
} } else {
print "No unpaid invoices found\n";
}
exit(0); exit(0);
} else {
dol_print_error($db);
dol_syslog("email_unpaid_invoices_to_customers.php: Error");
exit(- 1);
} }
else
{
dol_print_error($db);
dol_syslog("email_unpaid_invoices_to_customers.php: Error");
exit(-1);
}
/** /**
* Send email * Send email
* *
* @param string $mode Mode (test | confirm) * @param string $mode
* @param string $oldemail Target email * Mode (test | confirm)
* @param string $message Message to send * @param string $oldemail
* @param string $total Total amount of unpayed invoices * Target email
* @param string $userlang Code lang to use for email output. * @param string $message
* @param string $oldtarget Target name * Message to send
* @return int <0 if KO, >0 if OK * @param string $total
* Total amount of unpayed invoices
* @param string $userlang
* Code lang to use for email output.
* @param string $oldtarget
* Target name
* @return int <0 if KO, >0 if OK
*/ */
function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget) function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldtarget)
{ {
global $conf,$langs; global $conf, $langs;
if (getenv('DOL_FORCE_EMAIL_TO')) $oldemail=getenv('DOL_FORCE_EMAIL_TO'); if (getenv('DOL_FORCE_EMAIL_TO'))
$oldemail = getenv('DOL_FORCE_EMAIL_TO');
$newlangs=new Translate('', $conf); $newlangs = new Translate('', $conf);
$newlangs->setDefaultLang(empty($userlang)?(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT):$userlang); $newlangs->setDefaultLang(empty($userlang) ? (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT) : $userlang);
$newlangs->load("main"); $newlangs->load("main");
$newlangs->load("bills"); $newlangs->load("bills");
$subject = (empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_SUBJECT)?$newlangs->trans("ListOfYourUnpaidInvoices"):$conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_SUBJECT); $subject = (empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_SUBJECT) ? $newlangs->trans("ListOfYourUnpaidInvoices") : $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_SUBJECT);
$sendto = $oldemail; $sendto = $oldemail;
$from = $conf->global->MAIN_MAIL_EMAIL_FROM; $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
$errorsto = $conf->global->MAIN_MAIL_ERRORS_TO; $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
$msgishtml = -1; $msgishtml = - 1;
print "- Send email to '".$oldtarget."' (".$oldemail."), total: ".$total."\n"; print "- Send email to '" . $oldtarget . "' (" . $oldemail . "), total: " . $total . "\n";
dol_syslog("email_unpaid_invoices_to_customers.php: send mail to ".$oldemail); dol_syslog("email_unpaid_invoices_to_customers.php: send mail to " . $oldemail);
$usehtml=0; $usehtml = 0;
if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER)) $usehtml+=1; if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER))
if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER)) $usehtml+=1; $usehtml += 1;
if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER))
$usehtml += 1;
$allmessage=''; $allmessage = '';
if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER)) if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER)) {
{ $allmessage .= $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER;
$allmessage.=$conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER; } else {
} $allmessage .= "Dear customer" . ($usehtml ? "<br>\n" : "\n") . ($usehtml ? "<br>\n" : "\n");
else $allmessage .= "Please, find a summary of the bills with pending payments from you." . ($usehtml ? "<br>\n" : "\n") . ($usehtml ? "<br>\n" : "\n");
{ $allmessage .= "Note: This list contains only unpaid invoices." . ($usehtml ? "<br>\n" : "\n");
$allmessage.= "Dear customer".($usehtml?"<br>\n":"\n").($usehtml?"<br>\n":"\n"); }
$allmessage.= "Please, find a summary of the bills with pending payments from you.".($usehtml?"<br>\n":"\n").($usehtml?"<br>\n":"\n"); $allmessage .= $message . ($usehtml ? "<br>\n" : "\n");
$allmessage.= "Note: This list contains only unpaid invoices.".($usehtml?"<br>\n":"\n"); $allmessage .= $langs->trans("Total") . " = " . price($total, 0, $userlang, 0, 0, - 1, $conf->currency) . ($usehtml ? "<br>\n" : "\n");
} if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER)) {
$allmessage.= $message.($usehtml?"<br>\n":"\n"); $allmessage .= $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER;
$allmessage.= $langs->trans("Total")." = ".price($total, 0, $userlang, 0, 0, -1, $conf->currency).($usehtml?"<br>\n":"\n"); if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER))
if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER)) $usehtml += 1;
{ }
$allmessage.=$conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER;
if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER)) $usehtml+=1;
}
$mail = new CMailFile( $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
$subject,
$sendto,
$from,
$allmessage,
array(),
array(),
array(),
'',
'',
0,
$msgishtml
);
$mail->errors_to = $errorsto; $mail->errors_to = $errorsto;
// Send or not email // Send or not email
if ($mode == 'confirm') if ($mode == 'confirm') {
{ $result = $mail->sendfile();
$result=$mail->sendfile(); if (! $result) {
if (! $result) print "Error sending email " . $mail->error . "\n";
{ dol_syslog("Error sending email " . $mail->error . "\n");
print "Error sending email ".$mail->error."\n"; }
dol_syslog("Error sending email ".$mail->error."\n"); } else {
} print "No email sent (test mode)\n";
} dol_syslog("No email sent (test mode)");
else $mail->dump_mail();
{ $result = 1;
print "No email sent (test mode)\n"; }
dol_syslog("No email sent (test mode)");
$mail->dump_mail();
$result=1;
}
unset($newlangs); unset($newlangs);
if ($result) if ($result) {
{ return 1;
return 1; } else {
} return - 1;
else }
{
return -1;
}
} }

View File

@ -1,9 +1,9 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/* /*
* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2013 Juanjo Menent <jmenent@2byte.es> * Copyright (C) 2013 Juanjo Menent <jmenent@2byte.es>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -12,7 +12,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -20,260 +20,235 @@
*/ */
/** /**
* \file scripts/invoices/email_unpaid_invoices_to_representatives.php * \file scripts/invoices/email_unpaid_invoices_to_representatives.php
* \ingroup facture * \ingroup facture
* \brief Script to send a mail to dolibarr users linked to companies with unpaid invoices * \brief Script to send a mail to dolibarr users linked to companies with unpaid invoices
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test si mode batch // Test si mode batch
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
if (! isset($argv[1]) || ! $argv[1] || ! in_array($argv[1], array('test','confirm'))) if (! isset($argv[1]) || ! $argv[1] || ! in_array($argv[1], array('test','confirm'))) {
{
print "Usage: $script_file (test|confirm) [delay]\n"; print "Usage: $script_file (test|confirm) [delay]\n";
print "\n"; print "\n";
print "Send an email to users to remind all unpaid customer invoices user is sale representative for.\n"; print "Send an email to users to remind all unpaid customer invoices user is sale representative for.\n";
print "If you choose 'test' mode, no emails are sent.\n"; print "If you choose 'test' mode, no emails are sent.\n";
print "If you add a delay (nb of days), only invoice with due date < today + delay are included.\n"; print "If you add a delay (nb of days), only invoice with due date < today + delay are included.\n";
exit(-1); exit(- 1);
} }
$mode=$argv[1]; $mode = $argv[1];
require $path . "../../htdocs/master.inc.php";
require $path."../../htdocs/master.inc.php"; require_once DOL_DOCUMENT_ROOT . "/core/class/CMailFile.class.php";
require_once DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php";
$langs->load('main'); $langs->load('main');
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
$now=dol_now('tzserver'); $now = dol_now('tzserver');
$duration_value=isset($argv[2])?$argv[2]:'none'; $duration_value = isset($argv[2]) ? $argv[2] : 'none';
print $script_file." launched with mode ".$mode." default lang=".$langs->defaultlang.(is_numeric($duration_value)?" delay=".$duration_value:"")."\n"; print $script_file . " launched with mode " . $mode . " default lang=" . $langs->defaultlang . (is_numeric($duration_value) ? " delay=" . $duration_value : "") . "\n";
if ($mode != 'confirm') $conf->global->MAIN_DISABLE_ALL_MAILS=1; if ($mode != 'confirm')
$conf->global->MAIN_DISABLE_ALL_MAILS = 1;
$sql = "SELECT f.ref, f.total_ttc, f.date_lim_reglement as due_date, s.nom as name, s.email, s.default_lang,"; $sql = "SELECT f.ref, f.total_ttc, f.date_lim_reglement as due_date, s.nom as name, s.email, s.default_lang,";
$sql.= " u.rowid as uid, u.lastname, u.firstname, u.email, u.lang"; $sql .= " u.rowid as uid, u.lastname, u.firstname, u.email, u.lang";
$sql .= " FROM ".MAIN_DB_PREFIX."facture as f"; $sql .= " FROM " . MAIN_DB_PREFIX . "facture as f";
$sql .= " , ".MAIN_DB_PREFIX."societe as s"; $sql .= " , " . MAIN_DB_PREFIX . "societe as s";
$sql .= " , ".MAIN_DB_PREFIX."societe_commerciaux as sc"; $sql .= " , " . MAIN_DB_PREFIX . "societe_commerciaux as sc";
$sql .= " , ".MAIN_DB_PREFIX."user as u"; $sql .= " , " . MAIN_DB_PREFIX . "user as u";
$sql .= " WHERE f.fk_statut = 1 AND f.paye = 0"; $sql .= " WHERE f.fk_statut = 1 AND f.paye = 0";
$sql .= " AND f.fk_soc = s.rowid"; $sql .= " AND f.fk_soc = s.rowid";
if (is_numeric($duration_value)) $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_time_plus_duree($now, $duration_value, "d"))."'"; if (is_numeric($duration_value))
$sql .= " AND f.date_lim_reglement < '" . $db->idate(dol_time_plus_duree($now, $duration_value, "d")) . "'";
$sql .= " AND sc.fk_soc = s.rowid"; $sql .= " AND sc.fk_soc = s.rowid";
$sql .= " AND sc.fk_user = u.rowid"; $sql .= " AND sc.fk_user = u.rowid";
$sql .= " ORDER BY u.email ASC, s.rowid ASC, f.ref ASC"; // Order by email to allow one message per email $sql .= " ORDER BY u.email ASC, s.rowid ASC, f.ref ASC"; // Order by email to allow one message per email
//print $sql; // print $sql;
$resql=$db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{ $num = $db->num_rows($resql);
$num = $db->num_rows($resql); $i = 0;
$i = 0; $oldemail = 'none';
$oldemail = 'none'; $olduid = 0; $oldlang=''; $olduid = 0;
$total = 0; $foundtoprocess = 0; $oldlang = '';
print "We found ".$num." couples (unpayed validated invoice - sale representative) qualified\n"; $total = 0;
dol_syslog("We found ".$num." couples (unpayed validated invoice - sale representative) qualified"); $foundtoprocess = 0;
$message=''; print "We found " . $num . " couples (unpayed validated invoice - sale representative) qualified\n";
dol_syslog("We found " . $num . " couples (unpayed validated invoice - sale representative) qualified");
$message = '';
if ($num) if ($num) {
{ while ($i < $num) {
while ($i < $num) $obj = $db->fetch_object($resql);
{
$obj = $db->fetch_object($resql);
if (($obj->email <> $oldemail || $obj->uid <> $olduid) || $oldemail == 'none') if (($obj->email != $oldemail || $obj->uid != $olduid) || $oldemail == 'none') {
{ // Break onto sales representative (new email or uid)
// Break onto sales representative (new email or uid) if (dol_strlen($oldemail) && $oldemail != 'none') {
if (dol_strlen($oldemail) && $oldemail != 'none') envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative);
{ } else {
envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative); if ($oldemail != 'none')
} print "- No email sent for " . $oldsalerepresentative . ", total: " . $total . "\n";
else }
{ $oldemail = $obj->email;
if ($oldemail != 'none') print "- No email sent for ".$oldsalerepresentative.", total: ".$total."\n"; $olduid = $obj->uid;
} $oldlang = $obj->lang;
$oldemail = $obj->email; $oldsalerepresentative = dolGetFirstLastname($obj->firstname, $obj->lastname);
$olduid = $obj->uid; $message = '';
$oldlang = $obj->lang; $total = 0;
$oldsalerepresentative=dolGetFirstLastname($obj->firstname, $obj->lastname); $foundtoprocess = 0;
$message = ''; $salerepresentative = dolGetFirstLastname($obj->firstname, $obj->lastname);
$total = 0; if (empty($obj->email))
$foundtoprocess = 0; print "Warning: Sale representative " . $salerepresentative . " has no email. Notice disabled.\n";
$salerepresentative=dolGetFirstLastname($obj->firstname, $obj->lastname); }
if (empty($obj->email)) print "Warning: Sale representative ".$salerepresentative." has no email. Notice disabled.\n";
}
// Define line content // Define line content
$outputlangs=new Translate('', $conf); $outputlangs = new Translate('', $conf);
$outputlangs->setDefaultLang(empty($obj->lang)?$langs->defaultlang:$obj->lang); // By default language of sale representative $outputlangs->setDefaultLang(empty($obj->lang) ? $langs->defaultlang : $obj->lang); // By default language of sale representative
// Load translation files required by the page // Load translation files required by the page
$outputlangs->loadLangs(array("main", "bills")); $outputlangs->loadLangs(array("main","bills"));
if (dol_strlen($obj->email)) if (dol_strlen($obj->email)) {
{ $message .= $outputlangs->trans("Invoice") . " " . $obj->ref . " : " . price($obj->total_ttc, 0, $outputlangs, 0, 0, - 1, $conf->currency) . " : " . $obj->name . "\n";
$message .= $outputlangs->trans("Invoice")." ".$obj->ref." : ".price($obj->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency)." : ".$obj->name."\n"; dol_syslog("email_unpaid_invoices_to_representatives.php: " . $obj->email);
dol_syslog("email_unpaid_invoices_to_representatives.php: ".$obj->email); $foundtoprocess ++;
$foundtoprocess++; }
} print "Unpaid invoice " . $obj->ref . ", price " . price2num($obj->total_ttc) . ", due date " . dol_print_date($db->jdate($obj->due_date), 'day') . " (linked to company " . $obj->name . ", sale representative " . dolGetFirstLastname($obj->firstname, $obj->lastname) . ", email " . $obj->email . ", lang " . $outputlangs->defaultlang . "): ";
print "Unpaid invoice ".$obj->ref.", price ".price2num($obj->total_ttc).", due date ".dol_print_date($db->jdate($obj->due_date), 'day')." (linked to company ".$obj->name.", sale representative ".dolGetFirstLastname($obj->firstname, $obj->lastname).", email ".$obj->email.", lang ".$outputlangs->defaultlang."): "; if (dol_strlen($obj->email))
if (dol_strlen($obj->email)) print "qualified."; print "qualified.";
else print "disqualified (no email)."; else
print "disqualified (no email).";
print "\n"; print "\n";
unset($outputlangs); unset($outputlangs);
$total += $obj->total_ttc; $total += $obj->total_ttc;
$i++; $i ++;
} }
// Si il reste des envois en buffer // Si il reste des envois en buffer
if ($foundtoprocess) if ($foundtoprocess) {
{ if (dol_strlen($oldemail) && $oldemail != 'none') // Break onto email (new email)
if (dol_strlen($oldemail) && $oldemail != 'none') // Break onto email (new email)
{
envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative);
}
else
{ {
if ($oldemail != 'none') print "- No email sent for ".$oldsalerepresentative.", total: ".$total."\n"; envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative);
} } else {
} if ($oldemail != 'none')
} print "- No email sent for " . $oldsalerepresentative . ", total: " . $total . "\n";
else }
{ }
print "No unpaid invoices (for companies linked to a particular commercial dolibarr user) found\n"; } else {
} print "No unpaid invoices (for companies linked to a particular commercial dolibarr user) found\n";
}
exit(0); exit(0);
} else {
dol_print_error($db);
dol_syslog("email_unpaid_invoices_to_representatives.php: Error");
exit(- 1);
} }
else
{
dol_print_error($db);
dol_syslog("email_unpaid_invoices_to_representatives.php: Error");
exit(-1);
}
/** /**
* Send email * Send email
* *
* @param string $mode Mode (test | confirm) * @param string $mode
* @param string $oldemail Old email * Mode (test | confirm)
* @param string $message Message to send * @param string $oldemail
* @param string $total Total amount of unpayed invoices * Old email
* @param string $userlang Code lang to use for email output. * @param string $message
* @param string $oldsalerepresentative Old sale representative * Message to send
* @return int <0 if KO, >0 if OK * @param string $total
* Total amount of unpayed invoices
* @param string $userlang
* Code lang to use for email output.
* @param string $oldsalerepresentative
* Old sale representative
* @return int <0 if KO, >0 if OK
*/ */
function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldsalerepresentative) function envoi_mail($mode, $oldemail, $message, $total, $userlang, $oldsalerepresentative)
{ {
global $conf,$langs; global $conf, $langs;
if (getenv('DOL_FORCE_EMAIL_TO')) $oldemail=getenv('DOL_FORCE_EMAIL_TO'); if (getenv('DOL_FORCE_EMAIL_TO'))
$oldemail = getenv('DOL_FORCE_EMAIL_TO');
$newlangs=new Translate('', $conf); $newlangs = new Translate('', $conf);
$newlangs->setDefaultLang(empty($userlang)?(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT):$userlang); $newlangs->setDefaultLang(empty($userlang) ? (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT) : $userlang);
$newlangs->load("main"); $newlangs->load("main");
$newlangs->load("bills"); $newlangs->load("bills");
$subject = (empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_SUBJECT)?$newlangs->trans("ListOfYourUnpaidInvoices"):$conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_SUBJECT); $subject = (empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_SUBJECT) ? $newlangs->trans("ListOfYourUnpaidInvoices") : $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_SUBJECT);
$sendto = $oldemail; $sendto = $oldemail;
$from = $conf->global->MAIN_MAIL_EMAIL_FROM; $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
$errorsto = $conf->global->MAIN_MAIL_ERRORS_TO; $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
$msgishtml = -1; $msgishtml = - 1;
print "- Send email for ".$oldsalerepresentative." (".$oldemail."), total: ".$total."\n"; print "- Send email for " . $oldsalerepresentative . " (" . $oldemail . "), total: " . $total . "\n";
dol_syslog("email_unpaid_invoices_to_representatives.php: send mail to ".$oldemail); dol_syslog("email_unpaid_invoices_to_representatives.php: send mail to " . $oldemail);
$usehtml=0; $usehtml = 0;
if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER)) $usehtml+=1; if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER))
if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER)) $usehtml+=1; $usehtml += 1;
if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER))
$usehtml += 1;
$allmessage=''; $allmessage = '';
if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER)) if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER)) {
{ $allmessage .= $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER;
$allmessage.=$conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER; } else {
} $allmessage .= $newlangs->transnoentities("ListOfYourUnpaidInvoices") . ($usehtml ? "<br>\n" : "\n") . ($usehtml ? "<br>\n" : "\n");
else $allmessage .= $newlangs->transnoentities("NoteListOfYourUnpaidInvoices") . ($usehtml ? "<br>\n" : "\n");
{ }
$allmessage.= $newlangs->transnoentities("ListOfYourUnpaidInvoices").($usehtml?"<br>\n":"\n").($usehtml?"<br>\n":"\n"); $allmessage .= $message . ($usehtml ? "<br>\n" : "\n");
$allmessage.= $newlangs->transnoentities("NoteListOfYourUnpaidInvoices").($usehtml?"<br>\n":"\n"); $allmessage .= $langs->trans("Total") . " = " . price($total, 0, $newlangs, 0, 0, - 1, $conf->currency) . ($usehtml ? "<br>\n" : "\n");
} if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER)) {
$allmessage.= $message.($usehtml?"<br>\n":"\n"); $allmessage .= $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER;
$allmessage.= $langs->trans("Total")." = ".price($total, 0, $newlangs, 0, 0, -1, $conf->currency).($usehtml?"<br>\n":"\n"); if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER))
if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER)) $usehtml += 1;
{ }
$allmessage.=$conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER;
if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER)) $usehtml+=1;
}
$mail = new CMailFile( $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
$subject,
$sendto,
$from,
$allmessage,
array(),
array(),
array(),
'',
'',
0,
$msgishtml
);
$mail->errors_to = $errorsto; $mail->errors_to = $errorsto;
// Send or not email // Send or not email
if ($mode == 'confirm') if ($mode == 'confirm') {
{ $result = $mail->sendfile();
$result=$mail->sendfile(); if (! $result) {
if (! $result) print "Error sending email " . $mail->error . "\n";
{ dol_syslog("Error sending email " . $mail->error . "\n");
print "Error sending email ".$mail->error."\n"; }
dol_syslog("Error sending email ".$mail->error."\n"); } else {
} print "No email sent (test mode)\n";
} dol_syslog("No email sent (test mode)");
else $mail->dump_mail();
{ $result = 1;
print "No email sent (test mode)\n"; }
dol_syslog("No email sent (test mode)");
$mail->dump_mail();
$result=1;
}
if ($result) if ($result) {
{ return 1;
return 1; } else {
} return - 1;
else }
{
return -1;
}
} }

View File

@ -1,7 +1,7 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/* /*
* Copyright (C) 2009-2012 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2009-2012 Laurent Destailleur <eldy@users.sourceforge.net>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -10,7 +10,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -18,251 +18,217 @@
*/ */
/** /**
* \file scripts/invoices/rebuild_merge_pdf.php * \file scripts/invoices/rebuild_merge_pdf.php
* \ingroup facture * \ingroup facture
* \brief Script to rebuild PDF and merge PDF files into one * \brief Script to rebuild PDF and merge PDF files into one
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
// Include Dolibarr environment // Include Dolibarr environment
require_once $path."../../htdocs/master.inc.php"; require_once $path . "../../htdocs/master.inc.php";
// After this $db is an opened handler to database. We close it at end of file. // After this $db is an opened handler to database. We close it at end of file.
require_once DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php"; require_once DOL_DOCUMENT_ROOT . "/compta/facture/class/facture.class.php";
require_once DOL_DOCUMENT_ROOT."/core/modules/facture/modules_facture.php"; require_once DOL_DOCUMENT_ROOT . "/core/modules/facture/modules_facture.php";
require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php"; require_once DOL_DOCUMENT_ROOT . "/core/lib/date.lib.php";
require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice2.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice2.lib.php';
// Load main language strings // Load main language strings
$langs->load("main"); $langs->load("main");
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
// Check parameters // Check parameters
if (! isset($argv[1])) if (! isset($argv[1])) {
{
usage(); usage();
exit(-1); exit(- 1);
} }
$diroutputpdf=$conf->facture->dir_output . '/temp'; $diroutputpdf = $conf->facture->dir_output . '/temp';
$newlangid='en_EN'; // To force a new lang id $newlangid = 'en_EN'; // To force a new lang id
$filter=array(); $filter = array();
$regenerate=''; // Ask regenerate (contains name of model to use) $regenerate = ''; // Ask regenerate (contains name of model to use)
$option=''; $option = '';
$fileprefix='mergedpdf'; $fileprefix = 'mergedpdf';
foreach ($argv as $key => $value) foreach ($argv as $key => $value) {
{ $found = false;
$found=false;
// Define options // Define options
if (preg_match('/^lang=/i', $value)) if (preg_match('/^lang=/i', $value)) {
{ $found = true;
$found=true; $valarray = explode('=', $value);
$valarray=explode('=', $value); $newlangid = $valarray[1];
$newlangid=$valarray[1]; print 'Use language ' . $newlangid . ".\n";
print 'Use language '.$newlangid.".\n";
} }
if (preg_match('/^prefix=/i', $value)) if (preg_match('/^prefix=/i', $value)) {
{ $found = true;
$found=true; $valarray = explode('=', $value);
$valarray=explode('=', $value); $fileprefix = $valarray[1];
$fileprefix=$valarray[1]; print 'Use prefix for filename ' . $fileprefix . ".\n";
print 'Use prefix for filename '.$fileprefix.".\n";
} }
if (preg_match('/^regenerate=(.*)/i', $value, $reg)) if (preg_match('/^regenerate=(.*)/i', $value, $reg)) {
{ if (! in_array($reg[1], array('','0','no'))) {
if (! in_array($reg[1], array('','0','no'))) $found = true;
{ $regenerate = $reg[1];
$found=true; print 'Regeneration of PDF is requested with template ' . $regenerate . "\n";
$regenerate=$reg[1];
print 'Regeneration of PDF is requested with template '.$regenerate."\n";
}
}
if ($value == 'filter=all')
{
$found=true;
$option.=(empty($option)?'':'_').'all';
$filter[]='all';
print 'Rebuild PDF for all invoices'."\n";
}
if ($value == 'filter=date')
{
$found=true;
$option.=(empty($option)?'':'_').'date_'.$argv[$key+1].'_'.$argv[$key+2];
$filter[]='date';
$dateafterdate=dol_stringtotime($argv[$key+1]);
$datebeforedate=dol_stringtotime($argv[$key+2]);
print 'Rebuild PDF for invoices validated between '.dol_print_date($dateafterdate, 'day', 'gmt')." and ".dol_print_date($datebeforedate, 'day', 'gmt').".\n";
}
if ($value == 'filter=payments')
{
$found=true;
$option.=(empty($option)?'':'_').'payments_'.$argv[$key+1].'_'.$argv[$key+2];
$filter[]='payments';
$paymentdateafter=dol_stringtotime($argv[$key+1].'000000');
$paymentdatebefore=dol_stringtotime($argv[$key+2].'235959');
if (empty($paymentdateafter) || empty($paymentdatebefore))
{
print 'Error: Bad date format or value'."\n";
exit(-1);
} }
print 'Rebuild PDF for invoices with at least one payment between '.dol_print_date($paymentdateafter, 'day', 'gmt')." and ".dol_print_date($paymentdatebefore, 'day', 'gmt').".\n";
} }
if ($value == 'filter=nopayment') if ($value == 'filter=all') {
{ $found = true;
$found=true; $option .= (empty($option) ? '' : '_') . 'all';
$option.=(empty($option)?'':'_').'nopayment'; $filter[] = 'all';
$filter[]='nopayment';
print 'Rebuild PDF for invoices with no payment done yet.'."\n"; print 'Rebuild PDF for all invoices' . "\n";
} }
if ($value == 'filter=bank') if ($value == 'filter=date') {
{ $found = true;
$found=true; $option .= (empty($option) ? '' : '_') . 'date_' . $argv[$key + 1] . '_' . $argv[$key + 2];
$option.=(empty($option)?'':'_').'bank_'.$argv[$key+1]; $filter[] = 'date';
$filter[]='bank';
$paymentonbankref=$argv[$key+1]; $dateafterdate = dol_stringtotime($argv[$key + 1]);
$bankaccount=new Account($db); $datebeforedate = dol_stringtotime($argv[$key + 2]);
$result=$bankaccount->fetch(0, $paymentonbankref); print 'Rebuild PDF for invoices validated between ' . dol_print_date($dateafterdate, 'day', 'gmt') . " and " . dol_print_date($datebeforedate, 'day', 'gmt') . ".\n";
if ($result <= 0) }
{
print 'Error: Bank account with ref "'.$paymentonbankref.'" not found'."\n"; if ($value == 'filter=payments') {
exit(-1); $found = true;
$option .= (empty($option) ? '' : '_') . 'payments_' . $argv[$key + 1] . '_' . $argv[$key + 2];
$filter[] = 'payments';
$paymentdateafter = dol_stringtotime($argv[$key + 1] . '000000');
$paymentdatebefore = dol_stringtotime($argv[$key + 2] . '235959');
if (empty($paymentdateafter) || empty($paymentdatebefore)) {
print 'Error: Bad date format or value' . "\n";
exit(- 1);
} }
$paymentonbankid=$bankaccount->id; print 'Rebuild PDF for invoices with at least one payment between ' . dol_print_date($paymentdateafter, 'day', 'gmt') . " and " . dol_print_date($paymentdatebefore, 'day', 'gmt') . ".\n";
print 'Rebuild PDF for invoices with at least one payment on financial account '.$bankaccount->ref."\n";
} }
if ($value == 'filter=nodeposit') if ($value == 'filter=nopayment') {
{ $found = true;
$found=true; $option .= (empty($option) ? '' : '_') . 'nopayment';
$option.=(empty($option)?'':'_').'nodeposit'; $filter[] = 'nopayment';
$filter[]='nodeposit';
print 'Exclude deposit invoices'."\n"; print 'Rebuild PDF for invoices with no payment done yet.' . "\n";
} }
if ($value == 'filter=noreplacement')
{
$found=true;
$option.=(empty($option)?'':'_').'noreplacement';
$filter[]='noreplacement';
print 'Exclude replacement invoices'."\n"; if ($value == 'filter=bank') {
} $found = true;
if ($value == 'filter=nocreditnote') $option .= (empty($option) ? '' : '_') . 'bank_' . $argv[$key + 1];
{ $filter[] = 'bank';
$found=true;
$option.=(empty($option)?'':'_').'nocreditnote';
$filter[]='nocreditnote';
print 'Exclude credit note invoices'."\n"; $paymentonbankref = $argv[$key + 1];
} $bankaccount = new Account($db);
$result = $bankaccount->fetch(0, $paymentonbankref);
if ($result <= 0) {
print 'Error: Bank account with ref "' . $paymentonbankref . '" not found' . "\n";
exit(- 1);
}
$paymentonbankid = $bankaccount->id;
print 'Rebuild PDF for invoices with at least one payment on financial account ' . $bankaccount->ref . "\n";
}
if ($value == 'filter=excludethirdparties') if ($value == 'filter=nodeposit') {
{ $found = true;
$found=true; $option .= (empty($option) ? '' : '_') . 'nodeposit';
$filter[]='excludethirdparties'; $filter[] = 'nodeposit';
$thirdpartiesid=explode(',', $argv[$key+1]); print 'Exclude deposit invoices' . "\n";
print 'Exclude thirdparties with id in list ('.join(',', $thirdpartiesid).").\n"; }
if ($value == 'filter=noreplacement') {
$found = true;
$option .= (empty($option) ? '' : '_') . 'noreplacement';
$filter[] = 'noreplacement';
$option.=(empty($option)?'':'_').'excludethirdparties'.join('-', $thirdpartiesid); print 'Exclude replacement invoices' . "\n";
} }
if ($value == 'filter=onlythirdparties') if ($value == 'filter=nocreditnote') {
{ $found = true;
$found=true; $option .= (empty($option) ? '' : '_') . 'nocreditnote';
$filter[]='onlythirdparties'; $filter[] = 'nocreditnote';
$thirdpartiesid=explode(',', $argv[$key+1]); print 'Exclude credit note invoices' . "\n";
print 'Only thirdparties with id in list ('.join(',', $thirdpartiesid).").\n"; }
$option.=(empty($option)?'':'_').'onlythirdparty'.join('-', $thirdpartiesid); if ($value == 'filter=excludethirdparties') {
} $found = true;
$filter[] = 'excludethirdparties';
if (! $found && preg_match('/filter=/i', $value)) $thirdpartiesid = explode(',', $argv[$key + 1]);
{ print 'Exclude thirdparties with id in list (' . join(',', $thirdpartiesid) . ").\n";
$option .= (empty($option) ? '' : '_') . 'excludethirdparties' . join('-', $thirdpartiesid);
}
if ($value == 'filter=onlythirdparties') {
$found = true;
$filter[] = 'onlythirdparties';
$thirdpartiesid = explode(',', $argv[$key + 1]);
print 'Only thirdparties with id in list (' . join(',', $thirdpartiesid) . ").\n";
$option .= (empty($option) ? '' : '_') . 'onlythirdparty' . join('-', $thirdpartiesid);
}
if (! $found && preg_match('/filter=/i', $value)) {
usage(); usage();
exit(-1); exit(- 1);
} }
} }
// Check if an option and a filter has been provided // Check if an option and a filter has been provided
if (empty($option) && count($filter) <= 0) if (empty($option) && count($filter) <= 0) {
{
usage(); usage();
exit(-1); exit(- 1);
} }
// Check if there is no uncompatible choice // Check if there is no uncompatible choice
if (in_array('payments', $filter) && in_array('nopayment', $filter)) if (in_array('payments', $filter) && in_array('nopayment', $filter)) {
{
usage(); usage();
exit(-1); exit(- 1);
} }
if (in_array('bank', $filter) && in_array('nopayment', $filter)) if (in_array('bank', $filter) && in_array('nopayment', $filter)) {
{
usage(); usage();
exit(-1); exit(- 1);
} }
// Define SQL and SQL request to select invoices // Define SQL and SQL request to select invoices
// Use $filter, $dateafterdate, datebeforedate, $paymentdateafter, $paymentdatebefore // Use $filter, $dateafterdate, datebeforedate, $paymentdateafter, $paymentdatebefore
$result=rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filter, $dateafterdate, $datebeforedate, $paymentdateafter, $paymentdatebefore, 1, $regenerate, $option, $paymentonbankid, $thirdpartiesid, $fileprefix); $result = rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filter, $dateafterdate, $datebeforedate, $paymentdateafter, $paymentdatebefore, 1, $regenerate, $option, $paymentonbankid, $thirdpartiesid, $fileprefix);
// -------------------- END OF YOUR CODE -------------------- // -------------------- END OF YOUR CODE --------------------
if ($result >= 0) if ($result >= 0) {
{ $error = 0;
$error=0; print '--- end ok' . "\n";
print '--- end ok'."\n"; } else {
} $error = $result;
else print '--- end error code=' . $error . "\n";
{
$error=$result;
print '--- end error code='.$error."\n";
} }
$db->close(); $db->close();
exit($error); exit($error);
/** /**
* Show usage of script * Show usage of script
* *
@ -272,29 +238,29 @@ function usage()
{ {
global $script_file; global $script_file;
print "Rebuild PDF files for some invoices and merge PDF files into one.\n"; print "Rebuild PDF files for some invoices and merge PDF files into one.\n";
print "\n"; print "\n";
print "To build/merge PDF for invoices in a date range:\n"; print "To build/merge PDF for invoices in a date range:\n";
print "Usage: ".$script_file." filter=date dateafter datebefore\n"; print "Usage: " . $script_file . " filter=date dateafter datebefore\n";
print "To build/merge PDF for invoices with at least one payment in a date range:\n"; print "To build/merge PDF for invoices with at least one payment in a date range:\n";
print "Usage: ".$script_file." filter=payments dateafter datebefore\n"; print "Usage: " . $script_file . " filter=payments dateafter datebefore\n";
print "To build/merge PDF for invoices with at least one payment onto a bank account:\n"; print "To build/merge PDF for invoices with at least one payment onto a bank account:\n";
print "Usage: ".$script_file." filter=bank bankref\n"; print "Usage: " . $script_file . " filter=bank bankref\n";
print "To build/merge PDF for all invoices, use filter=all\n"; print "To build/merge PDF for all invoices, use filter=all\n";
print "Usage: ".$script_file." filter=all\n"; print "Usage: " . $script_file . " filter=all\n";
print "To build/merge PDF for invoices with no payments, use filter=nopayment\n"; print "To build/merge PDF for invoices with no payments, use filter=nopayment\n";
print "Usage: ".$script_file." filter=nopayment\n"; print "Usage: " . $script_file . " filter=nopayment\n";
print "To exclude credit notes, use filter=nocreditnote\n"; print "To exclude credit notes, use filter=nocreditnote\n";
print "To exclude replacement invoices, use filter=noreplacement\n"; print "To exclude replacement invoices, use filter=noreplacement\n";
print "To exclude deposit invoices, use filter=nodeposit\n"; print "To exclude deposit invoices, use filter=nodeposit\n";
print "To exclude some thirdparties, use filter=excludethirdparties id1,id2...\n"; print "To exclude some thirdparties, use filter=excludethirdparties id1,id2...\n";
print "To limit to some thirdparties, use filter=onlythirdparties id1,id2...\n"; print "To limit to some thirdparties, use filter=onlythirdparties id1,id2...\n";
print "To regenerate existing PDF, use regenerate=templatename\n"; print "To regenerate existing PDF, use regenerate=templatename\n";
print "To generate invoices in a language, use lang=xx_XX\n"; print "To generate invoices in a language, use lang=xx_XX\n";
print "To set prefix of generated file name, use prefix=myfileprefix\n"; print "To set prefix of generated file name, use prefix=myfileprefix\n";
print "\n"; print "\n";
print "Example: ".$script_file." filter=payments 20080101 20081231 lang=fr_FR regenerate=crabe\n"; print "Example: " . $script_file . " filter=payments 20080101 20081231 lang=fr_FR regenerate=crabe\n";
print "Example: ".$script_file." filter=all lang=en_US\n"; print "Example: " . $script_file . " filter=all lang=en_US\n";
print "\n"; print "\n";
print "Note that some filters can be cumulated.\n"; print "Note that some filters can be cumulated.\n";
} }

View File

@ -1,8 +1,8 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/** /**
* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2006-2008 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2006-2008 Laurent Destailleur <eldy@users.sourceforge.net>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -11,7 +11,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -19,74 +19,71 @@
*/ */
/** /**
* \file scripts/members/sync_members_dolibarr2ldap.php * \file scripts/members/sync_members_dolibarr2ldap.php
* \ingroup ldap member * \ingroup ldap member
* \brief Script de mise a jour des adherents dans LDAP depuis base Dolibarr * \brief Script de mise a jour des adherents dans LDAP depuis base Dolibarr
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
require_once $path."../../htdocs/master.inc.php"; require_once $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php"; require_once DOL_DOCUMENT_ROOT . "/core/class/ldap.class.php";
require_once DOL_DOCUMENT_ROOT."/adherents/class/adherent.class.php"; require_once DOL_DOCUMENT_ROOT . "/adherents/class/adherent.class.php";
$langs->load("main"); $langs->load("main");
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
$confirmed=0; $confirmed = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
if (! isset($argv[1]) || ! $argv[1]) { if (! isset($argv[1]) || ! $argv[1]) {
print "Usage: $script_file now [-y]\n"; print "Usage: $script_file now [-y]\n";
exit(-1); exit(- 1);
} }
foreach($argv as $key => $val) foreach ($argv as $key => $val) {
{ if (preg_match('/-y$/', $val, $reg))
if (preg_match('/-y$/', $val, $reg)) $confirmed=1; $confirmed = 1;
} }
$now=$argv[1]; $now = $argv[1];
print "Mails sending disabled (useless in batch mode)\n"; print "Mails sending disabled (useless in batch mode)\n";
$conf->global->MAIN_DISABLE_ALL_MAILS=1; // On bloque les mails $conf->global->MAIN_DISABLE_ALL_MAILS = 1; // On bloque les mails
print "\n"; print "\n";
print "----- Synchronize all records from Dolibarr database:\n"; print "----- Synchronize all records from Dolibarr database:\n";
print "type=".$conf->db->type."\n"; print "type=" . $conf->db->type . "\n";
print "host=".$conf->db->host."\n"; print "host=" . $conf->db->host . "\n";
print "port=".$conf->db->port."\n"; print "port=" . $conf->db->port . "\n";
print "login=".$conf->db->user."\n"; print "login=" . $conf->db->user . "\n";
//print "pass=".preg_replace('/./i','*',$conf->db->password)."\n"; // Not defined for security reasons // print "pass=".preg_replace('/./i','*',$conf->db->password)."\n"; // Not defined for security reasons
print "database=".$conf->db->name."\n"; print "database=" . $conf->db->name . "\n";
print "\n"; print "\n";
print "----- To LDAP database:\n"; print "----- To LDAP database:\n";
print "host=".$conf->global->LDAP_SERVER_HOST."\n"; print "host=" . $conf->global->LDAP_SERVER_HOST . "\n";
print "port=".$conf->global->LDAP_SERVER_PORT."\n"; print "port=" . $conf->global->LDAP_SERVER_PORT . "\n";
print "login=".$conf->global->LDAP_ADMIN_DN."\n"; print "login=" . $conf->global->LDAP_ADMIN_DN . "\n";
print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n"; print "pass=" . preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS) . "\n";
print "DN target=".$conf->global->LDAP_MEMBER_DN."\n"; print "DN target=" . $conf->global->LDAP_MEMBER_DN . "\n";
print "\n"; print "\n";
if (! $confirmed) if (! $confirmed) {
{
print "Press a key to confirm...\n"; print "Press a key to confirm...\n";
$input = trim(fgets(STDIN)); $input = trim(fgets(STDIN));
print "Warning, this operation may result in data loss if it failed.\n"; print "Warning, this operation may result in data loss if it failed.\n";
@ -96,76 +93,67 @@ if (! $confirmed)
} }
/* /*
if (! $conf->global->LDAP_MEMBER_ACTIVE) * if (! $conf->global->LDAP_MEMBER_ACTIVE)
{ * {
print $langs->trans("LDAPSynchronizationNotSetupInDolibarr"); * print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
exit(-1); * exit(-1);
} * }
*/ */
$sql = "SELECT rowid"; $sql = "SELECT rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."adherent"; $sql .= " FROM " . MAIN_DB_PREFIX . "adherent";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
$ldap=new Ldap(); $ldap = new Ldap();
$ldap->connect_bind(); $ldap->connect_bind();
while ($i < $num) while ($i < $num) {
{ $ldap->error = "";
$ldap->error="";
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$member = new Adherent($db); $member = new Adherent($db);
$result=$member->fetch($obj->rowid); $result = $member->fetch($obj->rowid);
if ($result < 0) if ($result < 0) {
{
dol_print_error($db, $member->error); dol_print_error($db, $member->error);
exit(-1); exit(- 1);
} }
$result=$member->fetch_subscriptions(); $result = $member->fetch_subscriptions();
if ($result < 0) if ($result < 0) {
{
dol_print_error($db, $member->error); dol_print_error($db, $member->error);
exit(-1); exit(- 1);
} }
print $langs->transnoentities("UpdateMember")." rowid=".$member->id." ".$member->getFullName($langs); print $langs->transnoentities("UpdateMember") . " rowid=" . $member->id . " " . $member->getFullName($langs);
$oldobject=$member; $oldobject = $member;
$oldinfo=$oldobject->_load_ldap_info(); $oldinfo = $oldobject->_load_ldap_info();
$olddn=$oldobject->_load_ldap_dn($oldinfo); $olddn = $oldobject->_load_ldap_dn($oldinfo);
$info=$member->_load_ldap_info(); $info = $member->_load_ldap_info();
$dn=$member->_load_ldap_dn($info); $dn = $member->_load_ldap_dn($info);
$result=$ldap->add($dn, $info, $user); // Wil fail if already exists $result = $ldap->add($dn, $info, $user); // Wil fail if already exists
$result=$ldap->update($dn, $info, $user, $olddn); $result = $ldap->update($dn, $info, $user, $olddn);
if ($result > 0) if ($result > 0) {
{ print " - " . $langs->transnoentities("OK");
print " - ".$langs->transnoentities("OK"); } else {
} $error ++;
else print " - " . $langs->transnoentities("KO") . ' - ' . $ldap->error;
{
$error++;
print " - ".$langs->transnoentities("KO").' - '.$ldap->error;
} }
print "\n"; print "\n";
$i++; $i ++;
} }
$ldap->unbind(); $ldap->unbind();
$ldap->close(); $ldap->close();
} } else {
else
{
dol_print_error($db); dol_print_error($db);
} }

View File

@ -1,8 +1,8 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/** /**
* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2006-2015 Laurent Destailleur <eldy@users.sourceforge.net>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -11,7 +11,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -19,322 +19,265 @@
*/ */
/** /**
* \file scripts/members/sync_members_ldap2dolibarr.php * \file scripts/members/sync_members_ldap2dolibarr.php
* \ingroup ldap member * \ingroup ldap member
* \brief Script de mise a jour des adherents dans Dolibarr depuis LDAP * \brief Script de mise a jour des adherents dans Dolibarr depuis LDAP
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
require_once $path."../../htdocs/master.inc.php"; require_once $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php"; require_once DOL_DOCUMENT_ROOT . "/core/lib/date.lib.php";
require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php"; require_once DOL_DOCUMENT_ROOT . "/core/class/ldap.class.php";
require_once DOL_DOCUMENT_ROOT."/adherents/class/adherent.class.php"; require_once DOL_DOCUMENT_ROOT . "/adherents/class/adherent.class.php";
require_once DOL_DOCUMENT_ROOT."/adherents/class/subscription.class.php"; require_once DOL_DOCUMENT_ROOT . "/adherents/class/subscription.class.php";
$langs->loadLangs(array("main", "errors")); $langs->loadLangs(array("main","errors"));
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
$forcecommit=0; $forcecommit = 0;
$confirmed=0; $confirmed = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
// List of fields to get from LDAP // List of fields to get from LDAP
$required_fields = array( $required_fields = array($conf->global->LDAP_KEY_MEMBERS,$conf->global->LDAP_FIELD_FULLNAME,$conf->global->LDAP_FIELD_LOGIN,$conf->global->LDAP_FIELD_LOGIN_SAMBA,$conf->global->LDAP_FIELD_PASSWORD,$conf->global->LDAP_FIELD_PASSWORD_CRYPTED,$conf->global->LDAP_FIELD_NAME,$conf->global->LDAP_FIELD_FIRSTNAME,$conf->global->LDAP_FIELD_MAIL,$conf->global->LDAP_FIELD_PHONE,$conf->global->LDAP_FIELD_PHONE_PERSO,$conf->global->LDAP_FIELD_MOBILE,$conf->global->LDAP_FIELD_FAX,$conf->global->LDAP_FIELD_ADDRESS,$conf->global->LDAP_FIELD_ZIP,$conf->global->LDAP_FIELD_TOWN,$conf->global->LDAP_FIELD_COUNTRY,$conf->global->LDAP_FIELD_DESCRIPTION,$conf->global->LDAP_FIELD_BIRTHDATE,$conf->global->LDAP_FIELD_MEMBER_STATUS,$conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION,
$conf->global->LDAP_KEY_MEMBERS,
$conf->global->LDAP_FIELD_FULLNAME,
$conf->global->LDAP_FIELD_LOGIN,
$conf->global->LDAP_FIELD_LOGIN_SAMBA,
$conf->global->LDAP_FIELD_PASSWORD,
$conf->global->LDAP_FIELD_PASSWORD_CRYPTED,
$conf->global->LDAP_FIELD_NAME,
$conf->global->LDAP_FIELD_FIRSTNAME,
$conf->global->LDAP_FIELD_MAIL,
$conf->global->LDAP_FIELD_PHONE,
$conf->global->LDAP_FIELD_PHONE_PERSO,
$conf->global->LDAP_FIELD_MOBILE,
$conf->global->LDAP_FIELD_FAX,
$conf->global->LDAP_FIELD_ADDRESS,
$conf->global->LDAP_FIELD_ZIP,
$conf->global->LDAP_FIELD_TOWN,
$conf->global->LDAP_FIELD_COUNTRY,
$conf->global->LDAP_FIELD_DESCRIPTION,
$conf->global->LDAP_FIELD_BIRTHDATE,
$conf->global->LDAP_FIELD_MEMBER_STATUS,
$conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION,
// Subscriptions // Subscriptions
$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE, $conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE,$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT,$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE,$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT);
$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT,
$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE,
$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT
);
// Remove from required_fields all entries not configured in LDAP (empty) and duplicated // Remove from required_fields all entries not configured in LDAP (empty) and duplicated
$required_fields=array_unique(array_values(array_filter($required_fields, "dolValidElement"))); $required_fields = array_unique(array_values(array_filter($required_fields, "dolValidElement")));
if (! isset($argv[2]) || ! is_numeric($argv[2])) { if (! isset($argv[2]) || ! is_numeric($argv[2])) {
print "Usage: $script_file (nocommitiferror|commitiferror) id_member_type [--server=ldapserverhost] [-y]\n"; print "Usage: $script_file (nocommitiferror|commitiferror) id_member_type [--server=ldapserverhost] [-y]\n";
exit(-1); exit(- 1);
} }
$typeid=$argv[2]; $typeid = $argv[2];
foreach($argv as $key => $val) foreach ($argv as $key => $val) {
{ if ($val == 'commitiferror')
if ($val == 'commitiferror') $forcecommit=1; $forcecommit = 1;
if (preg_match('/--server=([^\s]+)$/', $val, $reg)) $conf->global->LDAP_SERVER_HOST=$reg[1]; if (preg_match('/--server=([^\s]+)$/', $val, $reg))
if (preg_match('/-y$/', $val, $reg)) $confirmed=1; $conf->global->LDAP_SERVER_HOST = $reg[1];
if (preg_match('/-y$/', $val, $reg))
$confirmed = 1;
} }
print "Mails sending disabled (useless in batch mode)\n"; print "Mails sending disabled (useless in batch mode)\n";
$conf->global->MAIN_DISABLE_ALL_MAILS=1; // On bloque les mails $conf->global->MAIN_DISABLE_ALL_MAILS = 1; // On bloque les mails
print "\n"; print "\n";
print "----- Synchronize all records from LDAP database:\n"; print "----- Synchronize all records from LDAP database:\n";
print "host=".$conf->global->LDAP_SERVER_HOST."\n"; print "host=" . $conf->global->LDAP_SERVER_HOST . "\n";
print "port=".$conf->global->LDAP_SERVER_PORT."\n"; print "port=" . $conf->global->LDAP_SERVER_PORT . "\n";
print "login=".$conf->global->LDAP_ADMIN_DN."\n"; print "login=" . $conf->global->LDAP_ADMIN_DN . "\n";
print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n"; print "pass=" . preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS) . "\n";
print "DN to extract=".$conf->global->LDAP_MEMBER_DN."\n"; print "DN to extract=" . $conf->global->LDAP_MEMBER_DN . "\n";
if (! empty($conf->global->LDAP_MEMBER_FILTER)) print 'Filter=('.$conf->global->LDAP_MEMBER_FILTER.')'."\n"; // Note: filter is defined into function getRecords if (! empty($conf->global->LDAP_MEMBER_FILTER))
else print 'Filter=('.$conf->global->LDAP_KEY_MEMBERS.'=*)'."\n"; print 'Filter=(' . $conf->global->LDAP_MEMBER_FILTER . ')' . "\n"; // Note: filter is defined into function getRecords
else
print 'Filter=(' . $conf->global->LDAP_KEY_MEMBERS . '=*)' . "\n";
print "----- To Dolibarr database:\n"; print "----- To Dolibarr database:\n";
print "type=".$conf->db->type."\n"; print "type=" . $conf->db->type . "\n";
print "host=".$conf->db->host."\n"; print "host=" . $conf->db->host . "\n";
print "port=".$conf->db->port."\n"; print "port=" . $conf->db->port . "\n";
print "login=".$conf->db->user."\n"; print "login=" . $conf->db->user . "\n";
print "database=".$conf->db->name."\n"; print "database=" . $conf->db->name . "\n";
print "----- Options:\n"; print "----- Options:\n";
print "commitiferror=".$forcecommit."\n"; print "commitiferror=" . $forcecommit . "\n";
print "Mapped LDAP fields=".join(',', $required_fields)."\n"; print "Mapped LDAP fields=" . join(',', $required_fields) . "\n";
print "\n"; print "\n";
// Check parameters // Check parameters
if (empty($conf->global->LDAP_MEMBER_DN)) if (empty($conf->global->LDAP_MEMBER_DN)) {
{ print $langs->trans("Error") . ': ' . $langs->trans("LDAP setup for members not defined inside Dolibarr") . "\n";
print $langs->trans("Error").': '.$langs->trans("LDAP setup for members not defined inside Dolibarr")."\n"; exit(- 1);
exit(-1);
} }
if ($typeid <= 0) if ($typeid <= 0) {
{ print $langs->trans("Error") . ': Parameter id_member_type is not a valid ref of an existing member type' . "\n";
print $langs->trans("Error").': Parameter id_member_type is not a valid ref of an existing member type'."\n"; exit(- 2);
exit(-2);
} }
if (! $confirmed) {
if (! $confirmed)
{
print "Hit Enter to continue or CTRL+C to stop...\n"; print "Hit Enter to continue or CTRL+C to stop...\n";
$input = trim(fgets(STDIN)); $input = trim(fgets(STDIN));
} }
// Load table of correspondence of countries // Load table of correspondence of countries
$hashlib2rowid=array(); $hashlib2rowid = array();
$countries=array(); $countries = array();
$sql = "SELECT rowid, code, label, active"; $sql = "SELECT rowid, code, label, active";
$sql.= " FROM ".MAIN_DB_PREFIX."c_country"; $sql .= " FROM " . MAIN_DB_PREFIX . "c_country";
$sql.= " WHERE active = 1"; $sql .= " WHERE active = 1";
$sql.= " ORDER BY code ASC"; $sql .= " ORDER BY code ASC";
$resql=$db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
if ($num) if ($num) {
{ while ($i < $num) {
while ($i < $num)
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if ($obj) if ($obj) {
{ // print 'Load cache for country '.strtolower($obj->label).' rowid='.$obj->rowid."\n";
//print 'Load cache for country '.strtolower($obj->label).' rowid='.$obj->rowid."\n"; $hashlib2rowid[strtolower($obj->label)] = $obj->rowid;
$hashlib2rowid[strtolower($obj->label)]=$obj->rowid; $countries[$obj->rowid] = array('rowid' => $obj->rowid,'label' => $obj->label,'code' => $obj->code);
$countries[$obj->rowid]=array('rowid' => $obj->rowid, 'label' => $obj->label, 'code' => $obj->code);
} }
$i++; $i ++;
} }
} }
} } else {
else
{
dol_print_error($db); dol_print_error($db);
exit(-1); exit(- 1);
} }
$ldap = new Ldap(); $ldap = new Ldap();
$result = $ldap->connect_bind(); $result = $ldap->connect_bind();
if ($result >= 0) if ($result >= 0) {
{ $justthese = array();
$justthese=array();
// We disable synchro Dolibarr-LDAP // We disable synchro Dolibarr-LDAP
$conf->global->LDAP_MEMBER_ACTIVE=0; $conf->global->LDAP_MEMBER_ACTIVE = 0;
$ldaprecords = $ldap->getRecords('*', $conf->global->LDAP_MEMBER_DN, $conf->global->LDAP_KEY_MEMBERS, $required_fields, 'member'); // Fiter on 'member' filter param $ldaprecords = $ldap->getRecords('*', $conf->global->LDAP_MEMBER_DN, $conf->global->LDAP_KEY_MEMBERS, $required_fields, 'member'); // Fiter on 'member' filter param
if (is_array($ldaprecords)) if (is_array($ldaprecords)) {
{
$db->begin(); $db->begin();
// Warning $ldapuser has a key in lowercase // Warning $ldapuser has a key in lowercase
foreach ($ldaprecords as $key => $ldapuser) foreach ($ldaprecords as $key => $ldapuser) {
{
$member = new Adherent($db); $member = new Adherent($db);
// Propriete membre // Propriete membre
$member->firstname=$ldapuser[$conf->global->LDAP_FIELD_FIRSTNAME]; $member->firstname = $ldapuser[$conf->global->LDAP_FIELD_FIRSTNAME];
$member->lastname=$ldapuser[$conf->global->LDAP_FIELD_NAME]; $member->lastname = $ldapuser[$conf->global->LDAP_FIELD_NAME];
$member->login=$ldapuser[$conf->global->LDAP_FIELD_LOGIN]; $member->login = $ldapuser[$conf->global->LDAP_FIELD_LOGIN];
$member->pass=$ldapuser[$conf->global->LDAP_FIELD_PASSWORD]; $member->pass = $ldapuser[$conf->global->LDAP_FIELD_PASSWORD];
//$member->societe; // $member->societe;
$member->address=$ldapuser[$conf->global->LDAP_FIELD_ADDRESS]; $member->address = $ldapuser[$conf->global->LDAP_FIELD_ADDRESS];
$member->zip=$ldapuser[$conf->global->LDAP_FIELD_ZIP]; $member->zip = $ldapuser[$conf->global->LDAP_FIELD_ZIP];
$member->town=$ldapuser[$conf->global->LDAP_FIELD_TOWN]; $member->town = $ldapuser[$conf->global->LDAP_FIELD_TOWN];
$member->country=$ldapuser[$conf->global->LDAP_FIELD_COUNTRY]; $member->country = $ldapuser[$conf->global->LDAP_FIELD_COUNTRY];
$member->country_id=$countries[$hashlib2rowid[strtolower($member->country)]]['rowid']; $member->country_id = $countries[$hashlib2rowid[strtolower($member->country)]]['rowid'];
$member->country_code=$countries[$hashlib2rowid[strtolower($member->country)]]['code']; $member->country_code = $countries[$hashlib2rowid[strtolower($member->country)]]['code'];
$member->phone=$ldapuser[$conf->global->LDAP_FIELD_PHONE]; $member->phone = $ldapuser[$conf->global->LDAP_FIELD_PHONE];
$member->phone_perso=$ldapuser[$conf->global->LDAP_FIELD_PHONE_PERSO]; $member->phone_perso = $ldapuser[$conf->global->LDAP_FIELD_PHONE_PERSO];
$member->phone_mobile=$ldapuser[$conf->global->LDAP_FIELD_MOBILE]; $member->phone_mobile = $ldapuser[$conf->global->LDAP_FIELD_MOBILE];
$member->email=$ldapuser[$conf->global->LDAP_FIELD_MAIL]; $member->email = $ldapuser[$conf->global->LDAP_FIELD_MAIL];
$member->note=$ldapuser[$conf->global->LDAP_FIELD_DESCRIPTION]; $member->note = $ldapuser[$conf->global->LDAP_FIELD_DESCRIPTION];
$member->morphy='phy'; $member->morphy = 'phy';
$member->photo=''; $member->photo = '';
$member->public=1; $member->public = 1;
$member->birth=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_BIRTHDATE]); $member->birth = dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_BIRTHDATE]);
$member->statut=-1; $member->statut = - 1;
if (isset($ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS])) if (isset($ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS])) {
{ $member->datec = dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
$member->datec=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]); $member->datevalid = dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
$member->datevalid=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]); $member->statut = $ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS];
$member->statut=$ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS];
} }
//if ($member->statut > 1) $member->statut=1; // if ($member->statut > 1) $member->statut=1;
//print_r($ldapuser); // print_r($ldapuser);
// Propriete type membre // Propriete type membre
$member->typeid=$typeid; $member->typeid = $typeid;
// Creation membre // Creation membre
print $langs->transnoentities("MemberCreate").' # '.$key.': login='.$member->login.', fullname='.$member->getFullName($langs); print $langs->transnoentities("MemberCreate") . ' # ' . $key . ': login=' . $member->login . ', fullname=' . $member->getFullName($langs);
print ', datec='.$member->datec; print ', datec=' . $member->datec;
$member_id=$member->create($user); $member_id = $member->create($user);
if ($member_id > 0) if ($member_id > 0) {
{ print ' --> Created member id=' . $member_id . ' login=' . $member->login;
print ' --> Created member id='.$member_id.' login='.$member->login; } else {
} $error ++;
else print ' --> ' . $member->error;
{
$error++;
print ' --> '.$member->error;
} }
print "\n"; print "\n";
//print_r($member); // print_r($member);
$datefirst=''; $datefirst = '';
if ($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE) if ($conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE) {
{ $datefirst = dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
$datefirst=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]); $pricefirst = price2num($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT]);
$pricefirst=price2num($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_AMOUNT]);
} }
$datelast=''; $datelast = '';
if ($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE) if ($conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE) {
{ $datelast = dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE]);
$datelast=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_DATE]); $pricelast = price2num($ldapuser[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT]);
$pricelast=price2num($ldapuser[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT]); } elseif ($conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION) {
} $datelast = dol_time_plus_duree(dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION]), - 1, 'y') + 60 * 60 * 24;
elseif ($conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION) $pricelast = price2num($ldapuser[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT]);
{
$datelast=dol_time_plus_duree(dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_END_LASTSUBSCRIPTION]), -1, 'y')+60*60*24;
$pricelast=price2num($ldapuser[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT]);
// Cas special ou date derniere <= date premiere // Cas special ou date derniere <= date premiere
if ($datefirst && $datelast && $datelast <= $datefirst) if ($datefirst && $datelast && $datelast <= $datefirst) {
{
// On ne va inserer que la premiere // On ne va inserer que la premiere
$datelast=0; $datelast = 0;
if (! $pricefirst && $pricelast) $pricefirst = $pricelast; if (! $pricefirst && $pricelast)
$pricefirst = $pricelast;
} }
} }
// Insert first subscription // Insert first subscription
if ($datefirst) if ($datefirst) {
{
// Cree premiere cotisation et met a jour datefin dans adherent // Cree premiere cotisation et met a jour datefin dans adherent
//print "xx".$datefirst."\n"; // print "xx".$datefirst."\n";
$crowid=$member->subscription($datefirst, $pricefirst, 0); $crowid = $member->subscription($datefirst, $pricefirst, 0);
} }
// Insert last subscription // Insert last subscription
if ($datelast) if ($datelast) {
{
// Cree derniere cotisation et met a jour datefin dans adherent // Cree derniere cotisation et met a jour datefin dans adherent
//print "yy".dol_print_date($datelast)."\n"; // print "yy".dol_print_date($datelast)."\n";
$crowid=$member->subscription($datelast, $pricelast, 0); $crowid = $member->subscription($datelast, $pricelast, 0);
} }
} }
if (! $error || $forcecommit) if (! $error || $forcecommit) {
{ if (! $error)
if (! $error) print $langs->transnoentities("NoErrorCommitIsDone")."\n"; print $langs->transnoentities("NoErrorCommitIsDone") . "\n";
else print $langs->transnoentities("ErrorButCommitIsDone")."\n"; else
print $langs->transnoentities("ErrorButCommitIsDone") . "\n";
$db->commit(); $db->commit();
} } else {
else print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error) . "\n";
{
print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
$db->rollback(); $db->rollback();
} }
print "\n"; print "\n";
} } else {
else
{
dol_print_error('', $ldap->error); dol_print_error('', $ldap->error);
$error++; $error ++;
} }
} } else {
else
{
dol_print_error('', $ldap->error); dol_print_error('', $ldap->error);
$error++; $error ++;
} }
exit($error); exit($error);
/** /**
* Function to say if a value is empty or not * Function to say if a value is empty or not
* *
* @param string $element Value to test * @param string $element
* @return boolean True of false * Value to test
* @return boolean True of false
*/ */
function dolValidElement($element) function dolValidElement($element)
{ {

View File

@ -1,9 +1,9 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/** /**
* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2006 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2006 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2017 Regis Houssin <regis.houssin@inodbox.com> * Copyright (C) 2017 Regis Houssin <regis.houssin@inodbox.com>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -12,7 +12,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -20,69 +20,64 @@
*/ */
/** /**
* \file scripts/user/sync_members_types_dolibarr2ldap.php * \file scripts/user/sync_members_types_dolibarr2ldap.php
* \ingroup ldap core * \ingroup ldap core
* \brief Script de mise a jour des types de membres dans LDAP depuis base Dolibarr * \brief Script de mise a jour des types de membres dans LDAP depuis base Dolibarr
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
if (! isset($argv[1]) || ! $argv[1]) { if (! isset($argv[1]) || ! $argv[1]) {
print "Usage: ".$script_file." now\n"; print "Usage: " . $script_file . " now\n";
exit(-1); exit(- 1);
} }
$now=$argv[1]; $now = $argv[1];
require_once $path."../../htdocs/master.inc.php"; require_once $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php"; require_once DOL_DOCUMENT_ROOT . "/core/class/ldap.class.php";
require_once DOL_DOCUMENT_ROOT."/adherents/class/adherent_type.class.php"; require_once DOL_DOCUMENT_ROOT . "/adherents/class/adherent_type.class.php";
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
/* /*
if (! $conf->global->LDAP_SYNCHRO_ACTIVE) * if (! $conf->global->LDAP_SYNCHRO_ACTIVE)
{ * {
print $langs->trans("LDAPSynchronizationNotSetupInDolibarr"); * print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
exit(-1); * exit(-1);
} * }
*/ */
$sql = "SELECT rowid"; $sql = "SELECT rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."adherent_type"; $sql .= " FROM " . MAIN_DB_PREFIX . "adherent_type";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
$ldap=new Ldap(); $ldap = new Ldap();
$result=$ldap->connect_bind(); $result = $ldap->connect_bind();
if ($result > 0) if ($result > 0) {
{ while ($i < $num) {
while ($i < $num) $ldap->error = "";
{
$ldap->error="";
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
@ -90,41 +85,35 @@ if ($resql)
$membertype->id = $obj->rowid; $membertype->id = $obj->rowid;
$membertype->fetch($membertype->id); $membertype->fetch($membertype->id);
print $langs->trans("UpdateMemberType")." rowid=".$membertype->id." ".$membertype-label; print $langs->trans("UpdateMemberType") . " rowid=" . $membertype->id . " " . $membertype - label;
$oldobject=$membertype; $oldobject = $membertype;
$oldinfo=$membertype->_load_ldap_info(); $oldinfo = $membertype->_load_ldap_info();
$olddn=$membertype->_load_ldap_dn($oldinfo); $olddn = $membertype->_load_ldap_dn($oldinfo);
$info=$membertype->_load_ldap_info(); $info = $membertype->_load_ldap_info();
$dn=$membertype->_load_ldap_dn($info); $dn = $membertype->_load_ldap_dn($info);
$result=$ldap->add($dn, $info, $user); // Wil fail if already exists $result = $ldap->add($dn, $info, $user); // Wil fail if already exists
$result=$ldap->update($dn, $info, $user, $olddn); $result = $ldap->update($dn, $info, $user, $olddn);
if ($result > 0) if ($result > 0) {
{ print " - " . $langs->trans("OK");
print " - ".$langs->trans("OK"); } else {
} $error ++;
else print " - " . $langs->trans("KO") . ' - ' . $ldap->error;
{
$error++;
print " - ".$langs->trans("KO").' - '.$ldap->error;
} }
print "\n"; print "\n";
$i++; $i ++;
} }
$ldap->unbind(); $ldap->unbind();
$ldap->close(); $ldap->close();
} } else {
else {
print $ldap->error; print $ldap->error;
} }
} } else {
else
{
dol_print_error($db); dol_print_error($db);
} }

View File

@ -1,10 +1,10 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/** /**
* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2006-2012 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2006-2012 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2013 Maxime Kohlhaas <maxime@atm-consulting.fr> * Copyright (C) 2013 Maxime Kohlhaas <maxime@atm-consulting.fr>
* Copyright (C) 2017 Regis Houssin <regis.houssin@inodbox.com> * Copyright (C) 2017 Regis Houssin <regis.houssin@inodbox.com>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -13,7 +13,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -21,196 +21,172 @@
*/ */
/** /**
* \file scripts/user/sync_members_types_ldap2dolibarr.php * \file scripts/user/sync_members_types_ldap2dolibarr.php
* \ingroup ldap member * \ingroup ldap member
* \brief Script to update members types into Dolibarr from LDAP * \brief Script to update members types into Dolibarr from LDAP
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
require_once $path."../../htdocs/master.inc.php"; require_once $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php"; require_once DOL_DOCUMENT_ROOT . "/core/lib/date.lib.php";
require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php"; require_once DOL_DOCUMENT_ROOT . "/core/class/ldap.class.php";
require_once DOL_DOCUMENT_ROOT."/adherents/class/adherent_type.class.php"; require_once DOL_DOCUMENT_ROOT . "/adherents/class/adherent_type.class.php";
$langs->loadLangs(array("main", "errors")); $langs->loadLangs(array("main","errors"));
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
$forcecommit=0; $forcecommit = 0;
$confirmed=0; $confirmed = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
// List of fields to get from LDAP // List of fields to get from LDAP
$required_fields = array( $required_fields = array($conf->global->LDAP_KEY_MEMBERS_TYPES,$conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME,$conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION,$conf->global->LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS);
$conf->global->LDAP_KEY_MEMBERS_TYPES,
$conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME,
$conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION,
$conf->global->LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS
);
// Remove from required_fields all entries not configured in LDAP (empty) and duplicated // Remove from required_fields all entries not configured in LDAP (empty) and duplicated
$required_fields=array_unique(array_values(array_filter($required_fields, "dolValidElementType"))); $required_fields = array_unique(array_values(array_filter($required_fields, "dolValidElementType")));
if (! isset($argv[1])) { if (! isset($argv[1])) {
//print "Usage: $script_file (nocommitiferror|commitiferror) [id_group]\n"; // print "Usage: $script_file (nocommitiferror|commitiferror) [id_group]\n";
print "Usage: $script_file (nocommitiferror|commitiferror) [--server=ldapserverhost] [--excludeuser=user1,user2...] [-y]\n"; print "Usage: $script_file (nocommitiferror|commitiferror) [--server=ldapserverhost] [--excludeuser=user1,user2...] [-y]\n";
exit(-1); exit(- 1);
} }
foreach($argv as $key => $val) foreach ($argv as $key => $val) {
{ if ($val == 'commitiferror')
if ($val == 'commitiferror') $forcecommit=1; $forcecommit = 1;
if (preg_match('/--server=([^\s]+)$/', $val, $reg)) $conf->global->LDAP_SERVER_HOST=$reg[1]; if (preg_match('/--server=([^\s]+)$/', $val, $reg))
if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg)) $excludeuser=explode(',', $reg[1]); $conf->global->LDAP_SERVER_HOST = $reg[1];
if (preg_match('/-y$/', $val, $reg)) $confirmed=1; if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg))
$excludeuser = explode(',', $reg[1]);
if (preg_match('/-y$/', $val, $reg))
$confirmed = 1;
} }
print "Mails sending disabled (useless in batch mode)\n"; print "Mails sending disabled (useless in batch mode)\n";
$conf->global->MAIN_DISABLE_ALL_MAILS=1; // On bloque les mails $conf->global->MAIN_DISABLE_ALL_MAILS = 1; // On bloque les mails
print "\n"; print "\n";
print "----- Synchronize all records from LDAP database:\n"; print "----- Synchronize all records from LDAP database:\n";
print "host=".$conf->global->LDAP_SERVER_HOST."\n"; print "host=" . $conf->global->LDAP_SERVER_HOST . "\n";
print "port=".$conf->global->LDAP_SERVER_PORT."\n"; print "port=" . $conf->global->LDAP_SERVER_PORT . "\n";
print "login=".$conf->global->LDAP_ADMIN_DN."\n"; print "login=" . $conf->global->LDAP_ADMIN_DN . "\n";
print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n"; print "pass=" . preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS) . "\n";
print "DN to extract=".$conf->global->LDAP_MEMBER_TYPE_DN."\n"; print "DN to extract=" . $conf->global->LDAP_MEMBER_TYPE_DN . "\n";
print 'Filter=('.$conf->global->LDAP_KEY_MEMBERS_TYPES.'=*)'."\n"; print 'Filter=(' . $conf->global->LDAP_KEY_MEMBERS_TYPES . '=*)' . "\n";
print "----- To Dolibarr database:\n"; print "----- To Dolibarr database:\n";
print "type=".$conf->db->type."\n"; print "type=" . $conf->db->type . "\n";
print "host=".$conf->db->host."\n"; print "host=" . $conf->db->host . "\n";
print "port=".$conf->db->port."\n"; print "port=" . $conf->db->port . "\n";
print "login=".$conf->db->user."\n"; print "login=" . $conf->db->user . "\n";
print "database=".$conf->db->name."\n"; print "database=" . $conf->db->name . "\n";
print "----- Options:\n"; print "----- Options:\n";
print "commitiferror=".$forcecommit."\n"; print "commitiferror=" . $forcecommit . "\n";
print "Mapped LDAP fields=".join(',', $required_fields)."\n"; print "Mapped LDAP fields=" . join(',', $required_fields) . "\n";
print "\n"; print "\n";
if (! $confirmed) if (! $confirmed) {
{
print "Hit Enter to continue or CTRL+C to stop...\n"; print "Hit Enter to continue or CTRL+C to stop...\n";
$input = trim(fgets(STDIN)); $input = trim(fgets(STDIN));
} }
if (empty($conf->global->LDAP_MEMBER_TYPE_DN)) if (empty($conf->global->LDAP_MEMBER_TYPE_DN)) {
{ print $langs->trans("Error") . ': ' . $langs->trans("LDAP setup for members types not defined inside Dolibarr");
print $langs->trans("Error").': '.$langs->trans("LDAP setup for members types not defined inside Dolibarr"); exit(- 1);
exit(-1);
} }
$ldap = new Ldap(); $ldap = new Ldap();
$result = $ldap->connect_bind(); $result = $ldap->connect_bind();
if ($result >= 0) if ($result >= 0) {
{ $justthese = array();
$justthese=array();
// We disable synchro Dolibarr-LDAP // We disable synchro Dolibarr-LDAP
$conf->global->LDAP_MEMBER_TYPE_ACTIVE=0; $conf->global->LDAP_MEMBER_TYPE_ACTIVE = 0;
$ldaprecords = $ldap->getRecords('*', $conf->global->LDAP_MEMBER_TYPE_DN, $conf->global->LDAP_KEY_MEMBERS_TYPES, $required_fields, 0, array($conf->global->LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS)); $ldaprecords = $ldap->getRecords('*', $conf->global->LDAP_MEMBER_TYPE_DN, $conf->global->LDAP_KEY_MEMBERS_TYPES, $required_fields, 0, array($conf->global->LDAP_MEMBER_TYPE_FIELD_GROUPMEMBERS));
if (is_array($ldaprecords)) if (is_array($ldaprecords)) {
{
$db->begin(); $db->begin();
// Warning $ldapuser has a key in lowercase // Warning $ldapuser has a key in lowercase
foreach ($ldaprecords as $key => $ldapgroup) foreach ($ldaprecords as $key => $ldapgroup) {
{
$membertype = new AdherentType($db); $membertype = new AdherentType($db);
$membertype->fetch('', $ldapgroup[$conf->global->LDAP_KEY_MEMBERS_TYPES]); $membertype->fetch('', $ldapgroup[$conf->global->LDAP_KEY_MEMBERS_TYPES]);
$membertype->label = $ldapgroup[$conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME]; $membertype->label = $ldapgroup[$conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME];
$membertype->description = $ldapgroup[$conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION]; $membertype->description = $ldapgroup[$conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION];
$membertype->entity = $conf->entity; $membertype->entity = $conf->entity;
//print_r($ldapgroup); // print_r($ldapgroup);
if ($membertype->id > 0) { // Member type update if ($membertype->id > 0) { // Member type update
print $langs->transnoentities("MemberTypeUpdate").' # '.$key.': name='.$membertype->label; print $langs->transnoentities("MemberTypeUpdate") . ' # ' . $key . ': name=' . $membertype->label;
$res=$membertype->update($user); $res = $membertype->update($user);
if ($res > 0) if ($res > 0) {
{ print ' --> Updated member type id=' . $membertype->id . ' name=' . $membertype->label;
print ' --> Updated member type id='.$membertype->id.' name='.$membertype->label; } else {
} $error ++;
else print ' --> ' . $res . ' ' . $membertype->error;
{
$error++;
print ' --> '.$res.' '.$membertype->error;
} }
print "\n"; print "\n";
} else { // Member type creation } else { // Member type creation
print $langs->transnoentities("MemberTypeCreate").' # '.$key.': name='.$membertype->label; print $langs->transnoentities("MemberTypeCreate") . ' # ' . $key . ': name=' . $membertype->label;
$res=$membertype->create($user); $res = $membertype->create($user);
if ($res > 0) if ($res > 0) {
{ print ' --> Created member type id=' . $membertype->id . ' name=' . $membertype->label;
print ' --> Created member type id='.$membertype->id.' name='.$membertype->label; } else {
} $error ++;
else print ' --> ' . $res . ' ' . $membertype->error;
{
$error++;
print ' --> '.$res.' '.$membertype->error;
} }
print "\n"; print "\n";
} }
//print_r($membertype); // print_r($membertype);
} }
if (! $error || $forcecommit) if (! $error || $forcecommit) {
{ if (! $error)
if (! $error) print $langs->transnoentities("NoErrorCommitIsDone")."\n"; print $langs->transnoentities("NoErrorCommitIsDone") . "\n";
else print $langs->transnoentities("ErrorButCommitIsDone")."\n"; else
print $langs->transnoentities("ErrorButCommitIsDone") . "\n";
$db->commit(); $db->commit();
} } else {
else print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error) . "\n";
{
print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
$db->rollback(); $db->rollback();
} }
print "\n"; print "\n";
} } else {
else
{
dol_print_error('', $ldap->error); dol_print_error('', $ldap->error);
$error++; $error ++;
} }
} } else {
else
{
dol_print_error('', $ldap->error); dol_print_error('', $ldap->error);
$error++; $error ++;
} }
exit($error); exit($error);
/** /**
* Function to say if a value is empty or not * Function to say if a value is empty or not
* *
* @param string $element Value to test * @param string $element
* @return boolean True of false * Value to test
* @return boolean True of false
*/ */
function dolValidElementType($element) function dolValidElementType($element)
{ {

View File

@ -1,7 +1,7 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/* /*
* Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -10,99 +10,94 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
/** /**
* \file scripts/modulebuilder/builddoc.php * \file scripts/modulebuilder/builddoc.php
* \ingroup modulebuilder * \ingroup modulebuilder
* \brief Script to build a documentation from input files (.asciidoc or .md files). Use asciidoctor tool. * \brief Script to build a documentation from input files (.asciidoc or .md files).
* Use asciidoctor tool.
* *
* If file is a MD file, convert image links into asciidoc format. * If file is a MD file, convert image links into asciidoc format.
* ![Screenshot patient card](img/dolimed_screenshot_patientcard.png?raw=true "Patient card") * ![Screenshot patient card](img/dolimed_screenshot_patientcard.png?raw=true "Patient card")
* image:img/dolimed_screenshot_patientcard.png[Screenshot patient card] * image:img/dolimed_screenshot_patientcard.png[Screenshot patient card]
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
if (! isset($argv[1]) || ! $argv[1]) { if (! isset($argv[1]) || ! $argv[1]) {
print "Usage: ".$script_file." ModuleName\n"; print "Usage: " . $script_file . " ModuleName\n";
exit(-1); exit(- 1);
} }
$modulename=$argv[1]; $modulename = $argv[1];
require_once $path."../../htdocs/master.inc.php"; require_once $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formadmin.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/modulebuilder.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/modulebuilder.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/utils.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/utils.class.php';
$langs->loadLangs(array("admin", "modulebuilder", "other", "cron"));
$langs->loadLangs(array("admin","modulebuilder","other","cron"));
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
// Dir for custom dirs // Dir for custom dirs
$tmp=explode(',', $dolibarr_main_document_root_alt); $tmp = explode(',', $dolibarr_main_document_root_alt);
$dirins = $tmp[0]; $dirins = $tmp[0];
$dirread = $dirins; $dirread = $dirins;
$forceddirread = 0; $forceddirread = 0;
$tmpdir = explode('@', $module); $tmpdir = explode('@', $module);
if (! empty($tmpdir[1])) if (! empty($tmpdir[1])) {
{ $module = $tmpdir[0];
$module=$tmpdir[0]; $dirread = $tmpdir[1];
$dirread=$tmpdir[1]; $forceddirread = 1;
$forceddirread=1;
} }
$FILEFLAG='modulebuilder.txt'; $FILEFLAG = 'modulebuilder.txt';
$now=dol_now(); $now = dol_now();
$newmask = 0; $newmask = 0;
if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK; if (empty($newmask) && ! empty($conf->global->MAIN_UMASK))
if (empty($newmask)) // This should no happen $newmask = $conf->global->MAIN_UMASK;
if (empty($newmask)) // This should no happen
{ {
$newmask='0664'; $newmask = '0664';
} }
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
print "modulename=".$modulename."\n"; print "modulename=" . $modulename . "\n";
print "dirins=".$dirins."\n"; print "dirins=" . $dirins . "\n";
$FILENAMEDOC=strtolower($module).'.html'; // TODO Use/text PDF $FILENAMEDOC = strtolower($module) . '.html'; // TODO Use/text PDF
$dirofmodule = dol_buildpath(strtolower($module), 0).'/doc'; $dirofmodule = dol_buildpath(strtolower($module), 0) . '/doc';
$outputfiledoc = $dirofmodule.'/'.$FILENAMEDOC; $outputfiledoc = $dirofmodule . '/' . $FILENAMEDOC;
$util = new Utils($db); $util = new Utils($db);
$result = $util->generateDoc($module); $result = $util->generateDoc($module);
if ($result <= 0) if ($result <= 0) {
{
print $util->errors; print $util->errors;
exit(1); exit(1);
} }

View File

@ -1,7 +1,7 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/* /*
* Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005-2013 Laurent Destailleur <eldy@users.sourceforge.net>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -10,165 +10,138 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
/** /**
* \file scripts/modulebuilder/initmodule.php * \file scripts/modulebuilder/initmodule.php
* \ingroup modulebuilder * \ingroup modulebuilder
* \brief Script to initialize a module. * \brief Script to initialize a module.
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
if (! isset($argv[1]) || ! $argv[1]) { if (! isset($argv[1]) || ! $argv[1]) {
print "Usage: ".$script_file." ModuleName\n"; print "Usage: " . $script_file . " ModuleName\n";
exit(-1); exit(- 1);
} }
$modulename=$argv[1]; $modulename = $argv[1];
require_once $path."../../htdocs/master.inc.php"; require_once $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/html.formadmin.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/modulebuilder.lib.php'; require_once DOL_DOCUMENT_ROOT . '/core/lib/modulebuilder.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
$langs->loadLangs(array("admin", "modulebuilder", "other", "cron"));
$langs->loadLangs(array("admin","modulebuilder","other","cron"));
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
// Dir for custom dirs // Dir for custom dirs
$tmp=explode(',', $dolibarr_main_document_root_alt); $tmp = explode(',', $dolibarr_main_document_root_alt);
$dirins = $tmp[0]; $dirins = $tmp[0];
$dirread = $dirins; $dirread = $dirins;
$forceddirread = 0; $forceddirread = 0;
$tmpdir = explode('@', $module); $tmpdir = explode('@', $module);
if (! empty($tmpdir[1])) if (! empty($tmpdir[1])) {
{ $module = $tmpdir[0];
$module=$tmpdir[0]; $dirread = $tmpdir[1];
$dirread=$tmpdir[1]; $forceddirread = 1;
$forceddirread=1;
} }
$FILEFLAG='modulebuilder.txt'; $FILEFLAG = 'modulebuilder.txt';
$now=dol_now(); $now = dol_now();
$newmask = 0; $newmask = 0;
if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK; if (empty($newmask) && ! empty($conf->global->MAIN_UMASK))
if (empty($newmask)) // This should no happen $newmask = $conf->global->MAIN_UMASK;
if (empty($newmask)) // This should no happen
{ {
$newmask='0664'; $newmask = '0664';
} }
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
print "modulename=".$modulename."\n"; print "modulename=" . $modulename . "\n";
print "dirins=".$dirins."\n"; print "dirins=" . $dirins . "\n";
if (preg_match('/[^a-z0-9_]/i', $modulename)) if (preg_match('/[^a-z0-9_]/i', $modulename)) {
{ $error ++;
$error++; print 'Error ' . $langs->trans("SpaceOrSpecialCharAreNotAllowed") . "\n";
print 'Error '.$langs->trans("SpaceOrSpecialCharAreNotAllowed")."\n";
exit(1); exit(1);
} }
if (! $error) if (! $error) {
{ $srcdir = DOL_DOCUMENT_ROOT . '/modulebuilder/template';
$srcdir = DOL_DOCUMENT_ROOT.'/modulebuilder/template'; $destdir = $dirins . '/' . strtolower($modulename);
$destdir = $dirins.'/'.strtolower($modulename);
$arrayreplacement=array( $arrayreplacement = array('mymodule' => strtolower($modulename),'MyModule' => $modulename);
'mymodule'=>strtolower($modulename),
'MyModule'=>$modulename
);
$result = dolCopyDir($srcdir, $destdir, 0, 0, $arrayreplacement); $result = dolCopyDir($srcdir, $destdir, 0, 0, $arrayreplacement);
//dol_mkdir($destfile); // dol_mkdir($destfile);
if ($result <= 0) if ($result <= 0) {
{ if ($result < 0) {
if ($result < 0) $error ++;
{
$error++;
$langs->load("errors"); $langs->load("errors");
print $langs->trans("ErrorFailToCopyDir", $srcdir, $destdir)."\n"; print $langs->trans("ErrorFailToCopyDir", $srcdir, $destdir) . "\n";
exit(2); exit(2);
} } else // $result == 0
else // $result == 0
{ {
print $langs->trans("AllFilesDidAlreadyExist", $srcdir, $destdir)."\n"; print $langs->trans("AllFilesDidAlreadyExist", $srcdir, $destdir) . "\n";
} }
} }
// Delete some files // Delete some files
dol_delete_file($destdir.'/myobject_card.php'); dol_delete_file($destdir . '/myobject_card.php');
dol_delete_file($destdir.'/myobject_note.php'); dol_delete_file($destdir . '/myobject_note.php');
dol_delete_file($destdir.'/myobject_document.php'); dol_delete_file($destdir . '/myobject_document.php');
dol_delete_file($destdir.'/myobject_agenda.php'); dol_delete_file($destdir . '/myobject_agenda.php');
dol_delete_file($destdir.'/myobject_list.php'); dol_delete_file($destdir . '/myobject_list.php');
dol_delete_file($destdir.'/lib/myobject.lib.php'); dol_delete_file($destdir . '/lib/myobject.lib.php');
dol_delete_file($destdir.'/test/phpunit/MyObjectTest.php'); dol_delete_file($destdir . '/test/phpunit/MyObjectTest.php');
dol_delete_file($destdir.'/sql/llx_mymodule_myobject.sql'); dol_delete_file($destdir . '/sql/llx_mymodule_myobject.sql');
dol_delete_file($destdir.'/sql/llx_mymodule_myobject_extrafields.sql'); dol_delete_file($destdir . '/sql/llx_mymodule_myobject_extrafields.sql');
dol_delete_file($destdir.'/sql/llx_mymodule_myobject.key.sql'); dol_delete_file($destdir . '/sql/llx_mymodule_myobject.key.sql');
dol_delete_file($destdir.'/scripts/myobject.php'); dol_delete_file($destdir . '/scripts/myobject.php');
dol_delete_file($destdir.'/img/object_myobject.png'); dol_delete_file($destdir . '/img/object_myobject.png');
dol_delete_file($destdir.'/class/myobject.class.php'); dol_delete_file($destdir . '/class/myobject.class.php');
dol_delete_file($destdir.'/class/api_mymodule.class.php'); dol_delete_file($destdir . '/class/api_mymodule.class.php');
} }
// Edit PHP files // Edit PHP files
if (! $error) if (! $error) {
{
$listofphpfilestoedit = dol_dir_list($destdir, 'files', 1, '\.(php|MD|js|sql|txt|xml|lang)$', '', 'fullname', SORT_ASC, 0, 1); $listofphpfilestoedit = dol_dir_list($destdir, 'files', 1, '\.(php|MD|js|sql|txt|xml|lang)$', '', 'fullname', SORT_ASC, 0, 1);
foreach($listofphpfilestoedit as $phpfileval) foreach ($listofphpfilestoedit as $phpfileval) {
{ // var_dump($phpfileval['fullname']);
//var_dump($phpfileval['fullname']); $arrayreplacement = array('mymodule' => strtolower($modulename),'MyModule' => $modulename,'MYMODULE' => strtoupper($modulename),'My module' => $modulename,'my module' => $modulename,'Mon module' => $modulename,'mon module' => $modulename,'htdocs/modulebuilder/template' => strtolower($modulename),'---Put here your own copyright and developer email---' => dol_print_date($now, '%Y') . ' ' . $user->getFullName($langs) . ($user->email ? ' <' . $user->email . '>' : ''));
$arrayreplacement=array(
'mymodule'=>strtolower($modulename),
'MyModule'=>$modulename,
'MYMODULE'=>strtoupper($modulename),
'My module'=>$modulename,
'my module'=>$modulename,
'Mon module'=>$modulename,
'mon module'=>$modulename,
'htdocs/modulebuilder/template'=>strtolower($modulename),
'---Put here your own copyright and developer email---'=>dol_print_date($now, '%Y').' '.$user->getFullName($langs).($user->email?' <'.$user->email.'>':'')
);
$result = dolReplaceInFile($phpfileval['fullname'], $arrayreplacement);
$result=dolReplaceInFile($phpfileval['fullname'], $arrayreplacement); // var_dump($result);
//var_dump($result); if ($result < 0) {
if ($result < 0) print $langs->trans("ErrorFailToMakeReplacementInto", $phpfileval['fullname']) . "\n";
{
print $langs->trans("ErrorFailToMakeReplacementInto", $phpfileval['fullname'])."\n";
exit(3); exit(3);
} }
} }
} }
print 'Module initialized'."\n"; print 'Module initialized' . "\n";
exit(0); exit(0);

View File

@ -1,7 +1,8 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/* Copyright (C) 2007-2016 Laurent Destailleur <eldy@users.sourceforge.net> /*
* Copyright (C) 2015 Jean Heimburger <http://tiaris.eu> * Copyright (C) 2007-2016 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2015 Jean Heimburger <http://tiaris.eu>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -10,7 +11,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -18,86 +19,76 @@
*/ */
/** /**
* \file scripts/product/migrate_picture_path.php * \file scripts/product/migrate_picture_path.php
* \ingroup scripts * \ingroup scripts
* \brief Migrate pictures from old system prior to 3.7 to new path for 3.7+ * \brief Migrate pictures from old system prior to 3.7 to new path for 3.7+
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
@set_time_limit(0); // No timeout for this script @set_time_limit(0); // No timeout for this script
define('EVEN_IF_ONLY_LOGIN_ALLOWED', 1); // Set this define to 0 if you want to lock your script when dolibarr setup is "locked to admin user only". define('EVEN_IF_ONLY_LOGIN_ALLOWED', 1); // Set this define to 0 if you want to lock your script when dolibarr setup is "locked to admin user only".
// Include and load Dolibarr environment variables // Include and load Dolibarr environment variables
require_once $path."../../htdocs/master.inc.php"; require_once $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT."/product/class/product.class.php"; require_once DOL_DOCUMENT_ROOT . "/product/class/product.class.php";
require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php"; require_once DOL_DOCUMENT_ROOT . "/core/lib/files.lib.php";
// After this $db, $mysoc, $langs, $conf and $hookmanager are defined (Opened $db handler to database will be closed at end of file). // After this $db, $mysoc, $langs, $conf and $hookmanager are defined (Opened $db handler to database will be closed at end of file).
// $user is created but empty. // $user is created but empty.
//$langs->setDefaultLang('en_US'); // To change default language of $langs // $langs->setDefaultLang('en_US'); // To change default language of $langs
$langs->load("main"); // To load language file for default language $langs->load("main"); // To load language file for default language
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
$forcecommit=0; $forcecommit = 0;
print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; dol_syslog($script_file . " launched with arg " . join(',', $argv));
dol_syslog($script_file." launched with arg ".join(',', $argv));
if (! isset($argv[1]) || $argv[1] != 'product') { if (! isset($argv[1]) || $argv[1] != 'product') {
print "Usage: $script_file product\n"; print "Usage: $script_file product\n";
exit(-1); exit(- 1);
} }
print '--- start'."\n"; print '--- start' . "\n";
// Case to migrate products path // Case to migrate products path
if ($argv[1] == 'product') if ($argv[1] == 'product') {
{
$product = new Product($db); $product = new Product($db);
$sql = "SELECT rowid as pid from ".MAIN_DB_PREFIX."product"; // Get list of all products $sql = "SELECT rowid as pid from " . MAIN_DB_PREFIX . "product"; // Get list of all products
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{ while ($obj = $db->fetch_object($resql)) {
while ($obj = $db->fetch_object($resql))
{
$product->fetch($obj->pid); $product->fetch($obj->pid);
print " migrating product id=".$product->id." ref=".$product->ref."\n"; print " migrating product id=" . $product->id . " ref=" . $product->ref . "\n";
migrate_product_photospath($product); migrate_product_photospath($product);
} }
} } else {
else print "\n sql error " . $sql;
{ exit();
print "\n sql error ".$sql;
exit;
} }
} }
$db->close(); // Close $db database opened handler
$db->close(); // Close $db database opened handler
exit($error); exit($error);
/** /**
* Migrate file from old path to new one for product $product * Migrate file from old path to new one for product $product
* *
* @param Product $product Object product * @param Product $product
* @return void * Object product
* @return void
*/ */
function migrate_product_photospath($product) function migrate_product_photospath($product)
{ {
@ -105,43 +96,34 @@ function migrate_product_photospath($product)
$dir = $conf->product->multidir_output[$product->entity]; $dir = $conf->product->multidir_output[$product->entity];
$conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO = 1; $conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO = 1;
$origin = $dir .'/'. get_exdir($product->id, 2, 0, 0, $product, 'product') . $product->id ."/photos"; $origin = $dir . '/' . get_exdir($product->id, 2, 0, 0, $product, 'product') . $product->id . "/photos";
$destin = $dir.'/'.dol_sanitizeFileName($product->ref); $destin = $dir . '/' . dol_sanitizeFileName($product->ref);
$error = 0; $error = 0;
$origin_osencoded=dol_osencode($origin); $origin_osencoded = dol_osencode($origin);
$destin_osencoded=dol_osencode($destin); $destin_osencoded = dol_osencode($destin);
dol_mkdir($destin); dol_mkdir($destin);
if (dol_is_dir($origin)) if (dol_is_dir($origin)) {
{ $handle = opendir($origin_osencoded);
$handle=opendir($origin_osencoded); if (is_resource($handle)) {
if (is_resource($handle)) while (($file = readdir($handle)) !== false) {
{ if ($file != '.' && $file != '..' && is_dir($origin_osencoded . '/' . $file)) {
while (($file = readdir($handle)) !== false) $thumbs = opendir($origin_osencoded . '/' . $file);
{ if (is_resource($thumbs)) {
if ($file != '.' && $file != '..' && is_dir($origin_osencoded.'/'.$file)) dol_mkdir($destin . '/' . $file);
{ while (($thumb = readdir($thumbs)) !== false) {
$thumbs = opendir($origin_osencoded.'/'.$file); dol_move($origin . '/' . $file . '/' . $thumb, $destin . '/' . $file . '/' . $thumb);
if (is_resource($thumbs)) }
{ // dol_delete_dir($origin.'/'.$file);
dol_mkdir($destin.'/'.$file); }
while (($thumb = readdir($thumbs)) !== false) } else {
{ if (dol_is_file($origin . '/' . $file)) {
dol_move($origin.'/'.$file.'/'.$thumb, $destin.'/'.$file.'/'.$thumb); dol_move($origin . '/' . $file, $destin . '/' . $file);
} }
// dol_delete_dir($origin.'/'.$file); }
} }
} }
else
{
if (dol_is_file($origin.'/'.$file) )
{
dol_move($origin.'/'.$file, $destin.'/'.$file);
}
}
}
}
} }
} }

View File

@ -1,7 +1,8 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/* Copyright (C) 2007-2016 Laurent Destailleur <eldy@users.sourceforge.net> /*
* Copyright (C) 2015 Jean Heimburger <http://tiaris.eu> * Copyright (C) 2007-2016 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2015 Jean Heimburger <http://tiaris.eu>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -10,7 +11,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -18,90 +19,85 @@
*/ */
/** /**
* \file scripts/product/migrate_picture_path.php * \file scripts/product/migrate_picture_path.php
* \ingroup scripts * \ingroup scripts
* \brief Migrate pictures from old system prior to 3.7 to new path for 3.7+ * \brief Migrate pictures from old system prior to 3.7 to new path for 3.7+
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
@set_time_limit(0); // No timeout for this script @set_time_limit(0); // No timeout for this script
define('EVEN_IF_ONLY_LOGIN_ALLOWED', 1); // Set this define to 0 if you want to lock your script when dolibarr setup is "locked to admin user only". define('EVEN_IF_ONLY_LOGIN_ALLOWED', 1); // Set this define to 0 if you want to lock your script when dolibarr setup is "locked to admin user only".
// Include and load Dolibarr environment variables // Include and load Dolibarr environment variables
require_once $path."../../htdocs/master.inc.php"; require_once $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT."/product/class/product.class.php"; require_once DOL_DOCUMENT_ROOT . "/product/class/product.class.php";
require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php"; require_once DOL_DOCUMENT_ROOT . "/core/lib/files.lib.php";
require_once DOL_DOCUMENT_ROOT."/core/lib/images.lib.php"; require_once DOL_DOCUMENT_ROOT . "/core/lib/images.lib.php";
// After this $db, $mysoc, $langs, $conf and $hookmanager are defined (Opened $db handler to database will be closed at end of file). // After this $db, $mysoc, $langs, $conf and $hookmanager are defined (Opened $db handler to database will be closed at end of file).
// $user is created but empty. // $user is created but empty.
//$langs->setDefaultLang('en_US'); // To change default language of $langs // $langs->setDefaultLang('en_US'); // To change default language of $langs
$langs->load("main"); // To load language file for default language $langs->load("main"); // To load language file for default language
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
$forcecommit=0; $forcecommit = 0;
print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; dol_syslog($script_file . " launched with arg " . join(',', $argv));
dol_syslog($script_file." launched with arg ".join(',', $argv));
if (empty($argv[1])) { if (empty($argv[1])) {
print "Usage: $script_file subdirtoscan\n"; print "Usage: $script_file subdirtoscan\n";
print "Example: $script_file produit\n"; print "Example: $script_file produit\n";
exit(-1); exit(- 1);
} }
print '--- start'."\n"; print '--- start' . "\n";
$dir = DOL_DATA_ROOT; $dir = DOL_DATA_ROOT;
$subdir=$argv[1]; $subdir = $argv[1];
if (empty($dir) || empty($subdir)) if (empty($dir) || empty($subdir)) {
{
dol_print_error('', 'dir not defined'); dol_print_error('', 'dir not defined');
exit(1); exit(1);
} }
if (! dol_is_dir($dir.'/'.$subdir)) if (! dol_is_dir($dir . '/' . $subdir)) {
{ print 'Directory ' . $dir . '/' . $subdir . ' not found.' . "\n";
print 'Directory '.$dir.'/'.$subdir.' not found.'."\n";
exit(2); exit(2);
} }
$filearray=dol_dir_list($dir.'/'.$subdir, "directories", 0, '', 'temp$'); $filearray = dol_dir_list($dir . '/' . $subdir, "directories", 0, '', 'temp$');
global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini; global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini;
foreach($filearray as $keyf => $valf) foreach ($filearray as $keyf => $valf) {
{ $ref = basename($valf['name']);
$ref=basename($valf['name']); $filearrayimg = dol_dir_list($valf['fullname'], "files", 0, '(\.gif|\.png|\.jpg|\.jpeg|\.bmp)$', '(\.meta|_preview.*\.png)$');
$filearrayimg=dol_dir_list($valf['fullname'], "files", 0, '(\.gif|\.png|\.jpg|\.jpeg|\.bmp)$', '(\.meta|_preview.*\.png)$'); foreach ($filearrayimg as $keyi => $vali) {
foreach($filearrayimg as $keyi => $vali) print 'Process image for ref ' . $ref . ' : ' . $vali['name'] . "\n";
{
print 'Process image for ref '.$ref.' : '.$vali['name']."\n";
// Create small thumbs for image // Create small thumbs for image
// Used on logon for example // Used on logon for example
$imgThumbSmall = vignette($vali['fullname'], $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs"); $imgThumbSmall = vignette($vali['fullname'], $maxwidthsmall, $maxheightsmall, '_small', 50, "thumbs");
if (preg_match('/Error/', $imgThumbSmall)) print $imgThumbSmall."\n"; if (preg_match('/Error/', $imgThumbSmall))
print $imgThumbSmall . "\n";
// Create mini thumbs for image (Ratio is near 16/9) // Create mini thumbs for image (Ratio is near 16/9)
// Used on menu or for setup page for example // Used on menu or for setup page for example
$imgThumbMini = vignette($vali['fullname'], $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs"); $imgThumbMini = vignette($vali['fullname'], $maxwidthmini, $maxheightmini, '_mini', 50, "thumbs");
if (preg_match('/Error/', $imgThumbMini)) print $imgThumbMini."\n"; if (preg_match('/Error/', $imgThumbMini))
print $imgThumbMini . "\n";
} }
} }
$db->close(); // Close $db database opened handler $db->close(); // Close $db database opened handler
exit($error); exit($error);

View File

@ -2,7 +2,7 @@
<?php <?php
/** /**
* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2006 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2006 Laurent Destailleur <eldy@users.sourceforge.net>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -11,7 +11,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -19,67 +19,63 @@
*/ */
/** /**
* \file scripts/user/sync_groups_dolibarr2ldap.php * \file scripts/user/sync_groups_dolibarr2ldap.php
* \ingroup ldap core * \ingroup ldap core
* \brief Script de mise a jour des groupes dans LDAP depuis base Dolibarr * \brief Script de mise a jour des groupes dans LDAP depuis base Dolibarr
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
if (! isset($argv[1]) || ! $argv[1]) { if (! isset($argv[1]) || ! $argv[1]) {
print "Usage: ".$script_file." now\n"; print "Usage: " . $script_file . " now\n";
exit(-1); exit(- 1);
} }
$now=$argv[1]; $now = $argv[1];
require_once $path."../../htdocs/master.inc.php"; require_once $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php"; require_once DOL_DOCUMENT_ROOT . "/core/class/ldap.class.php";
require_once DOL_DOCUMENT_ROOT."/user/class/usergroup.class.php"; require_once DOL_DOCUMENT_ROOT . "/user/class/usergroup.class.php";
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
/* /*
if (! $conf->global->LDAP_SYNCHRO_ACTIVE) * if (! $conf->global->LDAP_SYNCHRO_ACTIVE)
{ * {
print $langs->trans("LDAPSynchronizationNotSetupInDolibarr"); * print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
exit(-1); * exit(-1);
} * }
*/ */
$sql = "SELECT rowid"; $sql = "SELECT rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."usergroup"; $sql .= " FROM " . MAIN_DB_PREFIX . "usergroup";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
$ldap=new Ldap(); $ldap = new Ldap();
$ldap->connect_bind(); $ldap->connect_bind();
while ($i < $num) while ($i < $num) {
{ $ldap->error = "";
$ldap->error="";
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
@ -87,37 +83,32 @@ if ($resql)
$fgroup->id = $obj->rowid; $fgroup->id = $obj->rowid;
$fgroup->fetch($fgroup->id); $fgroup->fetch($fgroup->id);
print $langs->trans("UpdateGroup")." rowid=".$fgroup->id." ".$fgroup->name; print $langs->trans("UpdateGroup") . " rowid=" . $fgroup->id . " " . $fgroup->name;
$oldobject=$fgroup; $oldobject = $fgroup;
$oldinfo=$oldobject->_load_ldap_info(); $oldinfo = $oldobject->_load_ldap_info();
$olddn=$oldobject->_load_ldap_dn($oldinfo); $olddn = $oldobject->_load_ldap_dn($oldinfo);
$info=$fgroup->_load_ldap_info(); $info = $fgroup->_load_ldap_info();
$dn=$fgroup->_load_ldap_dn($info); $dn = $fgroup->_load_ldap_dn($info);
$result=$ldap->add($dn, $info, $user); // Wil fail if already exists $result = $ldap->add($dn, $info, $user); // Wil fail if already exists
$result=$ldap->update($dn, $info, $user, $olddn); $result = $ldap->update($dn, $info, $user, $olddn);
if ($result > 0) if ($result > 0) {
{ print " - " . $langs->trans("OK");
print " - ".$langs->trans("OK"); } else {
} $error ++;
else print " - " . $langs->trans("KO") . ' - ' . $ldap->error;
{
$error++;
print " - ".$langs->trans("KO").' - '.$ldap->error;
} }
print "\n"; print "\n";
$i++; $i ++;
} }
$ldap->unbind(); $ldap->unbind();
$ldap->close(); $ldap->close();
} } else {
else
{
dol_print_error($db); dol_print_error($db);
} }

View File

@ -1,9 +1,9 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/** /**
* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2006-2012 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2006-2012 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2013 Maxime Kohlhaas <maxime@atm-consulting.fr> * Copyright (C) 2013 Maxime Kohlhaas <maxime@atm-consulting.fr>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -12,7 +12,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -20,182 +20,166 @@
*/ */
/** /**
* \file scripts/user/sync_groups_ldap2dolibarr.php * \file scripts/user/sync_groups_ldap2dolibarr.php
* \ingroup ldap member * \ingroup ldap member
* \brief Script to update groups into Dolibarr from LDAP * \brief Script to update groups into Dolibarr from LDAP
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
require_once $path."../../htdocs/master.inc.php"; require_once $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php"; require_once DOL_DOCUMENT_ROOT . "/core/lib/date.lib.php";
require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php"; require_once DOL_DOCUMENT_ROOT . "/core/class/ldap.class.php";
require_once DOL_DOCUMENT_ROOT."/user/class/user.class.php"; require_once DOL_DOCUMENT_ROOT . "/user/class/user.class.php";
require_once DOL_DOCUMENT_ROOT."/user/class/usergroup.class.php"; require_once DOL_DOCUMENT_ROOT . "/user/class/usergroup.class.php";
$langs->loadLangs(array("main", "errors")); $langs->loadLangs(array("main","errors"));
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
$forcecommit=0; $forcecommit = 0;
$confirmed=0; $confirmed = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
// List of fields to get from LDAP // List of fields to get from LDAP
$required_fields = array( $required_fields = array($conf->global->LDAP_KEY_GROUPS,$conf->global->LDAP_GROUP_FIELD_FULLNAME,$conf->global->LDAP_GROUP_FIELD_DESCRIPTION,$conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS);
$conf->global->LDAP_KEY_GROUPS,
$conf->global->LDAP_GROUP_FIELD_FULLNAME,
$conf->global->LDAP_GROUP_FIELD_DESCRIPTION,
$conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS
);
// Remove from required_fields all entries not configured in LDAP (empty) and duplicated // Remove from required_fields all entries not configured in LDAP (empty) and duplicated
$required_fields=array_unique(array_values(array_filter($required_fields, "dolValidElement"))); $required_fields = array_unique(array_values(array_filter($required_fields, "dolValidElement")));
if (! isset($argv[1])) { if (! isset($argv[1])) {
//print "Usage: $script_file (nocommitiferror|commitiferror) [id_group]\n"; // print "Usage: $script_file (nocommitiferror|commitiferror) [id_group]\n";
print "Usage: $script_file (nocommitiferror|commitiferror) [--server=ldapserverhost] [--excludeuser=user1,user2...] [-y]\n"; print "Usage: $script_file (nocommitiferror|commitiferror) [--server=ldapserverhost] [--excludeuser=user1,user2...] [-y]\n";
exit(-1); exit(- 1);
} }
foreach($argv as $key => $val) foreach ($argv as $key => $val) {
{ if ($val == 'commitiferror')
if ($val == 'commitiferror') $forcecommit=1; $forcecommit = 1;
if (preg_match('/--server=([^\s]+)$/', $val, $reg)) $conf->global->LDAP_SERVER_HOST=$reg[1]; if (preg_match('/--server=([^\s]+)$/', $val, $reg))
if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg)) $excludeuser=explode(',', $reg[1]); $conf->global->LDAP_SERVER_HOST = $reg[1];
if (preg_match('/-y$/', $val, $reg)) $confirmed=1; if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg))
$excludeuser = explode(',', $reg[1]);
if (preg_match('/-y$/', $val, $reg))
$confirmed = 1;
} }
print "Mails sending disabled (useless in batch mode)\n"; print "Mails sending disabled (useless in batch mode)\n";
$conf->global->MAIN_DISABLE_ALL_MAILS=1; // On bloque les mails $conf->global->MAIN_DISABLE_ALL_MAILS = 1; // On bloque les mails
print "\n"; print "\n";
print "----- Synchronize all records from LDAP database:\n"; print "----- Synchronize all records from LDAP database:\n";
print "host=".$conf->global->LDAP_SERVER_HOST."\n"; print "host=" . $conf->global->LDAP_SERVER_HOST . "\n";
print "port=".$conf->global->LDAP_SERVER_PORT."\n"; print "port=" . $conf->global->LDAP_SERVER_PORT . "\n";
print "login=".$conf->global->LDAP_ADMIN_DN."\n"; print "login=" . $conf->global->LDAP_ADMIN_DN . "\n";
print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n"; print "pass=" . preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS) . "\n";
print "DN to extract=".$conf->global->LDAP_GROUP_DN."\n"; print "DN to extract=" . $conf->global->LDAP_GROUP_DN . "\n";
print 'Filter=('.$conf->global->LDAP_KEY_GROUPS.'=*)'."\n"; print 'Filter=(' . $conf->global->LDAP_KEY_GROUPS . '=*)' . "\n";
print "----- To Dolibarr database:\n"; print "----- To Dolibarr database:\n";
print "type=".$conf->db->type."\n"; print "type=" . $conf->db->type . "\n";
print "host=".$conf->db->host."\n"; print "host=" . $conf->db->host . "\n";
print "port=".$conf->db->port."\n"; print "port=" . $conf->db->port . "\n";
print "login=".$conf->db->user."\n"; print "login=" . $conf->db->user . "\n";
print "database=".$conf->db->name."\n"; print "database=" . $conf->db->name . "\n";
print "----- Options:\n"; print "----- Options:\n";
print "commitiferror=".$forcecommit."\n"; print "commitiferror=" . $forcecommit . "\n";
print "Mapped LDAP fields=".join(',', $required_fields)."\n"; print "Mapped LDAP fields=" . join(',', $required_fields) . "\n";
print "\n"; print "\n";
if (! $confirmed) if (! $confirmed) {
{
print "Hit Enter to continue or CTRL+C to stop...\n"; print "Hit Enter to continue or CTRL+C to stop...\n";
$input = trim(fgets(STDIN)); $input = trim(fgets(STDIN));
} }
if (empty($conf->global->LDAP_GROUP_DN)) if (empty($conf->global->LDAP_GROUP_DN)) {
{ print $langs->trans("Error") . ': ' . $langs->trans("LDAP setup for groups not defined inside Dolibarr");
print $langs->trans("Error").': '.$langs->trans("LDAP setup for groups not defined inside Dolibarr"); exit(- 1);
exit(-1);
} }
$ldap = new Ldap(); $ldap = new Ldap();
$result = $ldap->connect_bind(); $result = $ldap->connect_bind();
if ($result >= 0) if ($result >= 0) {
{ $justthese = array();
$justthese=array();
// We disable synchro Dolibarr-LDAP // We disable synchro Dolibarr-LDAP
$conf->global->LDAP_SYNCHRO_ACTIVE=0; $conf->global->LDAP_SYNCHRO_ACTIVE = 0;
$ldaprecords = $ldap->getRecords('*', $conf->global->LDAP_GROUP_DN, $conf->global->LDAP_KEY_GROUPS, $required_fields, 0, array($conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS)); $ldaprecords = $ldap->getRecords('*', $conf->global->LDAP_GROUP_DN, $conf->global->LDAP_KEY_GROUPS, $required_fields, 0, array($conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS));
if (is_array($ldaprecords)) if (is_array($ldaprecords)) {
{
$db->begin(); $db->begin();
// Warning $ldapuser has a key in lowercase // Warning $ldapuser has a key in lowercase
foreach ($ldaprecords as $key => $ldapgroup) foreach ($ldaprecords as $key => $ldapgroup) {
{
$group = new UserGroup($db); $group = new UserGroup($db);
$group->fetch('', $ldapgroup[$conf->global->LDAP_KEY_GROUPS]); $group->fetch('', $ldapgroup[$conf->global->LDAP_KEY_GROUPS]);
$group->name = $ldapgroup[$conf->global->LDAP_GROUP_FIELD_FULLNAME]; $group->name = $ldapgroup[$conf->global->LDAP_GROUP_FIELD_FULLNAME];
$group->nom = $group->name; // For backward compatibility $group->nom = $group->name; // For backward compatibility
$group->note = $ldapgroup[$conf->global->LDAP_GROUP_FIELD_DESCRIPTION]; $group->note = $ldapgroup[$conf->global->LDAP_GROUP_FIELD_DESCRIPTION];
$group->entity = $conf->entity; $group->entity = $conf->entity;
//print_r($ldapgroup); // print_r($ldapgroup);
if($group->id > 0) { // Group update if ($group->id > 0) { // Group update
print $langs->transnoentities("GroupUpdate").' # '.$key.': name='.$group->name; print $langs->transnoentities("GroupUpdate") . ' # ' . $key . ': name=' . $group->name;
$res=$group->update(); $res = $group->update();
if ($res > 0) if ($res > 0) {
{ print ' --> Updated group id=' . $group->id . ' name=' . $group->name;
print ' --> Updated group id='.$group->id.' name='.$group->name; } else {
} $error ++;
else print ' --> ' . $res . ' ' . $group->error;
{
$error++;
print ' --> '.$res.' '.$group->error;
} }
print "\n"; print "\n";
} else { // Group creation } else { // Group creation
print $langs->transnoentities("GroupCreate").' # '.$key.': name='.$group->name; print $langs->transnoentities("GroupCreate") . ' # ' . $key . ': name=' . $group->name;
$res=$group->create(); $res = $group->create();
if ($res > 0) if ($res > 0) {
{ print ' --> Created group id=' . $group->id . ' name=' . $group->name;
print ' --> Created group id='.$group->id.' name='.$group->name; } else {
} $error ++;
else print ' --> ' . $res . ' ' . $group->error;
{
$error++;
print ' --> '.$res.' '.$group->error;
} }
print "\n"; print "\n";
} }
//print_r($group); // print_r($group);
// Gestion des utilisateurs associés au groupe // Gestion des utilisateurs associés au groupe
// 1 - Association des utilisateurs du groupe LDAP au groupe Dolibarr // 1 - Association des utilisateurs du groupe LDAP au groupe Dolibarr
$userList = array(); $userList = array();
$userIdList = array(); $userIdList = array();
foreach($ldapgroup[$conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS] as $key => $userdn) { foreach ($ldapgroup[$conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS] as $key => $userdn) {
if($key === 'count') continue; if ($key === 'count')
if(empty($userList[$userdn])) { // Récupération de l'utilisateur continue;
// Schéma rfc2307: les membres sont listés dans l'attribut memberUid sous form de login uniquement if (empty($userList[$userdn])) { // Récupération de l'utilisateur
if ($conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS === 'memberUid'){ // Schéma rfc2307: les membres sont listés dans l'attribut memberUid sous form de login uniquement
if ($conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS === 'memberUid') {
$userKey = array($userdn); $userKey = array($userdn);
} else { // Pour les autres schémas, les membres sont listés sous forme de DN complets } else { // Pour les autres schémas, les membres sont listés sous forme de DN complets
$userFilter = explode(',', $userdn); $userFilter = explode(',', $userdn);
$userKey = $ldap->getAttributeValues('('.$userFilter[0].')', $conf->global->LDAP_KEY_USERS); $userKey = $ldap->getAttributeValues('(' . $userFilter[0] . ')', $conf->global->LDAP_KEY_USERS);
} }
if(!is_array($userKey)) continue; if (! is_array($userKey))
continue;
$fuser = new User($db); $fuser = new User($db);
if($conf->global->LDAP_KEY_USERS == $conf->global->LDAP_FIELD_SID) { if ($conf->global->LDAP_KEY_USERS == $conf->global->LDAP_FIELD_SID) {
$fuser->fetch('', '', $userKey[0]); // Chargement du user concerné par le SID $fuser->fetch('', '', $userKey[0]); // Chargement du user concerné par le SID
} elseif ($conf->global->LDAP_KEY_USERS == $conf->global->LDAP_FIELD_LOGIN) { } elseif ($conf->global->LDAP_KEY_USERS == $conf->global->LDAP_FIELD_LOGIN) {
$fuser->fetch('', $userKey[0]); // Chargement du user concerné par le login $fuser->fetch('', $userKey[0]); // Chargement du user concerné par le login
@ -209,55 +193,49 @@ if ($result >= 0)
$userIdList[$userdn] = $fuser->id; $userIdList[$userdn] = $fuser->id;
// Ajout de l'utilisateur dans le groupe // Ajout de l'utilisateur dans le groupe
if(!in_array($fuser->id, array_keys($group->members))) { if (! in_array($fuser->id, array_keys($group->members))) {
$fuser->SetInGroup($group->id, $group->entity); $fuser->SetInGroup($group->id, $group->entity);
echo $fuser->login.' added'."\n"; echo $fuser->login . ' added' . "\n";
} }
} }
// 2 - Suppression des utilisateurs du groupe Dolibarr qui ne sont plus dans le groupe LDAP // 2 - Suppression des utilisateurs du groupe Dolibarr qui ne sont plus dans le groupe LDAP
foreach ($group->members as $guser) { foreach ($group->members as $guser) {
if(!in_array($guser->id, $userIdList)) { if (! in_array($guser->id, $userIdList)) {
$guser->RemoveFromGroup($group->id, $group->entity); $guser->RemoveFromGroup($group->id, $group->entity);
echo $guser->login.' removed'."\n"; echo $guser->login . ' removed' . "\n";
} }
} }
} }
if (! $error || $forcecommit) if (! $error || $forcecommit) {
{ if (! $error)
if (! $error) print $langs->transnoentities("NoErrorCommitIsDone")."\n"; print $langs->transnoentities("NoErrorCommitIsDone") . "\n";
else print $langs->transnoentities("ErrorButCommitIsDone")."\n"; else
print $langs->transnoentities("ErrorButCommitIsDone") . "\n";
$db->commit(); $db->commit();
} } else {
else print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error) . "\n";
{
print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
$db->rollback(); $db->rollback();
} }
print "\n"; print "\n";
} } else {
else
{
dol_print_error('', $ldap->error); dol_print_error('', $ldap->error);
$error++; $error ++;
} }
} } else {
else
{
dol_print_error('', $ldap->error); dol_print_error('', $ldap->error);
$error++; $error ++;
} }
exit($error); exit($error);
/** /**
* Function to say if a value is empty or not * Function to say if a value is empty or not
* *
* @param string $element Value to test * @param string $element
* @return boolean True of false * Value to test
* @return boolean True of false
*/ */
function dolValidElement($element) function dolValidElement($element)
{ {

View File

@ -2,7 +2,7 @@
<?php <?php
/** /**
* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2006 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2006 Laurent Destailleur <eldy@users.sourceforge.net>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -11,7 +11,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -19,104 +19,95 @@
*/ */
/** /**
* \file scripts/user/sync_users_dolibarr2ldap.php * \file scripts/user/sync_users_dolibarr2ldap.php
* \ingroup ldap core * \ingroup ldap core
* \brief Script de mise a jour des users dans LDAP depuis base Dolibarr * \brief Script de mise a jour des users dans LDAP depuis base Dolibarr
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
if (! isset($argv[1]) || ! $argv[1]) { if (! isset($argv[1]) || ! $argv[1]) {
print "Usage: $script_file now\n"; print "Usage: $script_file now\n";
exit(-1); exit(- 1);
} }
$now=$argv[1]; $now = $argv[1];
require_once $path."../../htdocs/master.inc.php"; require_once $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php"; require_once DOL_DOCUMENT_ROOT . "/core/class/ldap.class.php";
require_once DOL_DOCUMENT_ROOT."/user/class/user.class.php"; require_once DOL_DOCUMENT_ROOT . "/user/class/user.class.php";
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
/* /*
if (! $conf->global->LDAP_SYNCHRO_ACTIVE) * if (! $conf->global->LDAP_SYNCHRO_ACTIVE)
{ * {
print $langs->trans("LDAPSynchronizationNotSetupInDolibarr"); * print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
exit(-1); * exit(-1);
} * }
*/ */
$sql = "SELECT rowid"; $sql = "SELECT rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."user"; $sql .= " FROM " . MAIN_DB_PREFIX . "user";
$resql = $db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
$ldap=new Ldap(); $ldap = new Ldap();
$ldap->connect_bind(); $ldap->connect_bind();
while ($i < $num) while ($i < $num) {
{ $ldap->error = "";
$ldap->error="";
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
$fuser = new User($db); $fuser = new User($db);
$fuser->fetch($obj->rowid); $fuser->fetch($obj->rowid);
print $langs->trans("UpdateUser")." rowid=".$fuser->id." ".$fuser->getFullName($langs); print $langs->trans("UpdateUser") . " rowid=" . $fuser->id . " " . $fuser->getFullName($langs);
$oldobject=$fuser; $oldobject = $fuser;
$oldinfo=$oldobject->_load_ldap_info(); $oldinfo = $oldobject->_load_ldap_info();
$olddn=$oldobject->_load_ldap_dn($oldinfo); $olddn = $oldobject->_load_ldap_dn($oldinfo);
$info=$fuser->_load_ldap_info(); $info = $fuser->_load_ldap_info();
$dn=$fuser->_load_ldap_dn($info); $dn = $fuser->_load_ldap_dn($info);
$result=$ldap->add($dn, $info, $user); // Wil fail if already exists $result = $ldap->add($dn, $info, $user); // Wil fail if already exists
$result=$ldap->update($dn, $info, $user, $olddn); $result = $ldap->update($dn, $info, $user, $olddn);
if ($result > 0) if ($result > 0) {
{ print " - " . $langs->trans("OK");
print " - ".$langs->trans("OK"); } else {
} $error ++;
else print " - " . $langs->trans("KO") . ' - ' . $ldap->error;
{
$error++;
print " - ".$langs->trans("KO").' - '.$ldap->error;
} }
print "\n"; print "\n";
$i++; $i ++;
} }
$ldap->unbind(); $ldap->unbind();
$ldap->close(); $ldap->close();
} } else {
else
{
dol_print_error($db); dol_print_error($db);
} }

View File

@ -1,8 +1,8 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/** /**
* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2006-2012 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2006-2012 Laurent Destailleur <eldy@users.sourceforge.net>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -11,7 +11,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -19,301 +19,266 @@
*/ */
/** /**
* \file scripts/user/sync_users_ldap2dolibarr.php * \file scripts/user/sync_users_ldap2dolibarr.php
* \ingroup ldap member * \ingroup ldap member
* \brief Script to update users into Dolibarr from LDAP * \brief Script to update users into Dolibarr from LDAP
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
require_once $path."../../htdocs/master.inc.php"; require_once $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT."/core/lib/date.lib.php"; require_once DOL_DOCUMENT_ROOT . "/core/lib/date.lib.php";
require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php"; require_once DOL_DOCUMENT_ROOT . "/core/class/ldap.class.php";
require_once DOL_DOCUMENT_ROOT."/user/class/user.class.php"; require_once DOL_DOCUMENT_ROOT . "/user/class/user.class.php";
$langs->loadLangs(array("main", "errors")); $langs->loadLangs(array("main","errors"));
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
$forcecommit=0; $forcecommit = 0;
$excludeuser=array(); $excludeuser = array();
$confirmed=0; $confirmed = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
// List of fields to get from LDAP // List of fields to get from LDAP
$required_fields = array( $required_fields = array($conf->global->LDAP_KEY_USERS,$conf->global->LDAP_FIELD_FULLNAME,$conf->global->LDAP_FIELD_NAME,$conf->global->LDAP_FIELD_FIRSTNAME,$conf->global->LDAP_FIELD_LOGIN,$conf->global->LDAP_FIELD_LOGIN_SAMBA,$conf->global->LDAP_FIELD_PASSWORD,$conf->global->LDAP_FIELD_PASSWORD_CRYPTED,$conf->global->LDAP_FIELD_PHONE,$conf->global->LDAP_FIELD_FAX,$conf->global->LDAP_FIELD_MOBILE,
$conf->global->LDAP_KEY_USERS, // $conf->global->LDAP_FIELD_ADDRESS,
$conf->global->LDAP_FIELD_FULLNAME, // $conf->global->LDAP_FIELD_ZIP,
$conf->global->LDAP_FIELD_NAME, // $conf->global->LDAP_FIELD_TOWN,
$conf->global->LDAP_FIELD_FIRSTNAME, // $conf->global->LDAP_FIELD_COUNTRY,
$conf->global->LDAP_FIELD_LOGIN, $conf->global->LDAP_FIELD_MAIL,$conf->global->LDAP_FIELD_TITLE,$conf->global->LDAP_FIELD_DESCRIPTION,$conf->global->LDAP_FIELD_SID);
$conf->global->LDAP_FIELD_LOGIN_SAMBA,
$conf->global->LDAP_FIELD_PASSWORD,
$conf->global->LDAP_FIELD_PASSWORD_CRYPTED,
$conf->global->LDAP_FIELD_PHONE,
$conf->global->LDAP_FIELD_FAX,
$conf->global->LDAP_FIELD_MOBILE,
//$conf->global->LDAP_FIELD_ADDRESS,
//$conf->global->LDAP_FIELD_ZIP,
//$conf->global->LDAP_FIELD_TOWN,
//$conf->global->LDAP_FIELD_COUNTRY,
$conf->global->LDAP_FIELD_MAIL,
$conf->global->LDAP_FIELD_TITLE,
$conf->global->LDAP_FIELD_DESCRIPTION,
$conf->global->LDAP_FIELD_SID
);
// Remove from required_fields all entries not configured in LDAP (empty) and duplicated // Remove from required_fields all entries not configured in LDAP (empty) and duplicated
$required_fields=array_unique(array_values(array_filter($required_fields, "dolValidElement"))); $required_fields = array_unique(array_values(array_filter($required_fields, "dolValidElement")));
if (! isset($argv[1])) { if (! isset($argv[1])) {
print "Usage: $script_file (nocommitiferror|commitiferror) [--server=ldapserverhost] [--excludeuser=user1,user2...] [-y]\n"; print "Usage: $script_file (nocommitiferror|commitiferror) [--server=ldapserverhost] [--excludeuser=user1,user2...] [-y]\n";
exit(-1); exit(- 1);
} }
foreach($argv as $key => $val) foreach ($argv as $key => $val) {
{ if ($val == 'commitiferror')
if ($val == 'commitiferror') $forcecommit=1; $forcecommit = 1;
if (preg_match('/--server=([^\s]+)$/', $val, $reg)) $conf->global->LDAP_SERVER_HOST=$reg[1]; if (preg_match('/--server=([^\s]+)$/', $val, $reg))
if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg)) $excludeuser=explode(',', $reg[1]); $conf->global->LDAP_SERVER_HOST = $reg[1];
if (preg_match('/-y$/', $val, $reg)) $confirmed=1; if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg))
$excludeuser = explode(',', $reg[1]);
if (preg_match('/-y$/', $val, $reg))
$confirmed = 1;
} }
print "Mails sending disabled (useless in batch mode)\n"; print "Mails sending disabled (useless in batch mode)\n";
$conf->global->MAIN_DISABLE_ALL_MAILS=1; // On bloque les mails $conf->global->MAIN_DISABLE_ALL_MAILS = 1; // On bloque les mails
print "\n"; print "\n";
print "----- Synchronize all records from LDAP database:\n"; print "----- Synchronize all records from LDAP database:\n";
print "host=".$conf->global->LDAP_SERVER_HOST."\n"; print "host=" . $conf->global->LDAP_SERVER_HOST . "\n";
print "port=".$conf->global->LDAP_SERVER_PORT."\n"; print "port=" . $conf->global->LDAP_SERVER_PORT . "\n";
print "login=".$conf->global->LDAP_ADMIN_DN."\n"; print "login=" . $conf->global->LDAP_ADMIN_DN . "\n";
print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n"; print "pass=" . preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS) . "\n";
print "DN to extract=".$conf->global->LDAP_USER_DN."\n"; print "DN to extract=" . $conf->global->LDAP_USER_DN . "\n";
if (! empty($conf->global->LDAP_FILTER_CONNECTION)) print 'Filter=('.$conf->global->LDAP_FILTER_CONNECTION.')'."\n"; // Note: filter is defined into function getRecords if (! empty($conf->global->LDAP_FILTER_CONNECTION))
else print 'Filter=('.$conf->global->LDAP_KEY_USERS.'=*)'."\n"; print 'Filter=(' . $conf->global->LDAP_FILTER_CONNECTION . ')' . "\n"; // Note: filter is defined into function getRecords
else
print 'Filter=(' . $conf->global->LDAP_KEY_USERS . '=*)' . "\n";
print "----- To Dolibarr database:\n"; print "----- To Dolibarr database:\n";
print "type=".$conf->db->type."\n"; print "type=" . $conf->db->type . "\n";
print "host=".$conf->db->host."\n"; print "host=" . $conf->db->host . "\n";
print "port=".$conf->db->port."\n"; print "port=" . $conf->db->port . "\n";
print "login=".$conf->db->user."\n"; print "login=" . $conf->db->user . "\n";
print "database=".$conf->db->name."\n"; print "database=" . $conf->db->name . "\n";
print "----- Options:\n"; print "----- Options:\n";
print "commitiferror=".$forcecommit."\n"; print "commitiferror=" . $forcecommit . "\n";
print "excludeuser=".join(',', $excludeuser)."\n"; print "excludeuser=" . join(',', $excludeuser) . "\n";
print "Mapped LDAP fields=".join(',', $required_fields)."\n"; print "Mapped LDAP fields=" . join(',', $required_fields) . "\n";
print "\n"; print "\n";
if (! $confirmed) if (! $confirmed) {
{
print "Hit Enter to continue or CTRL+C to stop...\n"; print "Hit Enter to continue or CTRL+C to stop...\n";
$input = trim(fgets(STDIN)); $input = trim(fgets(STDIN));
} }
if (empty($conf->global->LDAP_USER_DN)) if (empty($conf->global->LDAP_USER_DN)) {
{ print $langs->trans("Error") . ': ' . $langs->trans("LDAP setup for users not defined inside Dolibarr");
print $langs->trans("Error").': '.$langs->trans("LDAP setup for users not defined inside Dolibarr"); exit(- 1);
exit(-1);
} }
// Load table of correspondence of countries // Load table of correspondence of countries
$hashlib2rowid=array(); $hashlib2rowid = array();
$countries=array(); $countries = array();
$sql = "SELECT rowid, code, label, active"; $sql = "SELECT rowid, code, label, active";
$sql.= " FROM ".MAIN_DB_PREFIX."c_country"; $sql .= " FROM " . MAIN_DB_PREFIX . "c_country";
$sql.= " WHERE active = 1"; $sql .= " WHERE active = 1";
$sql.= " ORDER BY code ASC"; $sql .= " ORDER BY code ASC";
$resql=$db->query($sql); $resql = $db->query($sql);
if ($resql) if ($resql) {
{
$num = $db->num_rows($resql); $num = $db->num_rows($resql);
$i = 0; $i = 0;
if ($num) if ($num) {
{ while ($i < $num) {
while ($i < $num)
{
$obj = $db->fetch_object($resql); $obj = $db->fetch_object($resql);
if ($obj) if ($obj) {
{ // print 'Load cache for country '.strtolower($obj->label).' rowid='.$obj->rowid."\n";
//print 'Load cache for country '.strtolower($obj->label).' rowid='.$obj->rowid."\n"; $hashlib2rowid[strtolower($obj->label)] = $obj->rowid;
$hashlib2rowid[strtolower($obj->label)]=$obj->rowid; $countries[$obj->rowid] = array('rowid' => $obj->rowid,'label' => $obj->label,'code' => $obj->code);
$countries[$obj->rowid]=array('rowid' => $obj->rowid, 'label' => $obj->label, 'code' => $obj->code);
} }
$i++; $i ++;
} }
} }
} } else {
else
{
dol_print_error($db); dol_print_error($db);
exit(-1); exit(- 1);
} }
$ldap = new Ldap(); $ldap = new Ldap();
$result = $ldap->connect_bind(); $result = $ldap->connect_bind();
if ($result >= 0) if ($result >= 0) {
{ $justthese = array();
$justthese=array();
// We disable synchro Dolibarr-LDAP // We disable synchro Dolibarr-LDAP
$conf->global->LDAP_SYNCHRO_ACTIVE=0; $conf->global->LDAP_SYNCHRO_ACTIVE = 0;
$ldaprecords = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, $required_fields, 'user'); // Fiter on 'user' filter param $ldaprecords = $ldap->getRecords('*', $conf->global->LDAP_USER_DN, $conf->global->LDAP_KEY_USERS, $required_fields, 'user'); // Fiter on 'user' filter param
if (is_array($ldaprecords)) if (is_array($ldaprecords)) {
{
$db->begin(); $db->begin();
// Warning $ldapuser has a key in lowercase // Warning $ldapuser has a key in lowercase
foreach ($ldaprecords as $key => $ldapuser) foreach ($ldaprecords as $key => $ldapuser) {
{
// If login into exclude list, we discard record // If login into exclude list, we discard record
if (in_array($ldapuser[$conf->global->LDAP_FIELD_LOGIN], $excludeuser)) if (in_array($ldapuser[$conf->global->LDAP_FIELD_LOGIN], $excludeuser)) {
{ print $langs->transnoentities("UserDiscarded") . ' # ' . $key . ': login=' . $ldapuser[$conf->global->LDAP_FIELD_LOGIN] . ' --> Discarded' . "\n";
print $langs->transnoentities("UserDiscarded").' # '.$key.': login='.$ldapuser[$conf->global->LDAP_FIELD_LOGIN].' --> Discarded'."\n";
continue; continue;
} }
$fuser = new User($db); $fuser = new User($db);
if($conf->global->LDAP_KEY_USERS == $conf->global->LDAP_FIELD_SID) { if ($conf->global->LDAP_KEY_USERS == $conf->global->LDAP_FIELD_SID) {
$fuser->fetch('', '', $ldapuser[$conf->global->LDAP_KEY_USERS]); // Chargement du user concerné par le SID $fuser->fetch('', '', $ldapuser[$conf->global->LDAP_KEY_USERS]); // Chargement du user concerné par le SID
} elseif ($conf->global->LDAP_KEY_USERS == $conf->global->LDAP_FIELD_LOGIN) { } elseif ($conf->global->LDAP_KEY_USERS == $conf->global->LDAP_FIELD_LOGIN) {
$fuser->fetch('', $ldapuser[$conf->global->LDAP_KEY_USERS]); // Chargement du user concerné par le login $fuser->fetch('', $ldapuser[$conf->global->LDAP_KEY_USERS]); // Chargement du user concerné par le login
} }
// Propriete membre // Propriete membre
$fuser->firstname=$ldapuser[$conf->global->LDAP_FIELD_FIRSTNAME]; $fuser->firstname = $ldapuser[$conf->global->LDAP_FIELD_FIRSTNAME];
$fuser->lastname=$ldapuser[$conf->global->LDAP_FIELD_NAME]; $fuser->lastname = $ldapuser[$conf->global->LDAP_FIELD_NAME];
$fuser->login=$ldapuser[$conf->global->LDAP_FIELD_LOGIN]; $fuser->login = $ldapuser[$conf->global->LDAP_FIELD_LOGIN];
$fuser->pass=$ldapuser[$conf->global->LDAP_FIELD_PASSWORD]; $fuser->pass = $ldapuser[$conf->global->LDAP_FIELD_PASSWORD];
$fuser->pass_indatabase_crypted=$ldapuser[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED]; $fuser->pass_indatabase_crypted = $ldapuser[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED];
//$user->societe; // $user->societe;
/* /*
$fuser->address=$ldapuser[$conf->global->LDAP_FIELD_ADDRESS]; * $fuser->address=$ldapuser[$conf->global->LDAP_FIELD_ADDRESS];
$fuser->zip=$ldapuser[$conf->global->LDAP_FIELD_ZIP]; * $fuser->zip=$ldapuser[$conf->global->LDAP_FIELD_ZIP];
$fuser->town=$ldapuser[$conf->global->LDAP_FIELD_TOWN]; * $fuser->town=$ldapuser[$conf->global->LDAP_FIELD_TOWN];
$fuser->country=$ldapuser[$conf->global->LDAP_FIELD_COUNTRY]; * $fuser->country=$ldapuser[$conf->global->LDAP_FIELD_COUNTRY];
$fuser->country_id=$countries[$hashlib2rowid[strtolower($fuser->country)]]['rowid']; * $fuser->country_id=$countries[$hashlib2rowid[strtolower($fuser->country)]]['rowid'];
$fuser->country_code=$countries[$hashlib2rowid[strtolower($fuser->country)]]['code']; * $fuser->country_code=$countries[$hashlib2rowid[strtolower($fuser->country)]]['code'];
*/ */
$fuser->office_phone=$ldapuser[$conf->global->LDAP_FIELD_PHONE]; $fuser->office_phone = $ldapuser[$conf->global->LDAP_FIELD_PHONE];
$fuser->user_mobile=$ldapuser[$conf->global->LDAP_FIELD_MOBILE]; $fuser->user_mobile = $ldapuser[$conf->global->LDAP_FIELD_MOBILE];
$fuser->office_fax=$ldapuser[$conf->global->LDAP_FIELD_FAX]; $fuser->office_fax = $ldapuser[$conf->global->LDAP_FIELD_FAX];
$fuser->email=$ldapuser[$conf->global->LDAP_FIELD_MAIL]; $fuser->email = $ldapuser[$conf->global->LDAP_FIELD_MAIL];
$fuser->ldap_sid=$ldapuser[$conf->global->LDAP_FIELD_SID]; $fuser->ldap_sid = $ldapuser[$conf->global->LDAP_FIELD_SID];
$fuser->job=$ldapuser[$conf->global->LDAP_FIELD_TITLE]; $fuser->job = $ldapuser[$conf->global->LDAP_FIELD_TITLE];
$fuser->note=$ldapuser[$conf->global->LDAP_FIELD_DESCRIPTION]; $fuser->note = $ldapuser[$conf->global->LDAP_FIELD_DESCRIPTION];
$fuser->admin=0; $fuser->admin = 0;
$fuser->societe_id=0; $fuser->societe_id = 0;
$fuser->contact_id=0; $fuser->contact_id = 0;
$fuser->fk_member=0; $fuser->fk_member = 0;
$fuser->statut=1; $fuser->statut = 1;
// TODO : revoir la gestion du status // TODO : revoir la gestion du status
/*if (isset($ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS])) /*
{ * if (isset($ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS]))
$fuser->datec=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]); * {
$fuser->datevalid=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]); * $fuser->datec=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
$fuser->statut=$ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS]; * $fuser->datevalid=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_MEMBER_FIRSTSUBSCRIPTION_DATE]);
}*/ * $fuser->statut=$ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS];
//if ($fuser->statut > 1) $fuser->statut=1; * }
*/
// if ($fuser->statut > 1) $fuser->statut=1;
//print_r($ldapuser); // print_r($ldapuser);
if($fuser->id > 0) { // User update if ($fuser->id > 0) { // User update
print $langs->transnoentities("UserUpdate").' # '.$key.': login='.$fuser->login.', fullname='.$fuser->getFullName($langs); print $langs->transnoentities("UserUpdate") . ' # ' . $key . ': login=' . $fuser->login . ', fullname=' . $fuser->getFullName($langs);
$res=$fuser->update($user); $res = $fuser->update($user);
if ($res < 0) if ($res < 0) {
{ $error ++;
$error++; print ' --> ' . $res . ' ' . $fuser->error;
print ' --> '.$res.' '.$fuser->error; } else {
} print ' --> Updated user id=' . $fuser->id . ' login=' . $fuser->login;
else
{
print ' --> Updated user id='.$fuser->id.' login='.$fuser->login;
} }
} else { // User creation } else { // User creation
print $langs->transnoentities("UserCreate").' # '.$key.': login='.$fuser->login.', fullname='.$fuser->getFullName($langs); print $langs->transnoentities("UserCreate") . ' # ' . $key . ': login=' . $fuser->login . ', fullname=' . $fuser->getFullName($langs);
$res=$fuser->create($user); $res = $fuser->create($user);
if ($res > 0) if ($res > 0) {
{ print ' --> Created user id=' . $fuser->id . ' login=' . $fuser->login;
print ' --> Created user id='.$fuser->id.' login='.$fuser->login; } else {
} $error ++;
else print ' --> ' . $res . ' ' . $fuser->error;
{
$error++;
print ' --> '.$res.' '.$fuser->error;
} }
} }
print "\n"; print "\n";
//print_r($fuser); // print_r($fuser);
// Gestion des groupes // Gestion des groupes
// TODO : revoir la gestion des groupes (ou script de sync groupes) // TODO : revoir la gestion des groupes (ou script de sync groupes)
/*if(!$error) { /*
foreach ($ldapuser[$conf->global->LDAP_FIELD_USERGROUPS] as $groupdn) { * if(!$error) {
$groupdn; * foreach ($ldapuser[$conf->global->LDAP_FIELD_USERGROUPS] as $groupdn) {
} * $groupdn;
}*/ * }
* }
*/
} }
if (! $error || $forcecommit) if (! $error || $forcecommit) {
{ if (! $error)
if (! $error) print $langs->transnoentities("NoErrorCommitIsDone")."\n"; print $langs->transnoentities("NoErrorCommitIsDone") . "\n";
else print $langs->transnoentities("ErrorButCommitIsDone")."\n"; else
print $langs->transnoentities("ErrorButCommitIsDone") . "\n";
$db->commit(); $db->commit();
} } else {
else print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error) . "\n";
{
print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
$db->rollback(); $db->rollback();
} }
print "\n"; print "\n";
} } else {
else
{
dol_print_error('', $ldap->error); dol_print_error('', $ldap->error);
$error++; $error ++;
} }
} } else {
else
{
dol_print_error('', $ldap->error); dol_print_error('', $ldap->error);
$error++; $error ++;
} }
exit($error); exit($error);
/** /**
* Function to say if a value is empty or not * Function to say if a value is empty or not
* *
* @param string $element Value to test * @param string $element
* @return boolean True of false * Value to test
* @return boolean True of false
*/ */
function dolValidElement($element) function dolValidElement($element)
{ {

View File

@ -1,8 +1,8 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
/* /*
* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org> * Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2005-2010 Laurent Destailleur <eldy@users.sourceforge.net> * Copyright (C) 2005-2010 Laurent Destailleur <eldy@users.sourceforge.net>
* *
* This program is free software; you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -11,7 +11,7 @@
* *
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
@ -19,39 +19,37 @@
*/ */
/** /**
* \file scripts/withdrawals/build_withdrawal_file.php * \file scripts/withdrawals/build_withdrawal_file.php
* \ingroup prelevement * \ingroup prelevement
* \brief Script de prelevement * \brief Script de prelevement
*/ */
$sapi_type = php_sapi_name(); $sapi_type = php_sapi_name();
$script_file = basename(__FILE__); $script_file = basename(__FILE__);
$path=dirname(__FILE__).'/'; $path = __DIR__ . '/';
// Test if batch mode // Test if batch mode
if (substr($sapi_type, 0, 3) == 'cgi') { if (substr($sapi_type, 0, 3) == 'cgi') {
echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n"; echo "Error: You are using PHP for CGI. To execute " . $script_file . " from command line, you must use PHP for CLI mode.\n";
exit(-1); exit(- 1);
} }
require_once $path."../../htdocs/master.inc.php"; require_once $path . "../../htdocs/master.inc.php";
require_once DOL_DOCUMENT_ROOT."/compta/prelevement/class/bonprelevement.class.php"; require_once DOL_DOCUMENT_ROOT . "/compta/prelevement/class/bonprelevement.class.php";
require_once DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php"; require_once DOL_DOCUMENT_ROOT . "/compta/facture/class/facture.class.php";
require_once DOL_DOCUMENT_ROOT."/societe/class/societe.class.php"; require_once DOL_DOCUMENT_ROOT . "/societe/class/societe.class.php";
require_once DOL_DOCUMENT_ROOT."/compta/paiement/class/paiement.class.php"; require_once DOL_DOCUMENT_ROOT . "/compta/paiement/class/paiement.class.php";
// Global variables // Global variables
$version=DOL_VERSION; $version = DOL_VERSION;
$error=0; $error = 0;
/* /*
* Main * Main
*/ */
@set_time_limit(0); @set_time_limit(0);
print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n"; print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
dol_syslog($script_file." launched with arg ".join(',', $argv)); dol_syslog($script_file . " launched with arg " . join(',', $argv));
$datetimeprev = dol_now(); $datetimeprev = dol_now();
@ -61,18 +59,16 @@ $year = strftime("%Y", $datetimeprev);
$user = new user($db); $user = new user($db);
$user->fetch($conf->global->PRELEVEMENT_USER); $user->fetch($conf->global->PRELEVEMENT_USER);
if (! isset($argv[1])) { // Check parameters if (! isset($argv[1])) { // Check parameters
print "This script check invoices with a withdrawal request and\n"; print "This script check invoices with a withdrawal request and\n";
print "then create payment and build a withdraw file.\n"; print "then create payment and build a withdraw file.\n";
print "Usage: ".$script_file." simu|real\n"; print "Usage: " . $script_file . " simu|real\n";
exit(-1); exit(- 1);
} }
$withdrawreceipt = new BonPrelevement($db);
$withdrawreceipt=new BonPrelevement($db);
// $conf->global->PRELEVEMENT_CODE_BANQUE and $conf->global->PRELEVEMENT_CODE_GUICHET should be empty // $conf->global->PRELEVEMENT_CODE_BANQUE and $conf->global->PRELEVEMENT_CODE_GUICHET should be empty
$result=$withdrawreceipt->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $argv[1]); $result = $withdrawreceipt->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $argv[1]);
$db->close(); $db->close();