diff --git a/.editorconfig b/.editorconfig
index 3c4bd7d679d..3e3bd16bb34 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -1,7 +1,8 @@
-# EditorConfig is awesome: http://EditorConfig.org
+# EditorConfig is awesome: https://editorconfig.org
# top-most EditorConfig file
root = true
+
# Unix-style newlines with a newline ending every file
[*]
charset = utf-8
@@ -11,9 +12,10 @@ insert_final_newline = true
# PHP PSR-2 Coding Standards
# http://www.php-fig.org/psr/psr-2/
[*.php]
-indent_style = space
+indent_style = tab
indent_size = 4
trim_trailing_whitespace = true
+insert_final_newline = true
[*.js]
indent_style = tab
[*.css]
diff --git a/COPYRIGHT b/COPYRIGHT
index 510bf5d3b4f..7cebde7c362 100644
--- a/COPYRIGHT
+++ b/COPYRIGHT
@@ -19,7 +19,7 @@ PHPDebugBar 1.15.0 MIT License Yes Used only by
EvalMath 1.0 BSD Yes Safe math expressions evaluation
Escpos-php ? MIT License Yes Thermal receipt printer library, for use with ESC/POS compatible printers
GeoIP 1.4 LGPL-2.1+ Yes Sample code to make geoip convert (not into deb package)
-Mobiledetect 2.8.17 MIT License Yes Detect mobile devices browsers
+Mobiledetect 2.8.83 MIT License Yes Detect mobile devices browsers
NuSoap 0.9.5 LGPL 2.1+ Yes Library to develop SOAP Web services (not into rpm and deb package)
PEAR Mail_MIME 1.8.9 BSD Yes NuSoap dependency
odtPHP 1.0.1 GPL-2+ Yes Library to build/edit ODT files
diff --git a/ChangeLog b/ChangeLog
index 355d9baa561..70ae8ff8b5c 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -6,21 +6,160 @@ English Dolibarr ChangeLog
***** ChangeLog for 10.0.0 compared to 9.0.0 *****
For Users:
NEW: Module "Ticket" is available as a stable module.
-NEW: module "Email Collector" is available as a stable module.
-NEW: module "TakePOS" is available as a stable module.
+NEW: Module "Email Collector" is available as a stable module.
+NEW: Module "TakePOS" is available as a stable module.
NEW: Experimental module "Vendor receptions".
NEW: Experimental module "BOM".
-FIX: Disallow line start date if after end date.
+NEW: Accounting - Add default accounting account for member subcriptions.
+NEW: Accounting - More comprehensive menu.
+NEW: Agenda/event - add description column available in list (hidden by default).
+NEW: Add accounting account for result.
+NEW: Add accounting code for EEC sales and export sales on products.
+NEW: Add a security permission to edit php dynamic content on the WebSite module.
+NEW: Attached document on bank account are now visible in automatic ECM.
+NEW: Add Autofill Remainder Amount picto on the Expense Report Payment Page.
+NEW: Add contact status in category export
+NEW: Add Default Warehouse to user record (if module stock is on)
+NEW: Add employee/user to subledger account list
+NEW: Add gender in member card
+NEW: Add getFormatedCustomerRef and getFormatedSupplierRef methods
+NEW: Add history to view and print previous sales on TakePos.
+NEW: Add import of accounting account for intra/export selling on product card
+NEW: Adding code to show update date of supplier price shown
+NEW: Add line total on list of payments
+NEW: Add LinkedIn field in social network module
+NEW: Add more complete error messages in log on stripe payments
+NEW: Add no_email field in contact list
+NEW: Add notes are show in tooltips
+NEW: Add option DONATION_USE_THIRDPARTIES in admin of membership module
+NEW: Add option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO
+NEW: add page to setup opening hours of the company
+NEW: add payments table to pdf of expense report
+NEW: add payment terms to invoices list
+NEW: Add picto of deletion on mass action combo lists
+NEW: add product extrafields available into shipping export
+NEW: add ref supplier on supplier invoice
+NEW: Add stats on entries & movements by fiscal year
+NEW: Add subledger in various payment module
+NEW: Add tag for ODT generation for localtax rates
+NEW: Add the now link when creating expense report
+NEW: Ask date of invoice when using the Clone feature.
+NEW: auto event msg
+NEW: Automatically binding for intra/export accountancy code in customer list
+NEW: automatic / manual selector form
+NEW: Better explanation for setup of WebDav module
+NEW: Can add more lines on situation invoices at end of project when there is extra to add.
+NEW: Can change the customer account of an instance
+NEW: Can choose the root category to show products for TakePOS module
+NEW: Can edit supplier on draft order supplier
+NEW: Can enter price with or without tax when entering expense repor line
+NEW: Can filter on the date of period for social contributions
+NEW: Can generate invoices from the timespent entered on a project
+NEW: Can update product supplier price ref
+NEW: Can upload files from the edit page of expense report
+NEW: Color for hover and for checked line is on by default
+NEW: Column of parent company is available in list of third parties
+NEW: conditionnal add member button by statut
+NEW: constant KEEP_DISCOUNT_LINES_FROM_ORIGIN
+NEW: Contact related items tab
+NEW: Can create of supplier invoice from a reception
+NEW: Ensure External RSS Links Open in New Window
+NEW: Export available for reception module
+NEW: Extend import option to Order's card and Propal's card
+NEW: filter by thirdparty on report CA by prod/serv
+NEW: Save space by moving the meteo on the title line
+NEW: Get the list of groups of a user with the REST API.
+NEW: Hidden option MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER to edit supplier on draft supplier order
+NEW: Improve Displaying Shortcut Access Keys in Navigation.
+NEW: Improve Expensereport, Inverse Receiver.
+NEW: Improve pdf description item visibitity.
+NEW: Introduce a config parameter $dolibarr_main_instance_unique_id
+NEW: Introduce css "nobottomiftotal"
+NEW: Introduce PhpSpreadsheet for export (need php5.6+)
+NEW: Invoice creation from the timesheet
+NEW: Can list remote stripe's payout in a dedicated page.
+NEW: Manage account sell_intra & sell_export in page accoutancy admin default product
+NEW: Manage loan schedule.
+NEW: Manage status of member types.
+NEW: Mass action "create bills" for validated reception
+NEW: Measuring unit are now defined into an editable dictionary. Add product size/unit into product import.
+NEW: Template pdf 'canelle_reception' displays linked reception lines.
+NEW: Moral/physic status can be defined at member type level
+NEW: Pagination into list of time spent.
+NEW: Performance enhancement (Replace dirname(__FILE__) with __DIR__)
+NEW: POS support in order (ex: online cart).
+NEW: Preview of images into the filemanager component.
+NEW: Resource module can be used in products/services (in a dedicated tab)
+NEW: Retrieve invoice infos from order when billing shipment
+NEW: Save and display type of membership in subscription table for more explicit historic
+NEW: Setup default thirdparty type (customer or prospect/customer)
+NEW: Add shipping "set draft" button and can update lines.
+NEW: show in blod, the invoice amount where we came from, when making payment
+NEW: Show product dimensions in product tooltips.
+NEW: Show the latest date of subscription in member statistics reports.
+NEW: Sort list of templates alphabetically
+NEW: Stripe Payment Intent (need option to use this new Stripe api method)
+NEW: Can support barcode on supplier price references.
+NEW: Support tag {ccc} on payment ref
+NEW: The preview of PDF files generates only 1 png file, even if several pages.
+NEW: Can select a Thirdparty object in donation module if option ON.
+NEW: Tooltip with VAT amount and price incl tax on lines of objects.
+NEW: Unsubscribed emails are now stored in a dedicated table.
+NEW: Update working chkbxlst filter for lists.
+NEW: Use ajax switch into setup of donation.php and multi-currency module.
+NEW: use recipient language when generating the fullname for emails.
+NEW: When you create product or service, sell accountancy account by default is suggested.
+NEW: Widget birthdays of the month.
+NEW: Option in workflow module to set a reception billed on validate supplier bill.
+NEW: Autocompletion on lists should be available on mobile applications.
For Developers:
NEW: Module "DebugBar" is available as a stable module.
+NEW: Add API REST for donations
+NEW: Add a script 'purge-data.php' to purge data older than a defined creation date
+NEW: Add constant XFRAMEOPTIONS_ALLOWALL
+NEW: Add function isValidVATID()
+NEW: ADD document's product support in APIs
+NEW: REST API: get the list of objects in a category.
+NEW: Update Stripe library to 6.34.3
+NEW: Upgrade jquery lib to 3.3.1
+NEW: Add hook 'addHtmlHeader()'
+NEW: Add hook 'createRecurringInvoices()'
+NEW: Add hook 'afterSelectContactOptions'
+NEW: Add hook support in accountancy index
+NEW: Add hook support in list of template invoices
+NEW: Add parameter 'replaceambiguouschars' on getRandomPassword function
+NEW: Add property 'noteditable' in modulebuilder
+NEW: Add the current modulepart into the Conf class object
+NEW: Add trigger FICHINTER_UNVALIDATE
+NEW: Add visibility with value 4 in framework to define fields to show
+NEW: More option to tune initialization of a new module with modulebuilder.
+NEW: API to list currencies
+NEW: API Proposal, Orders, Invoices: Add contact details
+NEW: hidden option to change concat desc order
+NEW: Enhance management of webhooks
+NEW: Generation of doc by modulebuilder can include README and CHANGELOG
+NEW: massfilesarea feature for external modules
+NEW: Show enabled modules in dol_print_error()
+NEW: Simplification of CSS styles of default themes.
+NEW: Clean code of a lot of deprecated code.
+NEW: Add hidden option to set a search entry to the top
+NEW: add hidden option DISPLAY_DISCOUNTED_SUPPLIER_PRICE
+NEW: add hidden option MAIN_DEFAULT_LANGUAGE_FILTER
+NEW: add hidden option NO_CONCAT_DESCRIPTION
+NEW: Add hidden option for ACCOUNTANCY_COMBO_FOR_AUX
+NEW: Add hidden option 'ADD_UNSPLASH_LOGIN_BACKGROUND'
+NEW: Add Hidden option 'OVERRIDE_VAT_FOR_EXPENSE_REPORT'
+NEW: add hidden option MAIN_DOC_UPLOAD_NOT_RENAME_BY_DEFAULT
+NEW: Hidden conf to improve pdf desc item visibitity
+NEW: Look and feel v10 - Add CSS 'tabBarNoTop'
WARNING:
Following changes may create regressions for some external modules, but were necessary to make Dolibarr better:
* PHP 5.4 is no more supported. Minimum PHP is now 5.5+.
-* The PHP extension php-intl is not mandatory but should be installed to have new features working correctly.
+* The PHP extension php-intl is not mandatory and must be installed to have new features working correctly.
* Method GetUrlTrackingStatus were renamed into getUrlTrackingStatus for consistency with naming rules.
* API getListOfCivility has been renamed into getListOfCivilities for consistency with naming rules.
* Deprecated function img_phone as been removed. You can use img_picto(..., 'call|call_out') instead.;
@@ -69,6 +208,7 @@ FIX: Total per day shows 00:00 if the total time spent is equal to 12:00
FIX: Update/delete currency on same languages
FIX: Wrong variable name make contact of supplier order not used on PDF.
FIX: Add hidden option MAIN_PDF_HIDE_SITUATION to hide situation (quick hack to fix output pb).
+FIX: attached files list with link file was broked
***** ChangeLog for 9.0.2 compared to 9.0.1 *****
FIX: #10822
@@ -289,6 +429,90 @@ Following changes may create regressions for some external modules, but were nec
* Remove the no more used and deprecated dol_print_graph function
+***** ChangeLog for 8.0.5 compared to 8.0.4 *****
+FIX: #10381
+FIX: #10460 compatibility with MariaDB 10.4
+FIX: #11025
+FIX: Accountancy - Add transaction with multicompany use all the time 1st entity
+FIX: Accountancy - Format EBP import
+FIX: actioncomm export: ORDER BY clause is in wrong export property + event type filter does not work
+FIX: actioncomm: sort events by date after external calendars and hook
+FIX: action list: add printFieldListSelect and printFieldListWhere hooks
+FIX: add fk_unit on addline action
+FIX: avoid php warning
+FIX: bad sql request
+FIX: better method
+FIX: better test
+FIX: better test on fetch
+FIX: broken external authentication module feature and avoid warning
+FIX: Can not create contract with numbering module without autogen rule
+FIX: can't add lines on invoices
+FIX: Can't generate invoice pdf
+FIX: Can't insert if there is extrafields mandatory on another entity.
+FIX: Can't insert if there is extrafields mandatory on another entity. FIX: Can't set default value of extrafield of type varchar
+FIX: Check for old picture name if the new one was not found
+FIX: Civility not saved when creating a member.
+FIX: $conf->fournisseur->commande->enabled doesn't exist, we must use $conf->fournisseur->enabled
+FIX: could not create several superadmin in transversal mode
+FIX: credit note can have negative value
+FIX: Default value on sales representative on third party creation
+FIX: Don't show journal:getNomUrl without data
+FIX: Erreur dans le Total
+FIX: error messages not displayed
+FIX: expedition: reset status on rollback + replace hardcoded status with const
+FIX: Fix PHP warning "count(): Parameter must be an array..."
+FIX: fk_default_warehouse missing in group by
+FIX: function sendEmailsReminder isn't completely developed, then MAIN_FEATURES_LEVEL must be 2 to "use" it
+FIX: holidays get natural_search if search params are set only
+FIX: if empty error message, we just see "error" displayed
+FIX: if(!method_exists(dol_loginfunction))
+FIX: If we build one invoice for several orders, we must put the ref of order on the line to not lose information.
+FIX: in fact expensereport must be in $check array
+FIX: Interface regression for bind people. Fix option MAIN_OPTIMIZEFORTEXTBROWSER
+FIX: line edit template: keep fk_parent_line
+FIX: Loan impossible to account
+FIX: Mark credit note as available for credit note in other currency
+FIX: missing access security checking with multicompany
+FIX: missing entity filter and wrong var name
+FIX: missing entity filter in function "build_filterField()" (export)
+FIX: Missing field in import/export of users
+FIX: missing hook completeTabsHead in margins module
+FIX: missing $ismultientitymanaged for previous/next ref
+FIX: Missing province in export of invoice
+FIX: multicompany compatibility
+FIX: must fetch member in current entity
+FIX: need an order by in case we found other invoice with same number but not same date
+FIX: need to round with 2 decimals to avoid movements not correctly balanced
+FIX: no need to test anything to display documents tabs on expense report
+FIX: positive values creating diff on addline rounding
+FIX: problem with multicompany transverse mode
+FIX: Product accountancey sell intra code must be visible if main feature level 1
+FIX: project_title for display of getNomUrl()
+FIX: quick search for supplier orders
+FIX: Remane of project
+FIX: same thing here
+FIX: Selection of email recipient with option MAIN_OPTIMIZEFORTEXTBROWSER
+FIX: several hooks in shipping/delivery cards
+FIX: shipping default warehouse if only one warehouse
+FIX: SQL injection on rowid of dict.php
+FIX: 'statut' is ignored when updating a user with the REST API.
+FIX: supplier invoice payment total dont care about deposit or credit
+FIX: supplier invoice product stats total ht is line total not invoice total
+FIX: The minimum amount filter does not work in the VAT report per customer
+FIX: Total per day shows 00:00 if the total time spent is equal to 12:00
+FIX: Update/delete currency on same languages
+FIX: [URGENT] broken feature, "$usercancreate" is for Dolibarr 9
+FIX: useless join
+FIX: we need to keep originline special_code
+FIX: we want to be able to reopen fourn credit note
+FIX: when 2 extra fields are mandatory in 2 different entities
+FIX: when we add a payment on an invoice which already has payments with credit note or deposit amount, and then we get an excess received, discount amount must be $total_paiements + $total_creditnote_and_deposit - $object->total_ttc;
+FIX: when we create deposit with multi tva, we mustn't add line if amount = 0 (example when we have a 100% reduc on one of origin invoice line)
+FIX: wrong redirect link on holiday refuse
+FIX: wrong test enabled
+FIX: Wrong variable name
+FIX: XSS
+
***** ChangeLog for 8.0.4 compared to 8.0.3 *****
FIX: #10030 better german chart
FIX: #10036
diff --git a/build/makepack-dolibarr.pl b/build/makepack-dolibarr.pl
index 8f9951ef157..b2aa49927e2 100755
--- a/build/makepack-dolibarr.pl
+++ b/build/makepack-dolibarr.pl
@@ -357,7 +357,7 @@ if ($nboftargetok) {
}
else
{
- print "ChangeLog for $MAJOR.$MINOR\.$BUILD was found into '$SOURCE/ChangeLog. But you can regenerate it with command:'\n";
+ print "ChangeLog for $MAJOR.$MINOR\.$BUILD was found into '$SOURCE/ChangeLog'. But you can regenerate it with command:\n";
}
if (! $BUILD || $BUILD eq '0-rc') # For a major version
{
diff --git a/htdocs/admin/company.php b/htdocs/admin/company.php
index 878a1081b40..54f3a4cbb73 100644
--- a/htdocs/admin/company.php
+++ b/htdocs/admin/company.php
@@ -271,7 +271,7 @@ if ($action == 'addthumb') // Regenerate thumbs
$error++;
$langs->load("errors");
setEventMessages($langs->trans("ErrorBadImageFormat"), null, 'errors');
- dol_syslog($langs->transnoentities("ErrorBadImageFormat"), LOG_WARNING);
+ dol_syslog($langs->transnoentities("ErrorBadImageFormat"), LOG_INFO);
}
}
else
@@ -412,9 +412,9 @@ if ($action == 'edit' || $action == 'updateedit')
}
// Logo
- print '
'.$langs->trans("Logo").' (png,jpg) ';
print '';
- print ' ';
+ print ' ';
print ' ';
if (! empty($mysoc->logo_mini)) {
print ''.img_delete($langs->trans("Delete")).' ';
@@ -798,9 +798,9 @@ else
print ' ';
// Barcode
+
if (! empty($conf->barcode->enabled))
{
-
print ''.$langs->trans("Gencod").' ' . $conf->global->MAIN_INFO_SOCIETE_GENCOD . ' ';
}
diff --git a/htdocs/admin/holiday.php b/htdocs/admin/holiday.php
index d67451812c6..347d45d729d 100644
--- a/htdocs/admin/holiday.php
+++ b/htdocs/admin/holiday.php
@@ -1,8 +1,8 @@
+/* Copyright (C) 2011-2019 Juanjo Menent
* Copyright (C) 2011-2018 Philippe Grand
* Copyright (C) 2018 Charlene Benke
- * Copyright (C) 2018 Frédéric France
+ * Copyright (C) 2018 Frédéric France
*
* 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
@@ -55,7 +55,7 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setmoduleoptions.inc.php';
if ($action == 'updateMask')
{
- $maskconst = GETPOST('maskconstholidaty', 'alpha');
+ $maskconst = GETPOST('maskconstholiday', 'alpha');
$maskvalue = GETPOST('maskholiday', 'alpha');
if ($maskconst) $res = dolibarr_set_const($db, $maskconst, $maskvalue, 'chaine', 0, '', $conf->entity);
diff --git a/htdocs/admin/workflow.php b/htdocs/admin/workflow.php
index 380f2cac9e3..b1e8c310ed0 100644
--- a/htdocs/admin/workflow.php
+++ b/htdocs/admin/workflow.php
@@ -34,9 +34,11 @@ if (! $user->admin) accessforbidden();
$action = GETPOST('action', 'alpha');
+
/*
* Actions
*/
+
if (preg_match('/set(.*)/', $action, $reg))
{
if (! dolibarr_set_const($db, $reg[1], '1', 'chaine', 0, '', $conf->entity) > 0)
@@ -47,7 +49,7 @@ if (preg_match('/set(.*)/', $action, $reg))
if (preg_match('/del(.*)/', $action, $reg))
{
- if (! dolibarr_del_const($db, $reg[1], $conf->entity) > 0)
+ if (! dolibarr_set_const($db, $reg[1], '0', 'chaine', 0, '', $conf->entity) > 0)
{
dol_print_error($db);
}
@@ -87,7 +89,7 @@ $workflowcodes=array(
// Automatic classification supplier order
'WORKFLOW_INVOICE_AMOUNT_CLASSIFY_BILLED_SUPPLIER_ORDER'=>array('family'=>'classify_supplier_order', 'position'=>62, 'enabled'=>'! empty($conf->fournisseur->enabled)', 'picto'=>'order','warning'=>''),
//Automatic classification reception
- 'WORKFLOW_BILL_ON_RECEPTION'=>array('family'=>'classify_reception', 'position'=>30, 'enabled'=>'! empty($conf->reception->enabled) && ! empty($conf->fournisseur->enabled)', 'picto'=>'bill'),
+ 'WORKFLOW_BILL_ON_RECEPTION'=>array('family'=>'classify_reception', 'position'=>64, 'enabled'=>'! empty($conf->reception->enabled) && ! empty($conf->fournisseur->enabled)', 'picto'=>'bill'),
);
if (! empty($conf->modules_parts['workflow']) && is_array($conf->modules_parts['workflow']))
diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php
index 19fe59062dd..b02f788f040 100644
--- a/htdocs/comm/propal/list.php
+++ b/htdocs/comm/propal/list.php
@@ -429,9 +429,9 @@ if ($resql)
// List of mass actions available
$arrayofmassactions = array(
- 'generate_doc'=>$langs->trans("Generate"),
- 'presend'=>$langs->trans("SendByMail"),
+ 'generate_doc'=>$langs->trans("ReGeneratePDF"),
'builddoc'=>$langs->trans("PDFMerge"),
+ 'presend'=>$langs->trans("SendByMail"),
);
if ($user->rights->propal->supprimer) $arrayofmassactions['predelete']=' '.$langs->trans("Delete");
if ($user->rights->propal->cloturer) $arrayofmassactions['closed']=$langs->trans("Close");
@@ -806,7 +806,7 @@ if ($resql)
if (! empty($arrayfields['pr.title']['checked']))
{
- // Project ref
+ // Project label
print '';
if ($obj->project_id > 0) {
print $projectstatic->title;
diff --git a/htdocs/commande/list.php b/htdocs/commande/list.php
index 4ff7fe364bd..ad3fd777a5c 100644
--- a/htdocs/commande/list.php
+++ b/htdocs/commande/list.php
@@ -430,11 +430,10 @@ if ($resql)
// List of mass actions available
$arrayofmassactions = array(
- 'generate_doc'=>$langs->trans("Generate"),
- 'presend'=>$langs->trans("SendByMail"),
+ 'generate_doc'=>$langs->trans("ReGeneratePDF"),
'builddoc'=>$langs->trans("PDFMerge"),
'cancelorders'=>$langs->trans("Cancel"),
-
+ 'presend'=>$langs->trans("SendByMail"),
);
if($user->rights->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer");
if ($user->rights->commande->supprimer) $arrayofmassactions['predelete']=' '.$langs->trans("Delete");
diff --git a/htdocs/commande/orderstoinvoice.php b/htdocs/commande/orderstoinvoice.php
index fe017a6b1aa..0d0b202a8c3 100644
--- a/htdocs/commande/orderstoinvoice.php
+++ b/htdocs/commande/orderstoinvoice.php
@@ -1,6 +1,6 @@
- * Copyright (C) 2004-2013 Laurent Destailleur
+ * Copyright (C) 2004-2019 Laurent Destailleur
* Copyright (C) 2005 Marc Barilley / Ocebo
* Copyright (C) 2005-2012 Regis Houssin
* Copyright (C) 2012 Andreu Bisquerra Gaya
@@ -50,14 +50,14 @@ $id = (GETPOST('id')?GETPOST('id', 'int'):GETPOST("facid", "int")); // For b
$ref = GETPOST('ref', 'alpha');
$action = GETPOST('action', 'alpha');
$confirm = GETPOST('confirm', 'alpha');
-$sref = GETPOST('sref');
-$sref_client = GETPOST('sref_client');
+$sref = GETPOST('sref', 'alpha');
+$sref_client = GETPOST('sref_client', 'alpha');
$sall = trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml'));
$socid = GETPOST('socid', 'int');
$selected = GETPOST('orders_to_invoice');
$sortfield = GETPOST("sortfield", 'alpha');
$sortorder = GETPOST("sortorder", 'alpha');
-$viewstatut = GETPOST('viewstatut');
+$viewstatut = GETPOST('viewstatut', 'alpha');
$error = 0;
@@ -290,32 +290,32 @@ if (($action == 'create' || $action == 'add') && !$error)
$array_options = $lines[$i]->array_options;
}
- $result = $object->addline(
- $desc,
- $lines[$i]->subprice,
- $lines[$i]->qty,
- $lines[$i]->tva_tx,
- $lines[$i]->localtax1_tx,
- $lines[$i]->localtax2_tx,
- $lines[$i]->fk_product,
- $lines[$i]->remise_percent,
- $date_start,
- $date_end,
- 0,
- $lines[$i]->info_bits,
- $lines[$i]->fk_remise_except,
- 'HT',
- 0,
- $product_type,
- $ii,
- $lines[$i]->special_code,
- $object->origin,
- $lines[$i]->rowid,
- $fk_parent_line,
- $lines[$i]->fk_fournprice,
- $lines[$i]->pa_ht,
- $lines[$i]->label,
- $array_options
+ $result = $object->addline(
+ $desc,
+ $lines[$i]->subprice,
+ $lines[$i]->qty,
+ $lines[$i]->tva_tx,
+ $lines[$i]->localtax1_tx,
+ $lines[$i]->localtax2_tx,
+ $lines[$i]->fk_product,
+ $lines[$i]->remise_percent,
+ $date_start,
+ $date_end,
+ 0,
+ $lines[$i]->info_bits,
+ $lines[$i]->fk_remise_except,
+ 'HT',
+ 0,
+ $product_type,
+ $ii,
+ $lines[$i]->special_code,
+ $object->origin,
+ $lines[$i]->rowid,
+ $fk_parent_line,
+ $lines[$i]->fk_fournprice,
+ $lines[$i]->pa_ht,
+ $lines[$i]->label,
+ $array_options
);
if ($result > 0)
{
@@ -578,9 +578,9 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error)
{
$sql.= ' AND c.ref_client LIKE \'%'.$db->escape($sref_client).'%\'';
}
- $sql.= ' ORDER BY '.$sortfield.' '.$sortorder;
- $resql = $db->query($sql);
+ $sql.= $db->order($sortfield, $sortorder);
+ $resql = $db->query($sql);
if ($resql)
{
if ($socid)
@@ -604,6 +604,7 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error)
print ''.$companystatic->getNomUrl(1, 'customer').' ';
}
+ print '';
print '
';
print '';
print_liste_field_titre('Ref', $_SERVER["PHP_SELF"], 'c.ref', '', '&socid='.$socid, '', $sortfield, $sortorder);
@@ -618,8 +619,9 @@ if (($action != 'create' && $action != 'add') || ($action == 'create' && $error)
print '
'."\n";
print "\n";
-print '
';
+print '
';
// EMail support
print '
';
@@ -135,7 +135,7 @@ print '';
print '
'."\n";
-print '
';
+print '
';
// Other support
diff --git a/htdocs/theme/eldy/global.inc.php b/htdocs/theme/eldy/global.inc.php
index b797ec69b9e..c07fad24dab 100644
--- a/htdocs/theme/eldy/global.inc.php
+++ b/htdocs/theme/eldy/global.inc.php
@@ -266,6 +266,10 @@ input#onlinepaymenturl, input#directdownloadlink {
opacity: 0.7;
}
+div#moretabsListaction {
+ z-index: 5;
+}
+
hr { border: 0; border-top: 1px solid #ccc; }
.tabBar hr { margin-top: 20px; margin-bottom: 17px; }
@@ -857,7 +861,7 @@ select.selectarrowonleft option {
input, input[type=text], input[type=password], select, textarea {
min-width: 20px;
}
- input[type=text], input[type=password] {
+ .trinputlogin input[type=text], input[type=password] {
max-width: 180px;
}
.vmenu .searchform input {
@@ -2251,8 +2255,8 @@ div.popuptabset {
border: 1px solid #888;
}
div.popuptab {
- padding-top: 3px;
- padding-bottom: 3px;
+ padding-top: 5px;
+ padding-bottom: 5px;
padding-left: 5px;
padding-right: 5px;
}
diff --git a/htdocs/theme/md/style.css.php b/htdocs/theme/md/style.css.php
index 2906da3729c..3aea173df6c 100644
--- a/htdocs/theme/md/style.css.php
+++ b/htdocs/theme/md/style.css.php
@@ -492,6 +492,10 @@ input[name=surface] { margin-right: 4px; }
fieldset { border: 1px solid #AAAAAA !important; }
.legendforfieldsetstep { padding-bottom: 10px; }
+div#moretabsListaction {
+ z-index: 5;
+}
+
hr { border: 0; border-top: 1px solid #ccc; }
.button, .buttonDelete, input[name="sbmtConnexion"] {
@@ -2405,8 +2409,8 @@ div.popuptabset {
border: 1px solid #888;
}
div.popuptab {
- padding-top: 3px;
- padding-bottom: 3px;
+ padding-top: 5px;
+ padding-bottom: 5px;
padding-left: 5px;
padding-right: 5px;
}
diff --git a/htdocs/ticket/card.php b/htdocs/ticket/card.php
index 26fec804370..475c9f5beae 100644
--- a/htdocs/ticket/card.php
+++ b/htdocs/ticket/card.php
@@ -283,8 +283,8 @@ if (GETPOST('update') && GETPOST('id') && $user->rights->ticket->write) {
if (!$error) {
$db->begin();
- $object->label = GETPOST("label");
- $object->description = GETPOST("description");
+ $object->label = GETPOST("label", 'alphanohtml');
+ $object->description = GETPOST("description", 'none');
//...
$ret = $object->update($user);
@@ -302,6 +302,7 @@ if (GETPOST('update') && GETPOST('id') && $user->rights->ticket->write) {
}
}
+// Mark as Read
if ($action == "mark_ticket_read" && $user->rights->ticket->write) {
$object->fetch('', '', GETPOST("track_id", 'alpha'));
@@ -317,6 +318,7 @@ if ($action == "mark_ticket_read" && $user->rights->ticket->write) {
$action = 'view';
}
+// Assign to someone
if ($action == "assign_user" && GETPOST('btn_assign_user', 'aplha') && $user->rights->ticket->write) {
$object->fetch('', '', GETPOST("track_id", 'alpha'));
$useroriginassign = $object->fk_user_assign;
diff --git a/htdocs/ticket/class/ticket.class.php b/htdocs/ticket/class/ticket.class.php
index c049712d623..5430932f53d 100644
--- a/htdocs/ticket/class/ticket.class.php
+++ b/htdocs/ticket/class/ticket.class.php
@@ -1370,7 +1370,7 @@ class Ticket extends CommonObject
$this->db->begin();
$sql = "UPDATE " . MAIN_DB_PREFIX . "ticket";
- $sql .= " SET fk_statut = 1, date_read='" . $this->db->idate(dol_now()) . "'";
+ $sql .= " SET fk_statut = ".Ticket::STATUS_READ.", date_read='" . $this->db->idate(dol_now()) . "'";
$sql .= " WHERE rowid = " . $this->id;
dol_syslog(get_class($this) . "::markAsRead");
@@ -1388,7 +1388,6 @@ class Ticket extends CommonObject
// End call triggers
}
-
if (!$error) {
$this->db->commit();
return 1;
@@ -1421,20 +1420,23 @@ class Ticket extends CommonObject
$this->db->begin();
+ $this->oldcopy = dol_clone($this);
+
$sql = "UPDATE " . MAIN_DB_PREFIX . "ticket";
if ($id_assign_user > 0)
{
- $sql .= " SET fk_user_assign=".$id_assign_user.", fk_statut=4";
+ $sql .= " SET fk_user_assign=".$id_assign_user.", fk_statut = ".Ticket::STATUS_ASSIGNED;
}
else
{
- $sql .= " SET fk_user_assign=null, fk_statut=1";
+ $sql .= " SET fk_user_assign=null, fk_statut = ".Ticket::STATUS_READ;
}
$sql .= " WHERE rowid = " . $this->id;
dol_syslog(get_class($this) . "::assignUser sql=" . $sql);
$resql = $this->db->query($sql);
- if ($resql) {
+ if ($resql)
+ {
$this->fk_user_assign = $id_assign_user; // May be used by trigger
if (! $notrigger) {
@@ -1710,11 +1712,11 @@ class Ticket extends CommonObject
{
global $conf, $langs;
- if ($this->fk_statut != 9) { // not closed
+ if ($this->fk_statut != Ticket::STATUS_CLOSED) { // not closed
$this->db->begin();
$sql = "UPDATE " . MAIN_DB_PREFIX . "ticket";
- $sql .= " SET fk_statut=8, progress=100, date_close='" . $this->db->idate(dol_now()) . "'";
+ $sql .= " SET fk_statut=".Ticket::STATUS_CLOSED.", progress=100, date_close='" . $this->db->idate(dol_now()) . "'";
$sql .= " WHERE rowid = " . $this->id;
dol_syslog(get_class($this) . "::close sql=" . $sql);
diff --git a/htdocs/user/card.php b/htdocs/user/card.php
index 479604ddc36..926cb50836e 100644
--- a/htdocs/user/card.php
+++ b/htdocs/user/card.php
@@ -423,8 +423,20 @@ if (empty($reshook)) {
if (GETPOST('deletephoto')) {
$object->photo = '';
}
- if (!empty($_FILES['photo']['name'])) {
- $object->photo = dol_sanitizeFileName($_FILES['photo']['name']);
+ if (!empty($_FILES['photo']['name']))
+ {
+ $isimage=image_format_supported($_FILES['photo']['name']);
+ if ($isimage > 0)
+ {
+ $object->photo = dol_sanitizeFileName($_FILES['photo']['name']);
+ }
+ else
+ {
+ $error++;
+ $langs->load("errors");
+ setEventMessages($langs->trans("ErrorBadImageFormat"), null, 'errors');
+ dol_syslog($langs->transnoentities("ErrorBadImageFormat"), LOG_INFO);
+ }
}
if (!$error) {
diff --git a/htdocs/user/perms.php b/htdocs/user/perms.php
index e1551310a43..992de6850db 100644
--- a/htdocs/user/perms.php
+++ b/htdocs/user/perms.php
@@ -272,7 +272,7 @@ if (($caneditperms && empty($objMod->rights_admin_allowed)) || empty($object->ad
{
print '
';
print 'id.'&action=addrights&entity='.$entity.'&module=allmodules">'.$langs->trans("All")." ";
- print '/';
+ print ' / ';
print 'id.'&action=delrights&entity='.$entity.'&module=allmodules">'.$langs->trans("None")." ";
print ' ';
}
@@ -316,27 +316,23 @@ if ($result)
// Show break line
print '
';
- print ''.img_object('', $picto, 'class="pictoobjectwidth"').' '.$objMod->getName();
- print ' ';
+ print '';
+ print img_object('', $picto, 'class="pictoobjectwidth"').' '.$objMod->getName();
+ print ' ';
+ print ' ';
if (($caneditperms && empty($objMod->rights_admin_allowed)) || empty($object->admin))
{
if ($caneditperms)
{
print '';
print 'id.'&action=addrights&entity='.$entity.'&module='.$obj->module.'">'.$langs->trans("All")." ";
- print '/';
+ print ' / ';
print 'id.'&action=delrights&entity='.$entity.'&module='.$obj->module.'">'.$langs->trans("None")." ";
print ' ';
}
+ print ' ';
}
- else
- {
- if ($caneditperms)
- {
- print ' ';
- }
- }
- print ' ';
+ print ' ';
print ' '."\n";
}
diff --git a/phpstan.neon b/phpstan.neon
new file mode 100644
index 00000000000..1c35bd2faf3
--- /dev/null
+++ b/phpstan.neon
@@ -0,0 +1,83 @@
+parameters:
+ bootstrap: null
+ excludes_analyse:
+ - %rootDir%/htdocs/includes/*
+ autoload_directories: []
+ autoload_files: []
+ featureToggles:
+ subtractableTypes: false
+ validateParameters: false
+ fileExtensions:
+ - php
+ checkAlwaysTrueCheckTypeFunctionCall: false
+ checkAlwaysTrueInstanceof: false
+ checkAlwaysTrueStrictComparison: false
+ checkClassCaseSensitivity: false
+ checkFunctionArgumentTypes: false
+ checkFunctionNameCase: false
+ checkArgumentsPassedByReference: false
+ checkMaybeUndefinedVariables: false
+ checkNullables: false
+ checkThisOnly: true
+ checkUnionTypes: false
+ checkExplicitMixedMissingReturn: false
+ checkPhpDocMissingReturn: false
+ reportMaybes: false
+ reportMaybesInMethodSignatures: false
+ reportStaticMethodSignatures: false
+ polluteScopeWithLoopInitialAssignments: true
+ polluteScopeWithAlwaysIterableForeach: true
+ polluteCatchScopeWithTryAssignments: false
+ reportMagicMethods: false
+ reportMagicProperties: false
+ ignoreErrors: []
+ internalErrorsCountLimit: 50
+ cache:
+ nodesByFileCountMax: 512
+ nodesByStringCountMax: 512
+ reportUnmatchedIgnoredErrors: true
+ scopeClass: PHPStan\Analyser\Scope
+ universalObjectCratesClasses:
+ - stdClass
+ - SimpleXMLElement
+ earlyTerminatingMethodCalls: []
+ memoryLimitFile: %tmpDir%/.memory_limit
+ benchmarkFile: null
+ dynamicConstantNames:
+ - ICONV_IMPL
+ - PHP_VERSION
+ - PHP_MAJOR_VERSION
+ - PHP_MINOR_VERSION
+ - PHP_RELEASE_VERSION
+ - PHP_VERSION_ID
+ - PHP_EXTRA_VERSION
+ - PHP_ZTS
+ - PHP_DEBUG
+ - PHP_MAXPATHLEN
+ - PHP_OS
+ - PHP_OS_FAMILY
+ - PHP_SAPI
+ - PHP_EOL
+ - PHP_INT_MAX
+ - PHP_INT_MIN
+ - PHP_INT_SIZE
+ - PHP_FLOAT_DIG
+ - PHP_FLOAT_EPSILON
+ - PHP_FLOAT_MIN
+ - PHP_FLOAT_MAX
+ - DEFAULT_INCLUDE_PATH
+ - PEAR_INSTALL_DIR
+ - PEAR_EXTENSION_DIR
+ - PHP_EXTENSION_DIR
+ - PHP_PREFIX
+ - PHP_BINDIR
+ - PHP_BINARY
+ - PHP_MANDIR
+ - PHP_LIBDIR
+ - PHP_DATADIR
+ - PHP_SYSCONFDIR
+ - PHP_LOCALSTATEDIR
+ - PHP_CONFIG_FILE_PATH
+ - PHP_CONFIG_FILE_SCAN_DIR
+ - PHP_SHLIB_SUFFIX
+ - PHP_FD_SETSIZE
diff --git a/scripts/bank/export-bank-receipts.php b/scripts/bank/export-bank-receipts.php
index f1654b92d2a..1fb0058610a 100755
--- a/scripts/bank/export-bank-receipts.php
+++ b/scripts/bank/export-bank-receipts.php
@@ -1,7 +1,7 @@
#!/usr/bin/env php
+ * Copyright (C) 2013 Laurent Destailleur
*
* 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
@@ -10,7 +10,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -18,200 +18,160 @@
*/
/**
- * \file scripts/bank/export-bank-receipts.php
- * \ingroup bank
- * \brief Script file to export bank receipts into Excel files
+ * \file scripts/bank/export-bank-receipts.php
+ * \ingroup bank
+ * \brief Script file to export bank receipts into Excel files
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test if batch mode
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";
- exit(-1);
+ 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);
}
-require_once $path."../../htdocs/master.inc.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.'/societe/class/societe.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/paiement/class/paiement.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.'/compta/bank/class/account.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.'/compta/tva/class/tva.class.php';
-require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/paymentsocialcontribution.class.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/bank.lib.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 . '/compta/sociales/class/chargesociales.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 . '/fourn/class/paiementfourn.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 . '/fourn/class/fournisseur.facture.class.php';
+require_once DOL_DOCUMENT_ROOT . '/compta/tva/class/tva.class.php';
+require_once DOL_DOCUMENT_ROOT . '/compta/sociales/class/paymentsocialcontribution.class.php';
// Global variables
-$version=DOL_VERSION;
-$error=0;
-
-
+$version = DOL_VERSION;
+$error = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
if (! isset($argv[3]) || ! $argv[3]) {
- print "Usage: ".$script_file." bank_ref [bank_receipt_number|all] (csv|tsv|excel|excel2007) [lang=xx_XX]\n";
- exit(-1);
+ print "Usage: " . $script_file . " bank_ref [bank_receipt_number|all] (csv|tsv|excel|excel2007) [lang=xx_XX]\n";
+ exit(- 1);
}
-$bankref=$argv[1];
-$num=$argv[2];
-$model=$argv[3];
-$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);
+$bankref = $argv[1];
+$num = $argv[2];
+$model = $argv[3];
+$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);
// Parse parameters
-foreach ($argv as $key => $value)
-{
- $found=false;
+foreach ($argv as $key => $value) {
+ $found = false;
// Define options
- if (preg_match('/^lang=/i', $value))
- {
- $found=true;
- $valarray=explode('=', $value);
- $newlangid=$valarray[1];
- print 'Use language '.$newlangid.".\n";
+ if (preg_match('/^lang=/i', $value)) {
+ $found = true;
+ $valarray = explode('=', $value);
+ $newlangid = $valarray[1];
+ print 'Use language ' . $newlangid . ".\n";
}
}
$outputlangs = $langs;
-if (! empty($newlangid))
-{
- if ($outputlangs->defaultlang != $newlangid)
- {
+if (! empty($newlangid)) {
+ if ($outputlangs->defaultlang != $newlangid) {
$outputlangs = new Translate("", $conf);
$outputlangs->setDefaultLang($newlangid);
}
}
// 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);
-$result=$acct->fetch('', $bankref);
-if ($result <= 0)
-{
- print "Failed to find bank account with ref ".$bankref.".\n";
- exit(-1);
+$acct = new Account($db);
+$result = $acct->fetch('', $bankref);
+if ($result <= 0) {
+ print "Failed to find bank account with ref " . $bankref . ".\n";
+ 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
$dir = DOL_DOCUMENT_ROOT . "/core/modules/export/";
-$file = "export_".$model.".modules.php";
-$classname = "Export".$model;
-if (! dol_is_file($dir.$file))
-{
- print "No driver to export with format ".$model."\n";
- exit(-1);
+$file = "export_" . $model . ".modules.php";
+$classname = "Export" . $model;
+if (! dol_is_file($dir . $file)) {
+ print "No driver to export with format " . $model . "\n";
+ exit(- 1);
}
-require_once $dir.$file;
+require_once $dir . $file;
$objmodel = new $classname($db);
-
// Define target path
$dirname = $conf->bank->dir_temp;
-$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'
-);
+$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');
// Build request to find records for a bank account/receipt
-$listofnum="";
-if (! empty($num) && $num != "all")
-{
- $listofnum.="'";
- $arraynum=explode(',', $num);
- foreach($arraynum as $val)
- {
- if ($listofnum != "'") $listofnum.="','";
- $listofnum.=$val;
+$listofnum = "";
+if (! empty($num) && $num != "all") {
+ $listofnum .= "'";
+ $arraynum = explode(',', $num);
+ foreach ($arraynum as $val) {
+ if ($listofnum != "'")
+ $listofnum .= "','";
+ $listofnum .= $val;
}
- $listofnum.="'";
+ $listofnum .= "'";
}
$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.= " ba.rowid as bankid, ba.ref as bankref, ba.label as banklabel";
-$sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba";
-$sql.= ", ".MAIN_DB_PREFIX."bank as b";
-$sql.= " WHERE b.fk_account = ".$acct->id;
-if ($listofnum) $sql.= " AND b.num_releve IN (".$listofnum.")";
-if (!isset($num)) $sql.= " OR b.num_releve is null";
-$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;
+$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 .= " FROM " . MAIN_DB_PREFIX . "bank_account as ba";
+$sql .= ", " . MAIN_DB_PREFIX . "bank as b";
+$sql .= " WHERE b.fk_account = " . $acct->id;
+if ($listofnum)
+ $sql .= " AND b.num_releve IN (" . $listofnum . ")";
+if (! isset($num))
+ $sql .= " OR b.num_releve is null";
+$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);
-if ($resql)
-{
- $balancebefore=array();
+$resql = $db->query($sql);
+if ($resql) {
+ $balancebefore = array();
$numrows = $db->num_rows($resql);
- if ($numrows > 0)
- {
+ if ($numrows > 0) {
// Open file
- print 'Open file '.$filename.' into directory '.$dirname."\n";
+ print 'Open file ' . $filename . ' into directory ' . $dirname . "\n";
dol_mkdir($dirname);
- $result=$objmodel->open_file($dirname."/".$filename, $outputlangs);
+ $result = $objmodel->open_file($dirname . "/" . $filename, $outputlangs);
- if ($result < 0)
- {
- print 'Failed to create file '.$filename.' into dir '.$dirname.'.'."\n";
- return -1;
+ if ($result < 0) {
+ print 'Failed to create file ' . $filename . ' into dir ' . $dirname . '.' . "\n";
+ return - 1;
}
// Genere en-tete
@@ -221,35 +181,30 @@ if ($resql)
$objmodel->write_title($array_fields, $array_selected, $outputlangs, $array_export_TypeFields);
}
- $i=0;
- while ($i < $numrows)
- {
- $thirdparty='';
- $accountelem='';
- $comment='';
+ $i = 0;
+ while ($i < $numrows) {
+ $thirdparty = '';
+ $accountelem = '';
+ $comment = '';
$objp = $db->fetch_object($resql);
// Calculate start balance
- if (! isset($balancebefore[$objp->num_releve]))
- {
- print 'Calculate start balance for receipt '.$objp->num_releve."\n";
+ if (! isset($balancebefore[$objp->num_releve])) {
+ print 'Calculate start balance for receipt ' . $objp->num_releve . "\n";
$sql2 = "SELECT sum(b.amount) as amount";
- $sql2.= " FROM ".MAIN_DB_PREFIX."bank as b";
- $sql2.= " WHERE b.num_releve < '".$db->escape($objp->num_releve)."'";
- $sql2.= " AND b.fk_account = ".$objp->bankid;
- $resql2=$db->query($sql2);
- if ($resql2)
- {
- $obj2=$db->fetch_object($resql2);
- $balancebefore[$objp->num_releve] = ($obj2->amount?$obj2->amount:0);
+ $sql2 .= " FROM " . MAIN_DB_PREFIX . "bank as b";
+ $sql2 .= " WHERE b.num_releve < '" . $db->escape($objp->num_releve) . "'";
+ $sql2 .= " AND b.fk_account = " . $objp->bankid;
+ $resql2 = $db->query($sql2);
+ if ($resql2) {
+ $obj2 = $db->fetch_object($resql2);
+ $balancebefore[$objp->num_releve] = ($obj2->amount ? $obj2->amount : 0);
$db->free($resql2);
- }
- else
- {
+ } else {
dol_print_error($db);
- exit(-1);
+ exit(- 1);
}
$total = $balancebefore[$objp->num_releve];
@@ -258,168 +213,153 @@ if ($resql)
$totalbefore = $total;
$total = $total + $objp->amount;
-
-
// Date operation
- $dateop=$db->jdate($objp->do);
+ $dateop = $db->jdate($objp->do);
// Date de valeur
- $datevalue=$db->jdate($objp->dv);
+ $datevalue = $db->jdate($objp->dv);
// Num cheque
- $numchq=($objp->num_chq?$objp->num_chq:'');
+ $numchq = ($objp->num_chq ? $objp->num_chq : '');
// Libelle
- $reg=array();
- 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]);
- else $description=$objp->label;
+ $reg = array();
+ 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]);
+ else
+ $description = $objp->label;
/*
* Ajout les liens (societe, company...)
*/
$links = $acct->get_url($objp->rowid);
- foreach($links as $key=>$val)
- {
- if ($links[$key]['type']=='payment')
- {
+ foreach ($links as $key => $val) {
+ if ($links[$key]['type'] == 'payment') {
$paymentstatic->fetch($links[$key]['url_id']);
- $tmparray=$paymentstatic->getBillsArray('');
- if (is_array($tmparray))
- {
- foreach($tmparray as $key => $val)
- {
+ $tmparray = $paymentstatic->getBillsArray('');
+ if (is_array($tmparray)) {
+ foreach ($tmparray as $key => $val) {
$invoicestatic->fetch($val);
- if ($accountelem) $accountelem.= ', ';
- $accountelem.=$invoicestatic->ref;
+ if ($accountelem)
+ $accountelem .= ', ';
+ $accountelem .= $invoicestatic->ref;
}
}
- }
- elseif ($links[$key]['type']=='payment_supplier')
- {
+ } elseif ($links[$key]['type'] == 'payment_supplier') {
$paymentsupplierstatic->fetch($links[$key]['url_id']);
- $tmparray=$paymentsupplierstatic->getBillsArray('');
- if (is_array($tmparray))
- {
- foreach($tmparray as $key => $val)
- {
+ $tmparray = $paymentsupplierstatic->getBillsArray('');
+ if (is_array($tmparray)) {
+ foreach ($tmparray as $key => $val) {
$invoicesupplierstatic->fetch($val);
- if ($accountelem) $accountelem.= ', ';
- $accountelem.=$invoicesupplierstatic->ref;
+ if ($accountelem)
+ $accountelem .= ', ';
+ $accountelem .= $invoicesupplierstatic->ref;
}
}
- }
- elseif ($links[$key]['type']=='payment_sc')
- {
+ } elseif ($links[$key]['type'] == 'payment_sc') {
$paymentsocialcontributionstatic->fetch($links[$key]['url_id']);
- if ($accountelem) $accountelem.= ', ';
- $accountelem.=$langs->transnoentitiesnoconv("SocialContribution").' '.$paymentsocialcontributionstatic->ref;
- }
- elseif ($links[$key]['type']=='payment_vat')
- {
+ if ($accountelem)
+ $accountelem .= ', ';
+ $accountelem .= $langs->transnoentitiesnoconv("SocialContribution") . ' ' . $paymentsocialcontributionstatic->ref;
+ } elseif ($links[$key]['type'] == 'payment_vat') {
$paymentvatstatic->fetch($links[$key]['url_id']);
- if ($accountelem) $accountelem.= ', ';
- $accountelem.=$langs->transnoentitiesnoconv("VATPayments").' '.$paymentvatstatic->ref;
- }
- elseif ($links[$key]['type']=='banktransfert')
- {
- $comment=$outputlangs->transnoentitiesnoconv("Transfer");
- if ($objp->amount > 0)
- {
- if ($comment) $comment.= ' ';
+ if ($accountelem)
+ $accountelem .= ', ';
+ $accountelem .= $langs->transnoentitiesnoconv("VATPayments") . ' ' . $paymentvatstatic->ref;
+ } elseif ($links[$key]['type'] == 'banktransfert') {
+ $comment = $outputlangs->transnoentitiesnoconv("Transfer");
+ if ($objp->amount > 0) {
+ if ($comment)
+ $comment .= ' ';
$banklinestatic->fetch($links[$key]['url_id']);
- $bankstatic->id=$banklinestatic->fk_account;
- $bankstatic->label=$banklinestatic->bank_account_label;
- $comment.= ' ('.$langs->transnoentitiesnoconv("from").' ';
- $comment.= $bankstatic->getNomUrl(1, 'transactions');
- $comment.= ' '.$langs->transnoentitiesnoconv("toward").' ';
- $bankstatic->id=$objp->bankid;
- $bankstatic->label=$objp->bankref;
- $comment.= $bankstatic->getNomUrl(1, '');
- $comment.= ')';
- }
- else
- {
- if ($comment) $comment.= ' ';
- $bankstatic->id=$objp->bankid;
- $bankstatic->label=$objp->bankref;
- $comment.= ' ('.$langs->transnoentitiesnoconv("from").' ';
- $comment.= $bankstatic->getNomUrl(1, '');
- $comment.= ' '.$langs->transnoentitiesnoconv("toward").' ';
+ $bankstatic->id = $banklinestatic->fk_account;
+ $bankstatic->label = $banklinestatic->bank_account_label;
+ $comment .= ' (' . $langs->transnoentitiesnoconv("from") . ' ';
+ $comment .= $bankstatic->getNomUrl(1, 'transactions');
+ $comment .= ' ' . $langs->transnoentitiesnoconv("toward") . ' ';
+ $bankstatic->id = $objp->bankid;
+ $bankstatic->label = $objp->bankref;
+ $comment .= $bankstatic->getNomUrl(1, '');
+ $comment .= ')';
+ } else {
+ if ($comment)
+ $comment .= ' ';
+ $bankstatic->id = $objp->bankid;
+ $bankstatic->label = $objp->bankref;
+ $comment .= ' (' . $langs->transnoentitiesnoconv("from") . ' ';
+ $comment .= $bankstatic->getNomUrl(1, '');
+ $comment .= ' ' . $langs->transnoentitiesnoconv("toward") . ' ';
$banklinestatic->fetch($links[$key]['url_id']);
- $bankstatic->id=$banklinestatic->fk_account;
- $bankstatic->label=$banklinestatic->bank_account_label;
- $comment.= $bankstatic->getNomUrl(1, 'transactions');
- $comment.= ')';
+ $bankstatic->id = $banklinestatic->fk_account;
+ $bankstatic->label = $banklinestatic->bank_account_label;
+ $comment .= $bankstatic->getNomUrl(1, 'transactions');
+ $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')
- {
- 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']=='sc')
- {
- if ($accountelem) $accountelem.= ', ';
- //$accountelem.= '';
- //$accountelem.= img_object($langs->transnoentitiesnoconv('ShowBill'),'bill').' ';
- $accountelem.= $langs->transnoentitiesnoconv("SocialContribution");
- //$accountelem.= ' ';
- $newline=0;
- }
- else
- {
- if ($accountelem) $accountelem.= ', ';
- //$accountelem.= '';
- $accountelem.= $links[$key]['label'];
- //$accountelem.= ' ';
- $newline=0;
- }*/
+ /*
+ * elseif ($links[$key]['type']=='sc')
+ * {
+ * if ($accountelem) $accountelem.= ', ';
+ * //$accountelem.= '';
+ * //$accountelem.= img_object($langs->transnoentitiesnoconv('ShowBill'),'bill').' ';
+ * $accountelem.= $langs->transnoentitiesnoconv("SocialContribution");
+ * //$accountelem.= ' ';
+ * $newline=0;
+ * }
+ * else
+ * {
+ * if ($accountelem) $accountelem.= ', ';
+ * //$accountelem.= '';
+ * $accountelem.= $links[$key]['label'];
+ * //$accountelem.= ' ';
+ * $newline=0;
+ * }
+ */
}
- $debit=$credit='';
- if ($objp->amount < 0)
- {
+ $debit = $credit = '';
+ if ($objp->amount < 0) {
$totald = $totald + abs($objp->amount);
- $debit=price2num($objp->amount * -1);
- }
- else
- {
+ $debit = price2num($objp->amount * - 1);
+ } else {
$totalc = $totalc + abs($objp->amount);
- $credit=price2num($objp->amount);
+ $credit = price2num($objp->amount);
}
- $i++;
+ $i ++;
- $rec=new stdClass();
- $rec->bankreceipt=$objp->num_releve;
- $rec->bankaccount=$objp->banklabel;
- $rec->dateop=dol_print_date($dateop, 'dayrfc');
- $rec->dateval=dol_print_date($datevalue, 'dayrfc');
- $rec->type=$objp->fk_type.' '.($objp->num_chq?$objp->num_chq:'');
- $rec->description=$description;
- $rec->thirdparty=$thirdparty;
- $rec->accountelem=$accountelem;
- $rec->debit=$debit;
- $rec->credit=$credit;
- $rec->comment=$comment;
- $rec->soldbefore=price2num($totalbefore);
- $rec->soldafter=price2num($total);
+ $rec = new stdClass();
+ $rec->bankreceipt = $objp->num_releve;
+ $rec->bankaccount = $objp->banklabel;
+ $rec->dateop = dol_print_date($dateop, 'dayrfc');
+ $rec->dateval = dol_print_date($datevalue, 'dayrfc');
+ $rec->type = $objp->fk_type . ' ' . ($objp->num_chq ? $objp->num_chq : '');
+ $rec->description = $description;
+ $rec->thirdparty = $thirdparty;
+ $rec->accountelem = $accountelem;
+ $rec->debit = $debit;
+ $rec->credit = $credit;
+ $rec->comment = $comment;
+ $rec->soldbefore = price2num($totalbefore);
+ $rec->soldafter = price2num($total);
// end of special operation processing
$objmodel->write_record($array_selected, $rec, $outputlangs, $array_export_TypeFields);
}
- if ($numrows > 0)
- {
- print "Found ".$numrows." records for receipt ".$num."\n";
+ if ($numrows > 0) {
+ print "Found " . $numrows . " records for receipt " . $num . "\n";
// Genere en-tete
$objmodel->write_footer($outputlangs);
@@ -427,21 +367,17 @@ if ($resql)
// 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;
- }
- else
- {
- print "No records found for receipt ".$num."\n";
+ $ret = 0;
+ } else {
+ print "No records found for receipt " . $num . "\n";
- $ret=0;
+ $ret = 0;
}
-}
-else
-{
+} else {
dol_print_error($db);
- $ret=-1;
+ $ret = - 1;
}
$db->close();
diff --git a/scripts/company/export-contacts-xls-example.php b/scripts/company/export-contacts-xls-example.php
index 1850cbece74..856496c0842 100755
--- a/scripts/company/export-contacts-xls-example.php
+++ b/scripts/company/export-contacts-xls-example.php
@@ -1,8 +1,8 @@
#!/usr/bin/env php
- * Copyright (C) 2009-2013 Laurent Destailleur
+ * Copyright (C) 2004 Rodolphe Quiedeville
+ * Copyright (C) 2009-2013 Laurent Destailleur
*
* 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
@@ -11,7 +11,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -19,52 +19,49 @@
*/
/**
- * \file scripts/company/export-contacts-xls-example.php
- * \ingroup company
- * \brief Script file to export contacts into an Excel file
+ * \file scripts/company/export-contacts-xls-example.php
+ * \ingroup company
+ * \brief Script file to export contacts into an Excel file
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test if batch mode
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";
- exit(-1);
+ 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);
}
if (! isset($argv[1]) || ! $argv[1]) {
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 PHP_WRITEEXCEL_PATH."/class.writeexcel_workbook.inc.php";
-//require_once PHP_WRITEEXCEL_PATH."/class.writeexcel_worksheet.inc.php";
-
-require_once PHPEXCEL_PATH."/PHPExcel.php";
-//require_once PHPEXCEL_PATH."/PHPExcel/Writer/Excel2007.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
-$version=DOL_VERSION;
-$error=0;
-
+$version = DOL_VERSION;
+$error = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+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->getProperties()->setCreator("Dolibarr script");
$objPHPExcel->getProperties()->setLastModifiedBy("Dolibarr script");
@@ -72,23 +69,21 @@ $objPHPExcel->getProperties()->setTitle("Test Document");
$objPHPExcel->getProperties()->setSubject("Test Document");
$objPHPExcel->getProperties()->setDescription("Test document, generated using PHP classes.");
-
-//$page = &$objPHPExcel->addworksheet('Export Dolibarr');
+// $page = &$objPHPExcel->addworksheet('Export Dolibarr');
$objPHPExcel->setActiveSheetIndex(0);
$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.= " FROM ".MAIN_DB_PREFIX."socpeople as c";
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s on s.rowid = c.fk_soc";
+$sql .= " FROM " . MAIN_DB_PREFIX . "socpeople as c";
+$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as s on s.rowid = c.fk_soc";
-$resql=$db->query($sql);
-if ($resql)
-{
+$resql = $db->query($sql);
+if ($resql) {
$num = $db->num_rows($resql);
- print "Lines ".$num."\n";
+ print "Lines " . $num . "\n";
$i = 0;
$j = 1;
@@ -98,27 +93,25 @@ if ($resql)
$objPHPExcel->getActiveSheet()->SetCellValue('C1', $langs->trans("Email"));
$objPHPExcel->getActiveSheet()->SetCellValue('D1', $langs->trans("ThirdPart"));
- while ($i < $num)
- {
+ while ($i < $num) {
$obj = $db->fetch_object($resql);
- $objPHPExcel->getActiveSheet()->SetCellValue('A'.($i+2), $obj->firstname);
- $objPHPExcel->getActiveSheet()->SetCellValue('B'.($i+2), $obj->lastname);
- $objPHPExcel->getActiveSheet()->SetCellValue('C'.($i+2), $obj->email);
- $objPHPExcel->getActiveSheet()->SetCellValue('D'.($i+2), $obj->name);
+ $objPHPExcel->getActiveSheet()->SetCellValue('A' . ($i + 2), $obj->firstname);
+ $objPHPExcel->getActiveSheet()->SetCellValue('B' . ($i + 2), $obj->lastname);
+ $objPHPExcel->getActiveSheet()->SetCellValue('C' . ($i + 2), $obj->email);
+ $objPHPExcel->getActiveSheet()->SetCellValue('D' . ($i + 2), $obj->name);
- $j++;
- $i++;
+ $j ++;
+ $i ++;
}
}
-
-//$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
+// $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
$objWriter->save($fname);
-//$objPHPExcel->close();
+// $objPHPExcel->close();
-print 'File '.$fname.' was generated.'."\n";
+print 'File ' . $fname . ' was generated.' . "\n";
exit(0);
diff --git a/scripts/company/sync_contacts_dolibarr2ldap.php b/scripts/company/sync_contacts_dolibarr2ldap.php
index d70ad7d20b3..9ee59e6cada 100755
--- a/scripts/company/sync_contacts_dolibarr2ldap.php
+++ b/scripts/company/sync_contacts_dolibarr2ldap.php
@@ -1,8 +1,8 @@
#!/usr/bin/env php
- * Copyright (C) 2006-2009 Laurent Destailleur
+ * Copyright (C) 2005 Rodolphe Quiedeville
+ * Copyright (C) 2006-2009 Laurent Destailleur
*
* 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
@@ -11,7 +11,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -19,74 +19,70 @@
*/
/**
- * \file scripts/company/sync_contacts_dolibarr2ldap.php
- * \ingroup ldap company
- * \brief Script to update all contacts from Dolibarr into a LDAP database
+ * \file scripts/company/sync_contacts_dolibarr2ldap.php
+ * \ingroup ldap company
+ * \brief Script to update all contacts from Dolibarr into a LDAP database
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test if batch mode
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";
- exit(-1);
+ 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);
}
-
-require_once $path."../../htdocs/master.inc.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."/core/class/ldap.class.php";
+require_once $path . "../../htdocs/master.inc.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 . "/core/class/ldap.class.php";
// Global variables
-$version=DOL_VERSION;
-$error=0;
-$confirmed=0;
-
+$version = DOL_VERSION;
+$error = 0;
+$confirmed = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
if (! isset($argv[1]) || ! $argv[1]) {
- print "Usage: $script_file now [-y]\n";
- exit(-1);
+ print "Usage: $script_file now [-y]\n";
+ exit(- 1);
}
-foreach($argv as $key => $val)
-{
- if (preg_match('/-y$/', $val, $reg)) $confirmed=1;
+foreach ($argv as $key => $val) {
+ if (preg_match('/-y$/', $val, $reg))
+ $confirmed = 1;
}
-$now=$argv[1];
+$now = $argv[1];
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 "----- Synchronize all records from Dolibarr database:\n";
-print "type=".$conf->db->type."\n";
-print "host=".$conf->db->host."\n";
-print "port=".$conf->db->port."\n";
-print "login=".$conf->db->user."\n";
-//print "pass=".preg_replace('/./i','*',$conf->db->password)."\n"; // Not defined for security reasons
-print "database=".$conf->db->name."\n";
+print "type=" . $conf->db->type . "\n";
+print "host=" . $conf->db->host . "\n";
+print "port=" . $conf->db->port . "\n";
+print "login=" . $conf->db->user . "\n";
+// print "pass=".preg_replace('/./i','*',$conf->db->password)."\n"; // Not defined for security reasons
+print "database=" . $conf->db->name . "\n";
print "\n";
print "----- To LDAP database:\n";
-print "host=".$conf->global->LDAP_SERVER_HOST."\n";
-print "port=".$conf->global->LDAP_SERVER_PORT."\n";
-print "login=".$conf->global->LDAP_ADMIN_DN."\n";
-print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n";
-print "DN target=".$conf->global->LDAP_CONTACT_DN."\n";
+print "host=" . $conf->global->LDAP_SERVER_HOST . "\n";
+print "port=" . $conf->global->LDAP_SERVER_PORT . "\n";
+print "login=" . $conf->global->LDAP_ADMIN_DN . "\n";
+print "pass=" . preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS) . "\n";
+print "DN target=" . $conf->global->LDAP_CONTACT_DN . "\n";
print "\n";
-if (! $confirmed)
-{
+if (! $confirmed) {
print "Press a key to confirm...\n";
$input = trim(fgets(STDIN));
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)
-{
- print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
- exit(-1);
-}
-*/
+ * if (! $conf->global->LDAP_CONTACT_ACTIVE)
+ * {
+ * print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
+ * exit(-1);
+ * }
+ */
$sql = "SELECT rowid";
-$sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
+$sql .= " FROM " . MAIN_DB_PREFIX . "socpeople";
$resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
$num = $db->num_rows($resql);
$i = 0;
- $ldap=new Ldap();
+ $ldap = new Ldap();
$ldap->connect_bind();
- while ($i < $num)
- {
- $ldap->error="";
+ while ($i < $num) {
+ $ldap->error = "";
$obj = $db->fetch_object($resql);
@@ -125,37 +119,32 @@ if ($resql)
$contact->id = $obj->rowid;
$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();
- $olddn=$oldobject->_load_ldap_dn($oldinfo);
+ $oldinfo = $oldobject->_load_ldap_info();
+ $olddn = $oldobject->_load_ldap_dn($oldinfo);
- $info=$contact->_load_ldap_info();
- $dn=$contact->_load_ldap_dn($info);
+ $info = $contact->_load_ldap_info();
+ $dn = $contact->_load_ldap_dn($info);
- $result=$ldap->add($dn, $info, $user); // Wil fail if already exists
- $result=$ldap->update($dn, $info, $user, $olddn);
- if ($result > 0)
- {
- print " - ".$langs->trans("OK");
- }
- else
- {
- $error++;
- print " - ".$langs->trans("KO").' - '.$ldap->error;
+ $result = $ldap->add($dn, $info, $user); // Wil fail if already exists
+ $result = $ldap->update($dn, $info, $user, $olddn);
+ if ($result > 0) {
+ print " - " . $langs->trans("OK");
+ } else {
+ $error ++;
+ print " - " . $langs->trans("KO") . ' - ' . $ldap->error;
}
print "\n";
- $i++;
+ $i ++;
}
$ldap->unbind();
$ldap->close();
-}
-else
-{
+} else {
dol_print_error($db);
}
diff --git a/scripts/contracts/email_expire_services_to_customers.php b/scripts/contracts/email_expire_services_to_customers.php
index eeb5967556e..041f9dd0b1c 100755
--- a/scripts/contracts/email_expire_services_to_customers.php
+++ b/scripts/contracts/email_expire_services_to_customers.php
@@ -1,9 +1,9 @@
#!/usr/bin/env php
- * Copyright (C) 2005-2013 Laurent Destailleur
- * Copyright (C) 2013 Juanjo Menent
+ * Copyright (C) 2005 Rodolphe Quiedeville
+ * Copyright (C) 2005-2013 Laurent Destailleur
+ * Copyright (C) 2013 Juanjo Menent
*
* 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
@@ -12,7 +12,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -20,297 +20,283 @@
*/
/**
- * \file scripts/contracts/email_expire_services_to_customers.php
- * \ingroup facture
- * \brief Script to send a mail to customers with services to expire
+ * \file scripts/contracts/email_expire_services_to_customers.php
+ * \ingroup facture
+ * \brief Script to send a mail to customers with services to expire
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test si mode batch
$sapi_type = php_sapi_name();
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";
- exit(-1);
+ 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);
}
-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 "\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 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";
- exit(-1);
+ exit(- 1);
}
-$mode=$argv[1];
-$targettype=$argv[2];
+$mode = $argv[1];
+$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";
-require_once DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php";
-
-$langs->loadLangs(array('main', 'contracts'));
+$langs->loadLangs(array('main','contracts'));
// Global variables
-$version=DOL_VERSION;
-$error=0;
-
+$version = DOL_VERSION;
+$error = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
-$now=dol_now('tzserver');
-$duration_value=isset($argv[3])?$argv[3]:'none';
-$duration_value2=isset($argv[4])?$argv[4]:'none';
+$now = dol_now('tzserver');
+$duration_value = isset($argv[3]) ? $argv[3] : 'none';
+$duration_value2 = isset($argv[4]) ? $argv[4] : 'none';
$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.= " 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";
-$sql .= " FROM ".MAIN_DB_PREFIX."societe AS s";
-if ($targettype == 'contacts') $sql.= ", ".MAIN_DB_PREFIX."socpeople as sp";
-$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 = "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";
+if ($targettype == 'contacts')
+ $sql .= ", sp.rowid as cid, sp.firstname as cfirstname, sp.lastname as clastname, sp.email as cemail";
+$sql .= " FROM " . MAIN_DB_PREFIX . "societe AS s";
+if ($targettype == 'contacts')
+ $sql .= ", " . MAIN_DB_PREFIX . "socpeople as sp";
+$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";
-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_value)) $sql.= " AND cd.date_fin_validite < '".$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, cd.date_fin_validite ASC"; // Order by email to allow one message per email
+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_value))
+ $sql .= " AND cd.date_fin_validite < '" . $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, cd.date_fin_validite ASC"; // Order by email to allow one message per email
-//print $sql;
-$resql=$db->query($sql);
-if ($resql)
-{
- $num = $db->num_rows($resql);
- $i = 0;
- $oldemail = 'none'; $oldsid = 0; $oldcid = 0; $oldlang='';
- $total = 0; $foundtoprocess = 0;
- $trackthirdpartiessent = array();
+// print $sql;
+$resql = $db->query($sql);
+if ($resql) {
+ $num = $db->num_rows($resql);
+ $i = 0;
+ $oldemail = 'none';
+ $oldsid = 0;
+ $oldcid = 0;
+ $oldlang = '';
+ $total = 0;
+ $foundtoprocess = 0;
+ $trackthirdpartiessent = array();
- print "We found ".$num." couples (services to expire-".$targettype.") qualified\n";
- dol_syslog("We found ".$num." couples (services to expire-".$targettype.") qualified");
- $message='';
+ print "We found " . $num . " couples (services to expire-" . $targettype . ") qualified\n";
+ dol_syslog("We found " . $num . " couples (services to expire-" . $targettype . ") qualified");
+ $message = '';
- if ($num)
- {
- while ($i < $num)
- {
- $obj = $db->fetch_object($resql);
+ if ($num) {
+ while ($i < $num) {
+ $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
- $startbreak=false;
- if ($newemail <> $oldemail || $oldemail == 'none') $startbreak=true;
- if ($obj->sid && $obj->sid <> $oldsid) $startbreak=true;
- if ($obj->cid && $obj->cid <> $oldcid) $startbreak=true;
+ // Check if this record is a break after previous one
+ $startbreak = false;
+ if ($newemail != $oldemail || $oldemail == 'none')
+ $startbreak = true;
+ if ($obj->sid && $obj->sid != $oldsid)
+ $startbreak = true;
+ if ($obj->cid && $obj->cid != $oldcid)
+ $startbreak = true;
- if ($startbreak)
- {
- // Break onto sales representative (new email or cid)
- 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;
- }
- else
- {
- 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";
- }
- }
- $oldemail = $newemail;
- $oldsid = $obj->sid;
- $oldcid = $obj->cid;
- $oldlang = $obj->lang;
- $oldtarget=(empty($obj->cfirstname) && empty($obj->clastname))?$obj->name:($obj->clastname." ".$obj->cfirstname);
- $message = '';
- $total = 0;
- $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";
- }
+ if ($startbreak) {
+ // Break onto sales representative (new email or cid)
+ 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;
+ } else {
+ 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";
+ }
+ }
+ $oldemail = $newemail;
+ $oldsid = $obj->sid;
+ $oldcid = $obj->cid;
+ $oldlang = $obj->lang;
+ $oldtarget = (empty($obj->cfirstname) && empty($obj->clastname)) ? $obj->name : ($obj->clastname . " " . $obj->cfirstname);
+ $message = '';
+ $total = 0;
+ $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
- $outputlangs=new Translate('', $conf);
- $outputlangs->setDefaultLang(empty($obj->default_lang)?$langs->defaultlang:$obj->default_lang); // By default language of customer
+ // Define line content
+ $outputlangs = new Translate('', $conf);
+ $outputlangs->setDefaultLang(empty($obj->default_lang) ? $langs->defaultlang : $obj->default_lang); // By default language of customer
- // Load translation files required by the page
- $outputlangs->loadLangs(array("main", "contracts", "bills", "products"));
+ // Load translation files required by the page
+ $outputlangs->loadLangs(array("main","contracts","bills","products"));
- 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";
- dol_syslog("email_expire_services_to_customers.php: ".$newemail." ".$message);
- $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.": ";
- if (dol_strlen($newemail)) print "qualified.";
- else print "disqualified (no email).";
+ 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";
+ dol_syslog("email_expire_services_to_customers.php: " . $newemail . " " . $message);
+ $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 . ": ";
+ if (dol_strlen($newemail))
+ print "qualified.";
+ else
+ 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
- if ($foundtoprocess)
- {
- 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
+ // Si il reste des envois en buffer
+ if ($foundtoprocess) {
+ if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid . '|' . $oldemail])) // Break onto email (new email)
{
- 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";
- }
+ envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget, $duration_value);
+ $trackthirdpartiessent[$oldsid . '|' . $oldemail] = 'contact id ' . $oldcid;
+ } else {
+ 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";
+ }
- 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 $oldemail Target email
- * @param string $message Message to send
- * @param string $total 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
+ * @param string $mode
+ * Mode (test | confirm)
+ * @param string $oldemail
+ * Target email
+ * @param string $message
+ * Message to send
+ * @param string $total
+ * 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)
{
- 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->setDefaultLang(empty($userlang)?(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT):$userlang);
- $newlangs->load("main");
- $newlangs->load("contracts");
+ $newlangs = new Translate('', $conf);
+ $newlangs->setDefaultLang(empty($userlang) ? (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT) : $userlang);
+ $newlangs->load("main");
+ $newlangs->load("contracts");
- if ($duration_value)
- {
- if ($duration_value > 0) $title=$newlangs->transnoentities("ListOfServicesToExpireWithDuration", $duration_value);
- else $title=$newlangs->transnoentities("ListOfServicesToExpireWithDurationNeg", $duration_value);
- }
- else
- $title= $newlangs->transnoentities("ListOfServicesToExpire");
+ if ($duration_value) {
+ if ($duration_value > 0)
+ $title = $newlangs->transnoentities("ListOfServicesToExpireWithDuration", $duration_value);
+ else
+ $title = $newlangs->transnoentities("ListOfServicesToExpireWithDurationNeg", $duration_value);
+ } else
+ $title = $newlangs->transnoentities("ListOfServicesToExpire");
- $subject = (empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT)?$title:$conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT);
- $sendto = $oldemail;
- $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
- $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
- $msgishtml = -1;
+ $subject = (empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT) ? $title : $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_SUBJECT);
+ $sendto = $oldemail;
+ $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
+ $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
+ $msgishtml = - 1;
- print "- Send email to '".$oldtarget."' (".$oldemail."), total: ".$total."\n";
- dol_syslog("email_expire_services_to_customers.php: send mail to ".$oldemail);
+ print "- Send email to '" . $oldtarget . "' (" . $oldemail . "), total: " . $total . "\n";
+ dol_syslog("email_expire_services_to_customers.php: send mail to " . $oldemail);
- $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_HEADER)) $usehtml+=1;
+ $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_HEADER))
+ $usehtml += 1;
- $allmessage='';
- if (! empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER))
- {
- $allmessage.=$conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER;
- }
- else
- {
- $allmessage.= "Dear customer".($usehtml?" \n":"\n").($usehtml?" \n":"\n");
- $allmessage.= "Please, find a summary of the services contracted by you that are about to expire.".($usehtml?" \n":"\n").($usehtml?" \n":"\n");
- }
- $allmessage.= $message.($usehtml?" \n":"\n");
- //$allmessage.= $langs->trans("Total")." = ".price($total,0,$userlang,0,0,-1,$conf->currency).($usehtml?" \n":"\n");
- if (! empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER))
- {
- $allmessage.=$conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER;
- if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) $usehtml+=1;
- }
+ $allmessage = '';
+ if (! empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER)) {
+ $allmessage .= $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_HEADER;
+ } else {
+ $allmessage .= "Dear customer" . ($usehtml ? " \n" : "\n") . ($usehtml ? " \n" : "\n");
+ $allmessage .= "Please, find a summary of the services contracted by you that are about to expire." . ($usehtml ? " \n" : "\n") . ($usehtml ? " \n" : "\n");
+ }
+ $allmessage .= $message . ($usehtml ? " \n" : "\n");
+ // $allmessage.= $langs->trans("Total")." = ".price($total,0,$userlang,0,0,-1,$conf->currency).($usehtml?" \n":"\n");
+ if (! empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_CUSTOMERS_FOOTER)) {
+ $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(
- $subject,
- $sendto,
- $from,
- $allmessage,
- array(),
- array(),
- array(),
- '',
- '',
- 0,
- $msgishtml
- );
+ $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
- $mail->errors_to = $errorsto;
+ $mail->errors_to = $errorsto;
- // Send or not email
- if ($mode == 'confirm')
- {
- $result=$mail->sendfile();
- if (! $result)
- {
- 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)");
- $mail->dump_mail();
- $result=1;
- }
+ // Send or not email
+ if ($mode == 'confirm') {
+ $result = $mail->sendfile();
+ if (! $result) {
+ 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)");
+ $mail->dump_mail();
+ $result = 1;
+ }
- unset($newlangs);
- if ($result)
- {
- return 1;
- }
- else
- {
- return -1;
- }
+ unset($newlangs);
+ if ($result) {
+ return 1;
+ } else {
+ return - 1;
+ }
}
diff --git a/scripts/contracts/email_expire_services_to_representatives.php b/scripts/contracts/email_expire_services_to_representatives.php
index 19b57c10fc5..be63d4804f9 100755
--- a/scripts/contracts/email_expire_services_to_representatives.php
+++ b/scripts/contracts/email_expire_services_to_representatives.php
@@ -1,9 +1,9 @@
#!/usr/bin/env php
- * Copyright (C) 2005-2013 Laurent Destailleur
- * Copyright (C) 2013 Juanjo Menent
+ * Copyright (C) 2005 Rodolphe Quiedeville
+ * Copyright (C) 2005-2013 Laurent Destailleur
+ * Copyright (C) 2013 Juanjo Menent
*
* 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
@@ -12,7 +12,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -20,263 +20,241 @@
*/
/**
- * \file scripts/contracts/email_expire_services_to_representatives.php
- * \ingroup contracts
- * \brief Script to send a mail to dolibarr users linked to companies with services to expire
+ * \file scripts/contracts/email_expire_services_to_representatives.php
+ * \ingroup contracts
+ * \brief Script to send a mail to dolibarr users linked to companies with services to expire
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test si mode batch
$sapi_type = php_sapi_name();
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";
- exit(-1);
+ 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);
}
-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 "\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 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";
-require_once DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php";
-
-$langs->loadLangs(array('main', 'contracts'));
+$langs->loadLangs(array('main','contracts'));
// Global variables
-$version=DOL_VERSION;
-$error=0;
-
+$version = DOL_VERSION;
+$error = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
-$now=dol_now('tzserver');
-$duration_value=isset($argv[2])?$argv[2]:'none';
+$now = dol_now('tzserver');
+$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.= " 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.= " 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";
-if (is_numeric($duration_value)) $sql .= " AND cd.date_fin_validite < '".$db->idate(dol_time_plus_duree($now, $duration_value, "d"))."'";
-$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
+$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 .= " 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 .= " 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")) . "'";
+$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;
-$resql=$db->query($sql);
-if ($resql)
-{
- $num = $db->num_rows($resql);
- $i = 0;
- $oldemail = 'none'; $olduid = 0; $oldlang='';
- $total = 0; $foundtoprocess = 0;
- 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='';
+// print $sql;
+$resql = $db->query($sql);
+if ($resql) {
+ $num = $db->num_rows($resql);
+ $i = 0;
+ $oldemail = 'none';
+ $olduid = 0;
+ $oldlang = '';
+ $total = 0;
+ $foundtoprocess = 0;
+ 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)
- {
- while ($i < $num)
- {
- $obj = $db->fetch_object($resql);
+ if ($num) {
+ while ($i < $num) {
+ $obj = $db->fetch_object($resql);
- if (($obj->email <> $oldemail || $obj->uid <> $olduid) || $oldemail == 'none')
- {
- // Break onto sales representative (new email or uid)
- if (dol_strlen($oldemail) && $oldemail != 'none')
- {
- envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative, $duration_value);
- }
- else
- {
- if ($oldemail != 'none') print "- No email sent for ".$oldsalerepresentative.", total: ".$total."\n";
- }
- $oldemail = $obj->email;
- $olduid = $obj->uid;
- $oldlang = $obj->lang;
- $oldsalerepresentative=dolGetFirstLastname($obj->firstname, $obj->lastname);
- $message = '';
- $total = 0;
- $foundtoprocess = 0;
- $salerepresentative=dolGetFirstLastname($obj->firstname, $obj->lastname);
- if (empty($obj->email)) print "Warning: Sale representative ".$salerepresentative." has no email. Notice disabled.\n";
- }
+ if (($obj->email != $oldemail || $obj->uid != $olduid) || $oldemail == 'none') {
+ // Break onto sales representative (new email or uid)
+ if (dol_strlen($oldemail) && $oldemail != 'none') {
+ envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative, $duration_value);
+ } else {
+ if ($oldemail != 'none')
+ print "- No email sent for " . $oldsalerepresentative . ", total: " . $total . "\n";
+ }
+ $oldemail = $obj->email;
+ $olduid = $obj->uid;
+ $oldlang = $obj->lang;
+ $oldsalerepresentative = dolGetFirstLastname($obj->firstname, $obj->lastname);
+ $message = '';
+ $total = 0;
+ $foundtoprocess = 0;
+ $salerepresentative = dolGetFirstLastname($obj->firstname, $obj->lastname);
+ if (empty($obj->email))
+ print "Warning: Sale representative " . $salerepresentative . " has no email. Notice disabled.\n";
+ }
- // Define line content
- $outputlangs=new Translate('', $conf);
- $outputlangs->setDefaultLang(empty($obj->lang)?$langs->defaultlang:$obj->lang); // By default language of sale representative
+ // Define line content
+ $outputlangs = new Translate('', $conf);
+ $outputlangs->setDefaultLang(empty($obj->lang) ? $langs->defaultlang : $obj->lang); // By default language of sale representative
- // Load translation files required by the page
- $outputlangs->loadLangs(array("main", "contracts", "bills", "products"));
+ // Load translation files required by the page
+ $outputlangs->loadLangs(array("main","contracts","bills","products"));
- 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";
- dol_syslog("email_expire_services_to_representatives.php: ".$obj->email);
- $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."): ";
- if (dol_strlen($obj->email)) print "qualified.";
- else print "disqualified (no 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";
+ dol_syslog("email_expire_services_to_representatives.php: " . $obj->email);
+ $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 . "): ";
+ if (dol_strlen($obj->email))
+ print "qualified.";
+ else
+ print "disqualified (no email).";
print "\n";
unset($outputlangs);
$total += $obj->total_ttc;
- $i++;
- }
+ $i ++;
+ }
- // Si il reste des envois en buffer
- if ($foundtoprocess)
- {
- if (dol_strlen($oldemail) && $oldemail != 'none') // Break onto email (new email)
- {
- envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative, $duration_value);
- }
- else
+ // Si il reste des envois en buffer
+ if ($foundtoprocess) {
+ if (dol_strlen($oldemail) && $oldemail != 'none') // Break onto email (new email)
{
- 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";
- }
+ 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";
+ }
- 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 $oldemail Old email
- * @param string $message Message to send
- * @param string $total 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
+ * @param string $mode
+ * Mode (test | confirm)
+ * @param string $oldemail
+ * Old email
+ * @param string $message
+ * Message to send
+ * @param string $total
+ * 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)
{
- 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->setDefaultLang(empty($userlang)?(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT):$userlang);
- $newlangs->load("main");
- $newlangs->load("contracts");
+ $newlangs = new Translate('', $conf);
+ $newlangs->setDefaultLang(empty($userlang) ? (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT) : $userlang);
+ $newlangs->load("main");
+ $newlangs->load("contracts");
- if ($duration_value)
- {
- if ($duration_value > 0) $title=$newlangs->transnoentities("ListOfServicesToExpireWithDuration", $duration_value);
- else $title=$newlangs->transnoentities("ListOfServicesToExpireWithDurationNeg", $duration_value);
- }
- else
- $title= $newlangs->transnoentities("ListOfServicesToExpire");
+ if ($duration_value) {
+ if ($duration_value > 0)
+ $title = $newlangs->transnoentities("ListOfServicesToExpireWithDuration", $duration_value);
+ else
+ $title = $newlangs->transnoentities("ListOfServicesToExpireWithDurationNeg", $duration_value);
+ } else
+ $title = $newlangs->transnoentities("ListOfServicesToExpire");
- $subject = (empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_SUBJECT)?$title:$conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_SUBJECT);
- $sendto = $oldemail;
- $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
- $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
- $msgishtml = -1;
+ $subject = (empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_SUBJECT) ? $title : $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_SUBJECT);
+ $sendto = $oldemail;
+ $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
+ $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
+ $msgishtml = - 1;
- print "- Send email for ".$oldsalerepresentative." (".$oldemail."), total: ".$total."\n";
- dol_syslog("email_expire_services_to_representatives.php: send mail to ".$oldemail);
+ print "- Send email for " . $oldsalerepresentative . " (" . $oldemail . "), total: " . $total . "\n";
+ dol_syslog("email_expire_services_to_representatives.php: send mail to " . $oldemail);
- $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_HEADER)) $usehtml+=1;
+ $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_HEADER))
+ $usehtml += 1;
- $allmessage='';
- if (! empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER))
- {
- $allmessage.=$conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER;
- }
- else
- {
- $allmessage.= $title.($usehtml?" \n":"\n").($usehtml?" \n":"\n");
- $allmessage.= $newlangs->transnoentities("NoteListOfYourExpiredServices").($usehtml?" \n":"\n").($usehtml?" \n":"\n");
- }
- $allmessage.= $message.($usehtml?" \n":"\n");
- $allmessage.= $langs->trans("Total")." = ".price($total, 0, $userlang, 0, 0, -1, $conf->currency).($usehtml?" \n":"\n");
- if (! empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER))
- {
- $allmessage.=$conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER;
- if (dol_textishtml($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER)) $usehtml+=1;
- }
+ $allmessage = '';
+ if (! empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER)) {
+ $allmessage .= $conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_HEADER;
+ } else {
+ $allmessage .= $title . ($usehtml ? " \n" : "\n") . ($usehtml ? " \n" : "\n");
+ $allmessage .= $newlangs->transnoentities("NoteListOfYourExpiredServices") . ($usehtml ? " \n" : "\n") . ($usehtml ? " \n" : "\n");
+ }
+ $allmessage .= $message . ($usehtml ? " \n" : "\n");
+ $allmessage .= $langs->trans("Total") . " = " . price($total, 0, $userlang, 0, 0, - 1, $conf->currency) . ($usehtml ? " \n" : "\n");
+ if (! empty($conf->global->SCRIPT_EMAIL_EXPIRE_SERVICES_SALESREPRESENTATIVES_FOOTER)) {
+ $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(
- $subject,
- $sendto,
- $from,
- $allmessage,
- array(),
- array(),
- array(),
- '',
- '',
- 0,
- $msgishtml
- );
+ $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
- $mail->errors_to = $errorsto;
+ $mail->errors_to = $errorsto;
- // Send or not email
- if ($mode == 'confirm')
- {
- $result=$mail->sendfile();
- if (! $result)
- {
- 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)");
- $mail->dump_mail();
- $result=1;
- }
+ // Send or not email
+ if ($mode == 'confirm') {
+ $result = $mail->sendfile();
+ if (! $result) {
+ 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)");
+ $mail->dump_mail();
+ $result = 1;
+ }
- if ($result)
- {
- return 1;
- }
- else
- {
- return -1;
- }
+ if ($result) {
+ return 1;
+ } else {
+ return - 1;
+ }
}
diff --git a/scripts/cron/cron_run_jobs.php b/scripts/cron/cron_run_jobs.php
index b115f4bbea9..54559e28c19 100755
--- a/scripts/cron/cron_run_jobs.php
+++ b/scripts/cron/cron_run_jobs.php
@@ -1,7 +1,8 @@
#!/usr/bin/env php
*
* 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,
* 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.
*
* You should have received a copy of the GNU General Public License
@@ -19,255 +20,231 @@
*/
/**
- * \file scripts/cron/cron_run_jobs.php
- * \ingroup cron
- * \brief Execute pendings jobs
+ * \file scripts/cron/cron_run_jobs.php
+ * \ingroup cron
+ * \brief Execute pendings jobs
*/
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal
-if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1');
-if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1');
-if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1');
-if (! defined('NOLOGIN')) define('NOLOGIN', '1');
-//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1');
-
+if (! defined('NOTOKENRENEWAL'))
+ define('NOTOKENRENEWAL', '1'); // Disables token renewal
+if (! defined('NOREQUIREMENU'))
+ define('NOREQUIREMENU', '1');
+if (! defined('NOREQUIREHTML'))
+ 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();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Error if Web mode
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";
- exit(-1);
+ 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);
}
-require_once $path."../../htdocs/master.inc.php";
-require_once DOL_DOCUMENT_ROOT."/cron/class/cronjob.class.php";
-require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
+require_once $path . "../../htdocs/master.inc.php";
+require_once DOL_DOCUMENT_ROOT . "/cron/class/cronjob.class.php";
+require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
// Check parameters
if (! isset($argv[1]) || ! $argv[1]) {
usage($path, $script_file);
- exit(-1);
+ exit(- 1);
}
-$key=$argv[1];
+$key = $argv[1];
if (! isset($argv[2]) || ! $argv[2]) {
usage($path, $script_file);
- exit(-1);
+ exit(- 1);
}
-$userlogin=$argv[2];
-
+$userlogin = $argv[2];
// Global variables
-$version=DOL_VERSION;
-$error=0;
-
-
+$version = DOL_VERSION;
+$error = 0;
/*
* Main
*/
-$langs->loadLangs(array('main', 'dict'));
+$langs->loadLangs(array('main','dict'));
// current date
-$now=dol_now();
+$now = dol_now();
@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
-if (empty($conf->cron->enabled))
-{
+if (empty($conf->cron->enabled)) {
print "Error: module Scheduled jobs (cron) not activated\n";
- exit(-1);
+ exit(- 1);
}
// Check module cron is activated
-if (empty($conf->cron->enabled))
-{
+if (empty($conf->cron->enabled)) {
print "Error: module Scheduled jobs (cron) not activated\n";
- exit(-1);
+ exit(- 1);
}
// Check security key
-if ($key != $conf->global->CRON_KEY)
-{
+if ($key != $conf->global->CRON_KEY) {
print "Error: securitykey is wrong\n";
- exit(-1);
+ exit(- 1);
}
// If param userlogin is reserved word 'firstadmin'
-if ($userlogin == 'firstadmin')
-{
- $sql='SELECT login, entity from '.MAIN_DB_PREFIX.'user WHERE admin = 1 and statut = 1 ORDER BY entity LIMIT 1';
- $resql=$db->query($sql);
- if ($resql)
- {
- $obj=$db->fetch_object($resql);
- if ($obj)
- {
- $userlogin = $obj->login;
- echo "First admin user found is login '".$userlogin."', entity ".$obj->entity."\n";
- }
- }
- else dol_print_error($db);
+if ($userlogin == 'firstadmin') {
+ $sql = 'SELECT login, entity from ' . MAIN_DB_PREFIX . 'user WHERE admin = 1 and statut = 1 ORDER BY entity LIMIT 1';
+ $resql = $db->query($sql);
+ if ($resql) {
+ $obj = $db->fetch_object($resql);
+ if ($obj) {
+ $userlogin = $obj->login;
+ echo "First admin user found is login '" . $userlogin . "', entity " . $obj->entity . "\n";
+ }
+ } else
+ dol_print_error($db);
}
// Check user login
-$user=new User($db);
-$result=$user->fetch('', $userlogin);
-if ($result < 0)
-{
- echo "User Error: ".$user->error;
- dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR);
- exit(-1);
-}
-else
-{
- if (empty($user->id))
- {
- echo "User login: ".$userlogin." does not exists";
- dol_syslog("User login:".$userlogin." does not exists", LOG_ERR);
- exit(-1);
+$user = new User($db);
+$result = $user->fetch('', $userlogin);
+if ($result < 0) {
+ echo "User Error: " . $user->error;
+ dol_syslog("cron_run_jobs.php:: User Error:" . $user->error, LOG_ERR);
+ exit(- 1);
+} else {
+ if (empty($user->id)) {
+ echo "User login: " . $userlogin . " does not exists";
+ dol_syslog("User login:" . $userlogin . " does not exists", LOG_ERR);
+ exit(- 1);
}
}
$user->getrights();
-if (isset($argv[3]) || $argv[3])
-{
+if (isset($argv[3]) || $argv[3]) {
$id = $argv[3];
}
// create a jobs object
$object = new Cronjob($db);
-$filter=array();
+$filter = array();
if (! empty($id)) {
- if (! is_numeric($id))
- {
+ if (! is_numeric($id)) {
echo "Error: Bad value for parameter job id";
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);
-if ($result<0)
-{
- echo "Error: ".$object->error;
- dol_syslog("cron_run_jobs.php:: fetch Error ".$object->error, LOG_ERR);
- exit(-1);
+if ($result < 0) {
+ echo "Error: " . $object->error;
+ dol_syslog("cron_run_jobs.php:: fetch Error " . $object->error, LOG_ERR);
+ exit(- 1);
}
-
$qualifiedjobs = array();
-foreach($object->lines as $val)
-{
- if (! verifCond($val->test)) continue;
+foreach ($object->lines as $val) {
+ if (! verifCond($val->test))
+ continue;
$qualifiedjobs[] = $val;
}
// TODO Duplicate. This sequence of code must be shared with code into public/cron/cron_run_jobs.php php page.
-$nbofjobs=count($qualifiedjobs);
-$nbofjobslaunchedok=0;
-$nbofjobslaunchedko=0;
+$nbofjobs = count($qualifiedjobs);
+$nbofjobslaunchedok = 0;
+$nbofjobslaunchedko = 0;
-if (is_array($qualifiedjobs) && (count($qualifiedjobs)>0))
-{
+if (is_array($qualifiedjobs) && (count($qualifiedjobs) > 0)) {
// Loop over job
- foreach($qualifiedjobs as $line)
- {
- dol_syslog("cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label, LOG_DEBUG);
+ foreach ($qualifiedjobs as $line) {
+ 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 (($line->datenextrun < $now) && (empty($line->datestart) || $line->datestart <= $now) && (empty($line->dateend) || $line->dateend >= $now))
- {
+ // 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)) {
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);
- $result=$cronjob->fetch($line->id);
- if ($result < 0)
- {
- echo "Error cronjobid: ".$line->id." cronjob->fetch: ".$cronjob->error."\n";
- echo "Failed to fetch job ".$line->id."\n";
- dol_syslog("cron_run_jobs.php::fetch Error ".$cronjob->error, LOG_ERR);
- exit(-1);
+ $cronjob = new Cronjob($db);
+ $result = $cronjob->fetch($line->id);
+ if ($result < 0) {
+ echo "Error cronjobid: " . $line->id . " cronjob->fetch: " . $cronjob->error . "\n";
+ echo "Failed to fetch job " . $line->id . "\n";
+ dol_syslog("cron_run_jobs.php::fetch Error " . $cronjob->error, LOG_ERR);
+ exit(- 1);
}
// Execute job
- $result=$cronjob->run_jobs($userlogin);
- if ($result < 0)
- {
- echo "Error cronjobid: ".$line->id." cronjob->run_job: ".$cronjob->error."\n";
+ $result = $cronjob->run_jobs($userlogin);
+ if ($result < 0) {
+ 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 "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);
- $nbofjobslaunchedko++;
- }
- else
- {
- $nbofjobslaunchedok++;
+ dol_syslog("cron_run_jobs.php::run_jobs Error " . $cronjob->error, LOG_ERR);
+ $nbofjobslaunchedko ++;
+ } else {
+ $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
- $result=$cronjob->reprogram_jobs($userlogin, $now);
- if ($result<0)
- {
- echo "Error cronjobid: ".$line->id." cronjob->reprogram_job: ".$cronjob->error."\n";
+ $result = $cronjob->reprogram_jobs($userlogin, $now);
+ if ($result < 0) {
+ 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";
- dol_syslog("cron_run_jobs.php::reprogram_jobs Error ".$cronjob->error, LOG_ERR);
- exit(-1);
+ dol_syslog("cron_run_jobs.php::reprogram_jobs Error " . $cronjob->error, LOG_ERR);
+ exit(- 1);
}
echo " - reprogrammed\n";
- }
- else
- {
+ } else {
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";
}
$db->close();
-if ($nbofjobslaunchedko) exit(1);
+if ($nbofjobslaunchedko)
+ exit(1);
exit(0);
-
-
/**
* script cron usage
*
- * @param string $path path
- * @param string $script_file filename
+ * @param string $path
+ * path
+ * @param string $script_file
+ * filename
* @return void
*/
function usage($path, $script_file)
{
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 "\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 "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 "*/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";
}
diff --git a/scripts/emailings/mailing-send.php b/scripts/emailings/mailing-send.php
index f3d88592dc4..0e161a9c9cc 100755
--- a/scripts/emailings/mailing-send.php
+++ b/scripts/emailings/mailing-send.php
@@ -1,9 +1,9 @@
#!/usr/bin/env php
- * Copyright (C) 2005-2013 Laurent Destailleur
- * Copyright (C) 2005-2016 Regis Houssin
+ * Copyright (C) 2004 Rodolphe Quiedeville
+ * Copyright (C) 2005-2013 Laurent Destailleur
+ * Copyright (C) 2005-2016 Regis Houssin
*
* 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
@@ -12,386 +12,347 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
-
/**
- * \file scripts/emailings/mailing-send.php
- * \ingroup mailing
- * \brief Script d'envoi d'un mailing prepare et valide
+ * \file scripts/emailings/mailing-send.php
+ * \ingroup mailing
+ * \brief Script d'envoi d'un mailing prepare et valide
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test if batch mode
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";
- exit(-1);
+ 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);
}
if (! isset($argv[1]) || ! $argv[1]) {
- print "Usage: ".$script_file." (ID_MAILING|all)\n";
- exit(-1);
+ print "Usage: " . $script_file . " (ID_MAILING|all)\n";
+ exit(- 1);
}
-$id=$argv[1];
-if (isset($argv[2]) || !empty($argv[2])) $login = $argv[2];
-else $login = '';
-
-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";
+$id = $argv[1];
+if (isset($argv[2]) || ! empty($argv[2]))
+ $login = $argv[2];
+else
+ $login = '';
+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
-$version=DOL_VERSION;
-$error=0;
-
-
+$version = DOL_VERSION;
+$error = 0;
/*
* Main
*/
@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);
// 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
$sql = "SELECT m.rowid";
-$sql.= " FROM ".MAIN_DB_PREFIX."mailing as m";
-$sql.= " WHERE m.statut IN (1,2)";
-if ($id != 'all')
-{
- $sql.= " AND m.rowid= ".$id;
- $sql.= " LIMIT 1";
+$sql .= " FROM " . MAIN_DB_PREFIX . "mailing as m";
+$sql .= " WHERE m.statut IN (1,2)";
+if ($id != 'all') {
+ $sql .= " AND m.rowid= " . $id;
+ $sql .= " LIMIT 1";
}
-$resql=$db->query($sql);
-if ($resql)
-{
+$resql = $db->query($sql);
+if ($resql) {
$num = $db->num_rows($resql);
$j = 0;
- if ($num)
- {
- for ($j=0; $j<$num; $j++)
- {
+ if ($num) {
+ for ($j = 0; $j < $num; $j ++) {
$obj = $db->fetch_object($resql);
- dol_syslog("Process mailing with id ".$obj->rowid);
- print "Process mailing with id ".$obj->rowid."\n";
+ dol_syslog("Process mailing with id " . $obj->rowid);
+ print "Process mailing with id " . $obj->rowid . "\n";
$emailing = new Mailing($db);
$emailing->fetch($obj->rowid);
- $id = $emailing->id;
- $subject = $emailing->sujet;
- $message = $emailing->body;
- $from = $emailing->email_from;
- $replyto = $emailing->email_replyto;
+ $id = $emailing->id;
+ $subject = $emailing->sujet;
+ $message = $emailing->body;
+ $from = $emailing->email_from;
+ $replyto = $emailing->email_replyto;
$errorsto = $emailing->email_errorsto;
// Le message est-il en html
- $msgishtml=-1; // Unknown by default
- if (preg_match('/[\s\t]*/i', $message)) $msgishtml=1;
+ $msgishtml = - 1; // Unknown by default
+ if (preg_match('/[\s\t]*/i', $message))
+ $msgishtml = 1;
- $nbok=0; $nbko=0;
+ $nbok = 0;
+ $nbko = 0;
// On choisit les mails non deja envoyes pour ce mailing (statut=0)
// 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.= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc";
- $sql2.= " WHERE mc.statut < 1 AND mc.fk_mailing = ".$id;
- if ($conf->global->MAILING_LIMIT_SENDBYCLI > 0)
- {
- $sql2.= " LIMIT ".$conf->global->MAILING_LIMIT_SENDBYCLI;
+ $sql2 .= " FROM " . MAIN_DB_PREFIX . "mailing_cibles as mc";
+ $sql2 .= " WHERE mc.statut < 1 AND mc.fk_mailing = " . $id;
+ if ($conf->global->MAILING_LIMIT_SENDBYCLI > 0) {
+ $sql2 .= " LIMIT " . $conf->global->MAILING_LIMIT_SENDBYCLI;
}
- $resql2=$db->query($sql2);
- if ($resql2)
- {
+ $resql2 = $db->query($sql2);
+ if ($resql2) {
$num2 = $db->num_rows($resql2);
- dol_syslog("Nb of targets = ".$num2, LOG_DEBUG);
- print "Nb of targets = ".$num2."\n";
+ dol_syslog("Nb of targets = " . $num2, LOG_DEBUG);
+ print "Nb of targets = " . $num2 . "\n";
- if ($num2)
- {
- $now=dol_now();
+ if ($num2) {
+ $now = dol_now();
// Positionne date debut envoi
- $sqlstartdate="UPDATE ".MAIN_DB_PREFIX."mailing SET date_envoi='".$db->idate($now)."' WHERE rowid=".$id;
- $resqlstartdate=$db->query($sqlstartdate);
- if (! $resqlstartdate)
- {
+ $sqlstartdate = "UPDATE " . MAIN_DB_PREFIX . "mailing SET date_envoi='" . $db->idate($now) . "' WHERE rowid=" . $id;
+ $resqlstartdate = $db->query($sqlstartdate);
+ if (! $resqlstartdate) {
dol_print_error($db);
- $error++;
+ $error ++;
}
// Look on each email and sent message
$i = 0;
- while ($i < $num2)
- {
+ while ($i < $num2) {
// Here code is common with same loop ino card.php
- $res=1;
- $now=dol_now();
+ $res = 1;
+ $now = dol_now();
$obj = $db->fetch_object($resql2);
// 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
- $other=explode(';', $obj->other);
- $tmpfield=explode('=', $other[0], 2); $other1=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]);
- $tmpfield=explode('=', $other[1], 2); $other2=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]);
- $tmpfield=explode('=', $other[2], 2); $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:'');
+ $other = explode(';', $obj->other);
+ $tmpfield = explode('=', $other[0], 2);
+ $other1 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]);
+ $tmpfield = explode('=', $other[1], 2);
+ $other2 = (isset($tmpfield[1]) ? $tmpfield[1] : $tmpfield[0]);
+ $tmpfield = explode('=', $other[2], 2);
+ $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
- $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
+ $object = null; // Not defined with mass 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
// Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
$substitutionarray['__ID__'] = $obj->source_id;
$substitutionarray['__EMAIL__'] = $obj->email;
$substitutionarray['__LASTNAME__'] = $obj->lastname;
$substitutionarray['__FIRSTNAME__'] = $obj->firstname;
- $substitutionarray['__MAILTOEMAIL__'] = ''.$obj->email.' ';
+ $substitutionarray['__MAILTOEMAIL__'] = '' . $obj->email . ' ';
$substitutionarray['__OTHER1__'] = $other1;
$substitutionarray['__OTHER2__'] = $other2;
$substitutionarray['__OTHER3__'] = $other3;
$substitutionarray['__OTHER4__'] = $other4;
$substitutionarray['__OTHER5__'] = $other5;
- $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['__CHECK_READ__'] = ' ';
- $substitutionarray['__UNSUBSCRIBE__'] = ''.$langs->trans("MailUnsubcribe").' ';
+ $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['__CHECK_READ__'] = ' ';
+ $substitutionarray['__UNSUBSCRIBE__'] = '' . $langs->trans("MailUnsubcribe") . ' ';
$onlinepaymentenabled = 0;
- if (! empty($conf->paypal->enabled)) $onlinepaymentenabled++;
- if (! empty($conf->paybox->enabled)) $onlinepaymentenabled++;
- if (! empty($conf->stripe->enabled)) $onlinepaymentenabled++;
- if ($onlinepaymentenabled && ! empty($conf->global->PAYMENT_SECURITY_TOKEN))
- {
- $substitutionarray['__SECUREKEYPAYMENT__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
- if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE))
- {
- $substitutionarray['__SECUREKEYPAYMENT_MEMBER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
- $substitutionarray['__SECUREKEYPAYMENT_ORDER__']=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
- {
- $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_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);
+ if (! empty($conf->paypal->enabled))
+ $onlinepaymentenabled ++;
+ if (! empty($conf->paybox->enabled))
+ $onlinepaymentenabled ++;
+ if (! empty($conf->stripe->enabled))
+ $onlinepaymentenabled ++;
+ if ($onlinepaymentenabled && ! empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
+ $substitutionarray['__SECUREKEYPAYMENT__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
+ if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
+ $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
+ $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 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 {
+ $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_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);
}
}
/* For backward compatibility */
- if (! empty($conf->paypal->enabled) && ! empty($conf->global->PAYPAL_SECURITY_TOKEN))
- {
- $substitutionarray['__SECUREKEYPAYPAL__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
+ if (! empty($conf->paypal->enabled) && ! empty($conf->global->PAYPAL_SECURITY_TOKEN)) {
+ $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);
- 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_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);
- 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_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);
- 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_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);
- else $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'contractline' . $obj->source_id, 2);
+ if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE))
+ $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);
- $newsubject=make_substitutions($subject, $substitutionarray);
- $newmessage=make_substitutions($message, $substitutionarray);
+ $newsubject = make_substitutions($subject, $substitutionarray);
+ $newmessage = make_substitutions($message, $substitutionarray);
- $substitutionisok=true;
+ $substitutionisok = true;
// Fabrication du mail
- $trackid='emailing-'.$obj->fk_mailing.'-'.$obj->rowid;
- $mail = new CMailFile(
- $newsubject,
- $sendto,
- $from,
- $newmessage,
- array(),
- array(),
- array(),
- '',
- '',
- 0,
- $msgishtml,
- $errorsto,
- '',
- $trackid,
- '',
- 'emailing'
- );
+ $trackid = 'emailing-' . $obj->fk_mailing . '-' . $obj->rowid;
+ $mail = new CMailFile($newsubject, $sendto, $from, $newmessage, array(), array(), array(), '', '', 0, $msgishtml, $errorsto, '', $trackid, '', 'emailing');
- if ($mail->error)
- {
- $res=0;
+ if ($mail->error) {
+ $res = 0;
}
- if (! $substitutionisok)
- {
- $mail->error='Some substitution failed';
- $res=0;
+ if (! $substitutionisok) {
+ $mail->error = 'Some substitution failed';
+ $res = 0;
}
// Send Email
- if ($res)
- {
- $res=$mail->sendfile();
+ if ($res) {
+ $res = $mail->sendfile();
}
- if ($res)
- {
+ if ($res) {
// 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
// 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
/*
- if ($obj->source_type == 'contact')
- {
- $emailing->sendtoid = $obj->source_id;
- }
- if ($obj->source_type == 'thirdparty')
- {
- $emailing->socid = $obj->source_id;
- }
- // Call trigger
- $result=$emailing->call_trigger('EMAILING_SENTBYMAIL',$user);
- if ($result < 0) $error++;
- // End call triggers
- */
+ * if ($obj->source_type == 'contact')
+ * {
+ * $emailing->sendtoid = $obj->source_id;
+ * }
+ * if ($obj->source_type == 'thirdparty')
+ * {
+ * $emailing->socid = $obj->source_id;
+ * }
+ * // Call trigger
+ * $result=$emailing->call_trigger('EMAILING_SENTBYMAIL',$user);
+ * if ($result < 0) $error++;
+ * // End call triggers
+ */
- $sqlok ="UPDATE ".MAIN_DB_PREFIX."mailing_cibles";
- $sqlok.=" SET statut=1, date_envoi='".$db->idate($now)."' WHERE rowid=".$obj->rowid;
- $resqlok=$db->query($sqlok);
- if (! $resqlok)
- {
+ $sqlok = "UPDATE " . MAIN_DB_PREFIX . "mailing_cibles";
+ $sqlok .= " SET statut=1, date_envoi='" . $db->idate($now) . "' WHERE rowid=" . $obj->rowid;
+ $resqlok = $db->query($sqlok);
+ if (! $resqlok) {
dol_print_error($db);
- $error++;
- }
- else
- {
- //if cheack read is use then update prospect contact status
- if (strpos($message, '__CHECK_READ__') !== false)
- {
- //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.")";
+ $error ++;
+ } else {
+ // if cheack read is use then update prospect contact status
+ if (strpos($message, '__CHECK_READ__') !== false) {
+ // 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);
- $resqlx=$db->query($sqlx);
- if (! $resqlx)
- {
+ $resqlx = $db->query($sqlx);
+ if (! $resqlx) {
dol_print_error($db);
- $error++;
+ $error ++;
}
- //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)";
+ // 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)";
dol_syslog("card.php: set prospect contact status", LOG_DEBUG);
- $resqlx=$db->query($sqlx);
- if (! $resqlx)
- {
+ $resqlx = $db->query($sqlx);
+ if (! $resqlx) {
dol_print_error($db);
- $error++;
+ $error ++;
}
}
- if (!empty($conf->global->MAILING_DELAY)) {
+ if (! empty($conf->global->MAILING_DELAY)) {
sleep($conf->global->MAILING_DELAY);
}
}
- }
- else
- {
+ } else {
// 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.=" SET statut=-1, date_envoi=".$db->idate($now)." WHERE rowid=".$obj->rowid;
- $resqlerror=$db->query($sqlerror);
- if (! $resqlerror)
- {
+ $sqlerror = "UPDATE " . MAIN_DB_PREFIX . "mailing_cibles";
+ $sqlerror .= " SET statut=-1, date_envoi=" . $db->idate($now) . " WHERE rowid=" . $obj->rowid;
+ $resqlerror = $db->query($sqlerror);
+ if (! $resqlerror) {
dol_print_error($db);
- $error++;
+ $error ++;
}
}
- $i++;
+ $i ++;
}
- }
- else
- {
- $mesg="Emailing id ".$id." has no recipient to target";
- print $mesg."\n";
+ } else {
+ $mesg = "Emailing id " . $id . " has no recipient to target";
+ print $mesg . "\n";
dol_syslog($mesg, LOG_ERR);
}
// Loop finished, set global statut of mail
- $statut=2;
- if (! $nbko) $statut=3;
+ $statut = 2;
+ 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);
- print "Update status of emailing id ".$id." to ".$statut."\n";
- $resqlenddate=$db->query($sqlenddate);
- if (! $resqlenddate)
- {
+ print "Update status of emailing id " . $id . " to " . $statut . "\n";
+ $resqlenddate = $db->query($sqlenddate);
+ if (! $resqlenddate) {
dol_print_error($db);
- $error++;
+ $error ++;
}
- }
- else
- {
+ } else {
dol_print_error($db);
- $error++;
+ $error ++;
}
}
- }
- else
- {
- $mesg="No validated emailing id to send found.";
- print $mesg."\n";
+ } else {
+ $mesg = "No validated emailing id to send found.";
+ print $mesg . "\n";
dol_syslog($mesg, LOG_ERR);
- $error++;
+ $error ++;
}
-}
-else
-{
+} else {
dol_print_error($db);
- $error++;
+ $error ++;
}
-
exit($error);
diff --git a/scripts/invoices/email_unpaid_invoices_to_customers.php b/scripts/invoices/email_unpaid_invoices_to_customers.php
index 5681688c645..e64c9e10edb 100755
--- a/scripts/invoices/email_unpaid_invoices_to_customers.php
+++ b/scripts/invoices/email_unpaid_invoices_to_customers.php
@@ -1,9 +1,9 @@
#!/usr/bin/env php
- * Copyright (C) 2005-2013 Laurent Destailleur
- * Copyright (C) 2013 Juanjo Menent
+ * Copyright (C) 2005 Rodolphe Quiedeville
+ * Copyright (C) 2005-2013 Laurent Destailleur
+ * Copyright (C) 2013 Juanjo Menent
*
* 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
@@ -12,7 +12,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -20,288 +20,272 @@
*/
/**
- * \file scripts/invoices/email_unpaid_invoices_to_customers.php
- * \ingroup facture
- * \brief Script to send a mail to customers with unpaid invoices
+ * \file scripts/invoices/email_unpaid_invoices_to_customers.php
+ * \ingroup facture
+ * \brief Script to send a mail to customers with unpaid invoices
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test si mode batch
$sapi_type = php_sapi_name();
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";
- exit(-1);
+ 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);
}
-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 "\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 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";
- exit(-1);
+ exit(- 1);
}
-$mode=$argv[1];
-$targettype=$argv[2];
+$mode = $argv[1];
+$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";
+require_once DOL_DOCUMENT_ROOT . "/core/class/CMailFile.class.php";
$langs->load('main');
// Global variables
-$version=DOL_VERSION;
-$error=0;
-
-
+$version = DOL_VERSION;
+$error = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
-$now=dol_now('tzserver');
-$duration_value=isset($argv[3])?$argv[3]:'none';
-$duration_value2=isset($argv[4])?$argv[4]:'none';
+$now = dol_now('tzserver');
+$duration_value = isset($argv[3]) ? $argv[3] : 'none';
+$duration_value2 = isset($argv[4]) ? $argv[4] : 'none';
$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.= " 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";
-$sql.= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."societe as s";
-if ($targettype == 'contacts') $sql.= ", ".MAIN_DB_PREFIX."socpeople as sp";
-$sql.= " WHERE f.fk_statut = 1 AND f.paye = 0";
-$sql.= " AND f.fk_soc = s.rowid";
-if (is_numeric($duration_value2)) $sql.= " AND f.date_lim_reglement >= '".$db->idate(dol_time_plus_duree($now, $duration_value2, "d"))."'";
-if (is_numeric($duration_value)) $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
+$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";
+$sql .= " FROM " . MAIN_DB_PREFIX . "facture as f, " . MAIN_DB_PREFIX . "societe as s";
+if ($targettype == 'contacts')
+ $sql .= ", " . MAIN_DB_PREFIX . "socpeople as sp";
+$sql .= " WHERE f.fk_statut = 1 AND f.paye = 0";
+$sql .= " AND f.fk_soc = s.rowid";
+if (is_numeric($duration_value2))
+ $sql .= " AND f.date_lim_reglement >= '" . $db->idate(dol_time_plus_duree($now, $duration_value2, "d")) . "'";
+if (is_numeric($duration_value))
+ $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;
-$resql=$db->query($sql);
-if ($resql)
-{
- $num = $db->num_rows($resql);
- $i = 0;
- $oldemail = 'none'; $oldsid = 0; $oldcid = 0; $oldlang='';
- $total = 0; $foundtoprocess = 0;
- $trackthirdpartiessent = array();
+// print $sql;
+$resql = $db->query($sql);
+if ($resql) {
+ $num = $db->num_rows($resql);
+ $i = 0;
+ $oldemail = 'none';
+ $oldsid = 0;
+ $oldcid = 0;
+ $oldlang = '';
+ $total = 0;
+ $foundtoprocess = 0;
+ $trackthirdpartiessent = array();
- print "We found ".$num." couples (unpayed validated invoices-".$targettype.") qualified\n";
- dol_syslog("We found ".$num." couples (unpayed validated invoices-".$targettype.") qualified");
- $message='';
+ print "We found " . $num . " couples (unpayed validated invoices-" . $targettype . ") qualified\n";
+ dol_syslog("We found " . $num . " couples (unpayed validated invoices-" . $targettype . ") qualified");
+ $message = '';
- if ($num)
- {
- while ($i < $num)
- {
- $obj = $db->fetch_object($resql);
+ if ($num) {
+ while ($i < $num) {
+ $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
- $startbreak=false;
- if ($newemail <> $oldemail || $oldemail == 'none') $startbreak=true;
- if ($obj->sid && $obj->sid <> $oldsid) $startbreak=true;
- if ($obj->cid && $obj->cid <> $oldcid) $startbreak=true;
+ // Check if this record is a break after previous one
+ $startbreak = false;
+ if ($newemail != $oldemail || $oldemail == 'none')
+ $startbreak = true;
+ if ($obj->sid && $obj->sid != $oldsid)
+ $startbreak = true;
+ if ($obj->cid && $obj->cid != $oldcid)
+ $startbreak = true;
- if ($startbreak)
- {
- // Break onto sales representative (new email or cid)
- if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid.'|'.$oldemail]))
- {
- envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget);
- $trackthirdpartiessent[$oldsid.'|'.$oldemail]='contact id '.$oldcid;
- }
- else
- {
- 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";
- }
- }
- $oldemail = $newemail;
- $oldsid = $obj->sid;
- $oldcid = $obj->cid;
- $oldlang = $obj->lang;
- $oldtarget=(empty($obj->cfirstname) && empty($obj->clastname))?$obj->name:($obj->clastname." ".$obj->cfirstname);
- $message = '';
- $total = 0;
- $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";
- }
+ if ($startbreak) {
+ // Break onto sales representative (new email or cid)
+ if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid . '|' . $oldemail])) {
+ envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget);
+ $trackthirdpartiessent[$oldsid . '|' . $oldemail] = 'contact id ' . $oldcid;
+ } else {
+ 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";
+ }
+ }
+ $oldemail = $newemail;
+ $oldsid = $obj->sid;
+ $oldcid = $obj->cid;
+ $oldlang = $obj->lang;
+ $oldtarget = (empty($obj->cfirstname) && empty($obj->clastname)) ? $obj->name : ($obj->clastname . " " . $obj->cfirstname);
+ $message = '';
+ $total = 0;
+ $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
- $outputlangs=new Translate('', $conf);
- $outputlangs->setDefaultLang(empty($obj->default_lang)?$langs->defaultlang:$obj->default_lang); // By default language of customer
+ // Define line content
+ $outputlangs = new Translate('', $conf);
+ $outputlangs->setDefaultLang(empty($obj->default_lang) ? $langs->defaultlang : $obj->default_lang); // By default language of customer
- // Load translation files required by the page
- $outputlangs->loadLangs(array("main", "bills"));
+ // Load translation files required by the page
+ $outputlangs->loadLangs(array("main","bills"));
- if (dol_strlen($newemail))
- {
- $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);
- $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.": ";
- if (dol_strlen($newemail)) print "qualified.";
- else print "disqualified (no email).";
- print "\n";
+ if (dol_strlen($newemail)) {
+ $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);
+ $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 . ": ";
+ if (dol_strlen($newemail))
+ print "qualified.";
+ else
+ 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
- if ($foundtoprocess)
- {
- 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
+ // Si il reste des envois en buffer
+ if ($foundtoprocess) {
+ if (dol_strlen($oldemail) && $oldemail != 'none' && empty($trackthirdpartiessent[$oldsid . '|' . $oldemail])) // Break onto email (new email)
{
- 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";
- }
+ envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldtarget);
+ $trackthirdpartiessent[$oldsid . '|' . $oldemail] = 'contact id ' . $oldcid;
+ } else {
+ 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";
+ }
- 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 $oldemail Target email
- * @param string $message Message to send
- * @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
+ * @param string $mode
+ * Mode (test | confirm)
+ * @param string $oldemail
+ * Target email
+ * @param string $message
+ * Message to send
+ * @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)
{
- 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->setDefaultLang(empty($userlang)?(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT):$userlang);
- $newlangs->load("main");
- $newlangs->load("bills");
+ $newlangs = new Translate('', $conf);
+ $newlangs->setDefaultLang(empty($userlang) ? (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT) : $userlang);
+ $newlangs->load("main");
+ $newlangs->load("bills");
- $subject = (empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_SUBJECT)?$newlangs->trans("ListOfYourUnpaidInvoices"):$conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_SUBJECT);
- $sendto = $oldemail;
- $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
- $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
- $msgishtml = -1;
+ $subject = (empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_SUBJECT) ? $newlangs->trans("ListOfYourUnpaidInvoices") : $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_SUBJECT);
+ $sendto = $oldemail;
+ $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
+ $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
+ $msgishtml = - 1;
- print "- Send email to '".$oldtarget."' (".$oldemail."), total: ".$total."\n";
- dol_syslog("email_unpaid_invoices_to_customers.php: send mail to ".$oldemail);
+ print "- Send email to '" . $oldtarget . "' (" . $oldemail . "), total: " . $total . "\n";
+ dol_syslog("email_unpaid_invoices_to_customers.php: send mail to " . $oldemail);
- $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_HEADER)) $usehtml+=1;
+ $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_HEADER))
+ $usehtml += 1;
- $allmessage='';
- if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER))
- {
- $allmessage.=$conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER;
- }
- else
- {
- $allmessage.= "Dear customer".($usehtml?" \n":"\n").($usehtml?" \n":"\n");
- $allmessage.= "Please, find a summary of the bills with pending payments from you.".($usehtml?" \n":"\n").($usehtml?" \n":"\n");
- $allmessage.= "Note: This list contains only unpaid invoices.".($usehtml?" \n":"\n");
- }
- $allmessage.= $message.($usehtml?" \n":"\n");
- $allmessage.= $langs->trans("Total")." = ".price($total, 0, $userlang, 0, 0, -1, $conf->currency).($usehtml?" \n":"\n");
- if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER))
- {
- $allmessage.=$conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER;
- if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER)) $usehtml+=1;
- }
+ $allmessage = '';
+ if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER)) {
+ $allmessage .= $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_HEADER;
+ } else {
+ $allmessage .= "Dear customer" . ($usehtml ? " \n" : "\n") . ($usehtml ? " \n" : "\n");
+ $allmessage .= "Please, find a summary of the bills with pending payments from you." . ($usehtml ? " \n" : "\n") . ($usehtml ? " \n" : "\n");
+ $allmessage .= "Note: This list contains only unpaid invoices." . ($usehtml ? " \n" : "\n");
+ }
+ $allmessage .= $message . ($usehtml ? " \n" : "\n");
+ $allmessage .= $langs->trans("Total") . " = " . price($total, 0, $userlang, 0, 0, - 1, $conf->currency) . ($usehtml ? " \n" : "\n");
+ if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_CUSTOMERS_FOOTER)) {
+ $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(
- $subject,
- $sendto,
- $from,
- $allmessage,
- array(),
- array(),
- array(),
- '',
- '',
- 0,
- $msgishtml
- );
+ $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
- $mail->errors_to = $errorsto;
+ $mail->errors_to = $errorsto;
- // Send or not email
- if ($mode == 'confirm')
- {
- $result=$mail->sendfile();
- if (! $result)
- {
- 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)");
- $mail->dump_mail();
- $result=1;
- }
+ // Send or not email
+ if ($mode == 'confirm') {
+ $result = $mail->sendfile();
+ if (! $result) {
+ 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)");
+ $mail->dump_mail();
+ $result = 1;
+ }
- unset($newlangs);
- if ($result)
- {
- return 1;
- }
- else
- {
- return -1;
- }
+ unset($newlangs);
+ if ($result) {
+ return 1;
+ } else {
+ return - 1;
+ }
}
diff --git a/scripts/invoices/email_unpaid_invoices_to_representatives.php b/scripts/invoices/email_unpaid_invoices_to_representatives.php
index 126ee5b8bd4..bf4264d57ba 100755
--- a/scripts/invoices/email_unpaid_invoices_to_representatives.php
+++ b/scripts/invoices/email_unpaid_invoices_to_representatives.php
@@ -1,9 +1,9 @@
#!/usr/bin/env php
- * Copyright (C) 2005-2013 Laurent Destailleur
- * Copyright (C) 2013 Juanjo Menent
+ * Copyright (C) 2005 Rodolphe Quiedeville
+ * Copyright (C) 2005-2013 Laurent Destailleur
+ * Copyright (C) 2013 Juanjo Menent
*
* 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
@@ -12,7 +12,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -20,260 +20,235 @@
*/
/**
- * \file scripts/invoices/email_unpaid_invoices_to_representatives.php
- * \ingroup facture
- * \brief Script to send a mail to dolibarr users linked to companies with unpaid invoices
+ * \file scripts/invoices/email_unpaid_invoices_to_representatives.php
+ * \ingroup facture
+ * \brief Script to send a mail to dolibarr users linked to companies with unpaid invoices
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test si mode batch
$sapi_type = php_sapi_name();
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";
- exit(-1);
+ 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);
}
-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 "\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 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_once DOL_DOCUMENT_ROOT."/core/class/CMailFile.class.php";
+require $path . "../../htdocs/master.inc.php";
+require_once DOL_DOCUMENT_ROOT . "/core/class/CMailFile.class.php";
$langs->load('main');
-
// Global variables
-$version=DOL_VERSION;
-$error=0;
-
-
+$version = DOL_VERSION;
+$error = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
-$now=dol_now('tzserver');
-$duration_value=isset($argv[2])?$argv[2]:'none';
+$now = dol_now('tzserver');
+$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.= " u.rowid as uid, u.lastname, u.firstname, u.email, u.lang";
-$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
-$sql .= " , ".MAIN_DB_PREFIX."societe as s";
-$sql .= " , ".MAIN_DB_PREFIX."societe_commerciaux as sc";
-$sql .= " , ".MAIN_DB_PREFIX."user as u";
+$sql .= " u.rowid as uid, u.lastname, u.firstname, u.email, u.lang";
+$sql .= " FROM " . MAIN_DB_PREFIX . "facture as f";
+$sql .= " , " . MAIN_DB_PREFIX . "societe as s";
+$sql .= " , " . MAIN_DB_PREFIX . "societe_commerciaux as sc";
+$sql .= " , " . MAIN_DB_PREFIX . "user as u";
$sql .= " WHERE f.fk_statut = 1 AND f.paye = 0";
$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_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;
-$resql=$db->query($sql);
-if ($resql)
-{
- $num = $db->num_rows($resql);
- $i = 0;
- $oldemail = 'none'; $olduid = 0; $oldlang='';
- $total = 0; $foundtoprocess = 0;
- 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='';
+// print $sql;
+$resql = $db->query($sql);
+if ($resql) {
+ $num = $db->num_rows($resql);
+ $i = 0;
+ $oldemail = 'none';
+ $olduid = 0;
+ $oldlang = '';
+ $total = 0;
+ $foundtoprocess = 0;
+ 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)
- {
- while ($i < $num)
- {
- $obj = $db->fetch_object($resql);
+ if ($num) {
+ while ($i < $num) {
+ $obj = $db->fetch_object($resql);
- if (($obj->email <> $oldemail || $obj->uid <> $olduid) || $oldemail == 'none')
- {
- // Break onto sales representative (new email or uid)
- if (dol_strlen($oldemail) && $oldemail != 'none')
- {
- envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative);
- }
- else
- {
- if ($oldemail != 'none') print "- No email sent for ".$oldsalerepresentative.", total: ".$total."\n";
- }
- $oldemail = $obj->email;
- $olduid = $obj->uid;
- $oldlang = $obj->lang;
- $oldsalerepresentative=dolGetFirstLastname($obj->firstname, $obj->lastname);
- $message = '';
- $total = 0;
- $foundtoprocess = 0;
- $salerepresentative=dolGetFirstLastname($obj->firstname, $obj->lastname);
- if (empty($obj->email)) print "Warning: Sale representative ".$salerepresentative." has no email. Notice disabled.\n";
- }
+ if (($obj->email != $oldemail || $obj->uid != $olduid) || $oldemail == 'none') {
+ // Break onto sales representative (new email or uid)
+ if (dol_strlen($oldemail) && $oldemail != 'none') {
+ envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative);
+ } else {
+ if ($oldemail != 'none')
+ print "- No email sent for " . $oldsalerepresentative . ", total: " . $total . "\n";
+ }
+ $oldemail = $obj->email;
+ $olduid = $obj->uid;
+ $oldlang = $obj->lang;
+ $oldsalerepresentative = dolGetFirstLastname($obj->firstname, $obj->lastname);
+ $message = '';
+ $total = 0;
+ $foundtoprocess = 0;
+ $salerepresentative = dolGetFirstLastname($obj->firstname, $obj->lastname);
+ if (empty($obj->email))
+ print "Warning: Sale representative " . $salerepresentative . " has no email. Notice disabled.\n";
+ }
- // Define line content
- $outputlangs=new Translate('', $conf);
- $outputlangs->setDefaultLang(empty($obj->lang)?$langs->defaultlang:$obj->lang); // By default language of sale representative
+ // Define line content
+ $outputlangs = new Translate('', $conf);
+ $outputlangs->setDefaultLang(empty($obj->lang) ? $langs->defaultlang : $obj->lang); // By default language of sale representative
- // Load translation files required by the page
- $outputlangs->loadLangs(array("main", "bills"));
+ // Load translation files required by the page
+ $outputlangs->loadLangs(array("main","bills"));
- 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";
- dol_syslog("email_unpaid_invoices_to_representatives.php: ".$obj->email);
- $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."): ";
- if (dol_strlen($obj->email)) print "qualified.";
- else print "disqualified (no 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";
+ dol_syslog("email_unpaid_invoices_to_representatives.php: " . $obj->email);
+ $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 . "): ";
+ if (dol_strlen($obj->email))
+ print "qualified.";
+ else
+ print "disqualified (no email).";
print "\n";
unset($outputlangs);
- $total += $obj->total_ttc;
- $i++;
- }
+ $total += $obj->total_ttc;
+ $i ++;
+ }
- // Si il reste des envois en buffer
- if ($foundtoprocess)
- {
- if (dol_strlen($oldemail) && $oldemail != 'none') // Break onto email (new email)
- {
- envoi_mail($mode, $oldemail, $message, $total, $oldlang, $oldsalerepresentative);
- }
- else
+ // Si il reste des envois en buffer
+ if ($foundtoprocess) {
+ if (dol_strlen($oldemail) && $oldemail != 'none') // Break onto email (new email)
{
- 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";
- }
+ 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";
+ }
- 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 $oldemail Old email
- * @param string $message Message to send
- * @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
+ * @param string $mode
+ * Mode (test | confirm)
+ * @param string $oldemail
+ * Old email
+ * @param string $message
+ * Message to send
+ * @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)
{
- 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->setDefaultLang(empty($userlang)?(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT):$userlang);
- $newlangs->load("main");
- $newlangs->load("bills");
+ $newlangs = new Translate('', $conf);
+ $newlangs->setDefaultLang(empty($userlang) ? (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT) : $userlang);
+ $newlangs->load("main");
+ $newlangs->load("bills");
- $subject = (empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_SUBJECT)?$newlangs->trans("ListOfYourUnpaidInvoices"):$conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_SUBJECT);
- $sendto = $oldemail;
- $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
- $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
- $msgishtml = -1;
+ $subject = (empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_SUBJECT) ? $newlangs->trans("ListOfYourUnpaidInvoices") : $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_SUBJECT);
+ $sendto = $oldemail;
+ $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
+ $errorsto = $conf->global->MAIN_MAIL_ERRORS_TO;
+ $msgishtml = - 1;
- print "- Send email for ".$oldsalerepresentative." (".$oldemail."), total: ".$total."\n";
- dol_syslog("email_unpaid_invoices_to_representatives.php: send mail to ".$oldemail);
+ print "- Send email for " . $oldsalerepresentative . " (" . $oldemail . "), total: " . $total . "\n";
+ dol_syslog("email_unpaid_invoices_to_representatives.php: send mail to " . $oldemail);
- $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_HEADER)) $usehtml+=1;
+ $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_HEADER))
+ $usehtml += 1;
- $allmessage='';
- if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER))
- {
- $allmessage.=$conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER;
- }
- else
- {
- $allmessage.= $newlangs->transnoentities("ListOfYourUnpaidInvoices").($usehtml?" \n":"\n").($usehtml?" \n":"\n");
- $allmessage.= $newlangs->transnoentities("NoteListOfYourUnpaidInvoices").($usehtml?" \n":"\n");
- }
- $allmessage.= $message.($usehtml?" \n":"\n");
- $allmessage.= $langs->trans("Total")." = ".price($total, 0, $newlangs, 0, 0, -1, $conf->currency).($usehtml?" \n":"\n");
- if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER))
- {
- $allmessage.=$conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER;
- if (dol_textishtml($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER)) $usehtml+=1;
- }
+ $allmessage = '';
+ if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER)) {
+ $allmessage .= $conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_HEADER;
+ } else {
+ $allmessage .= $newlangs->transnoentities("ListOfYourUnpaidInvoices") . ($usehtml ? " \n" : "\n") . ($usehtml ? " \n" : "\n");
+ $allmessage .= $newlangs->transnoentities("NoteListOfYourUnpaidInvoices") . ($usehtml ? " \n" : "\n");
+ }
+ $allmessage .= $message . ($usehtml ? " \n" : "\n");
+ $allmessage .= $langs->trans("Total") . " = " . price($total, 0, $newlangs, 0, 0, - 1, $conf->currency) . ($usehtml ? " \n" : "\n");
+ if (! empty($conf->global->SCRIPT_EMAIL_UNPAID_INVOICES_SALESREPRESENTATIVES_FOOTER)) {
+ $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(
- $subject,
- $sendto,
- $from,
- $allmessage,
- array(),
- array(),
- array(),
- '',
- '',
- 0,
- $msgishtml
- );
+ $mail = new CMailFile($subject, $sendto, $from, $allmessage, array(), array(), array(), '', '', 0, $msgishtml);
- $mail->errors_to = $errorsto;
+ $mail->errors_to = $errorsto;
- // Send or not email
- if ($mode == 'confirm')
- {
- $result=$mail->sendfile();
- if (! $result)
- {
- 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)");
- $mail->dump_mail();
- $result=1;
- }
+ // Send or not email
+ if ($mode == 'confirm') {
+ $result = $mail->sendfile();
+ if (! $result) {
+ 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)");
+ $mail->dump_mail();
+ $result = 1;
+ }
- if ($result)
- {
- return 1;
- }
- else
- {
- return -1;
- }
+ if ($result) {
+ return 1;
+ } else {
+ return - 1;
+ }
}
diff --git a/scripts/invoices/rebuild_merge_pdf.php b/scripts/invoices/rebuild_merge_pdf.php
index 62865570b28..f90f4a615c9 100755
--- a/scripts/invoices/rebuild_merge_pdf.php
+++ b/scripts/invoices/rebuild_merge_pdf.php
@@ -1,7 +1,7 @@
#!/usr/bin/env php
+ * Copyright (C) 2009-2012 Laurent Destailleur
*
* 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
@@ -10,7 +10,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -18,251 +18,217 @@
*/
/**
- * \file scripts/invoices/rebuild_merge_pdf.php
- * \ingroup facture
- * \brief Script to rebuild PDF and merge PDF files into one
+ * \file scripts/invoices/rebuild_merge_pdf.php
+ * \ingroup facture
+ * \brief Script to rebuild PDF and merge PDF files into one
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test if batch mode
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";
- exit(-1);
+ 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);
}
// 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.
-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/lib/date.lib.php";
-require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice2.lib.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/lib/date.lib.php";
+require_once DOL_DOCUMENT_ROOT . '/core/lib/invoice2.lib.php';
// Load main language strings
$langs->load("main");
// Global variables
-$version=DOL_VERSION;
-$error=0;
-
-
+$version = DOL_VERSION;
+$error = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
// Check parameters
-if (! isset($argv[1]))
-{
+if (! isset($argv[1])) {
usage();
- exit(-1);
+ exit(- 1);
}
-$diroutputpdf=$conf->facture->dir_output . '/temp';
-$newlangid='en_EN'; // To force a new lang id
-$filter=array();
-$regenerate=''; // Ask regenerate (contains name of model to use)
-$option='';
-$fileprefix='mergedpdf';
+$diroutputpdf = $conf->facture->dir_output . '/temp';
+$newlangid = 'en_EN'; // To force a new lang id
+$filter = array();
+$regenerate = ''; // Ask regenerate (contains name of model to use)
+$option = '';
+$fileprefix = 'mergedpdf';
-foreach ($argv as $key => $value)
-{
- $found=false;
+foreach ($argv as $key => $value) {
+ $found = false;
// Define options
- if (preg_match('/^lang=/i', $value))
- {
- $found=true;
- $valarray=explode('=', $value);
- $newlangid=$valarray[1];
- print 'Use language '.$newlangid.".\n";
+ if (preg_match('/^lang=/i', $value)) {
+ $found = true;
+ $valarray = explode('=', $value);
+ $newlangid = $valarray[1];
+ print 'Use language ' . $newlangid . ".\n";
}
- if (preg_match('/^prefix=/i', $value))
- {
- $found=true;
- $valarray=explode('=', $value);
- $fileprefix=$valarray[1];
- print 'Use prefix for filename '.$fileprefix.".\n";
+ if (preg_match('/^prefix=/i', $value)) {
+ $found = true;
+ $valarray = explode('=', $value);
+ $fileprefix = $valarray[1];
+ print 'Use prefix for filename ' . $fileprefix . ".\n";
}
- if (preg_match('/^regenerate=(.*)/i', $value, $reg))
- {
- if (! in_array($reg[1], array('','0','no')))
- {
- $found=true;
- $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);
+ if (preg_match('/^regenerate=(.*)/i', $value, $reg)) {
+ if (! in_array($reg[1], array('','0','no'))) {
+ $found = true;
+ $regenerate = $reg[1];
+ print 'Regeneration of PDF is requested with template ' . $regenerate . "\n";
}
- 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')
- {
- $found=true;
- $option.=(empty($option)?'':'_').'nopayment';
- $filter[]='nopayment';
+ if ($value == 'filter=all') {
+ $found = true;
+ $option .= (empty($option) ? '' : '_') . 'all';
+ $filter[] = 'all';
- print 'Rebuild PDF for invoices with no payment done yet.'."\n";
+ print 'Rebuild PDF for all invoices' . "\n";
}
- if ($value == 'filter=bank')
- {
- $found=true;
- $option.=(empty($option)?'':'_').'bank_'.$argv[$key+1];
- $filter[]='bank';
+ if ($value == 'filter=date') {
+ $found = true;
+ $option .= (empty($option) ? '' : '_') . 'date_' . $argv[$key + 1] . '_' . $argv[$key + 2];
+ $filter[] = 'date';
- $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);
+ $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);
}
- $paymentonbankid=$bankaccount->id;
- print 'Rebuild PDF for invoices with at least one payment on financial account '.$bankaccount->ref."\n";
+ 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=nodeposit')
- {
- $found=true;
- $option.=(empty($option)?'':'_').'nodeposit';
- $filter[]='nodeposit';
+ if ($value == 'filter=nopayment') {
+ $found = true;
+ $option .= (empty($option) ? '' : '_') . 'nopayment';
+ $filter[] = 'nopayment';
- print 'Exclude deposit invoices'."\n";
- }
- if ($value == 'filter=noreplacement')
- {
- $found=true;
- $option.=(empty($option)?'':'_').'noreplacement';
- $filter[]='noreplacement';
+ print 'Rebuild PDF for invoices with no payment done yet.' . "\n";
+ }
- print 'Exclude replacement invoices'."\n";
- }
- if ($value == 'filter=nocreditnote')
- {
- $found=true;
- $option.=(empty($option)?'':'_').'nocreditnote';
- $filter[]='nocreditnote';
+ if ($value == 'filter=bank') {
+ $found = true;
+ $option .= (empty($option) ? '' : '_') . 'bank_' . $argv[$key + 1];
+ $filter[] = 'bank';
- 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')
- {
- $found=true;
- $filter[]='excludethirdparties';
+ if ($value == 'filter=nodeposit') {
+ $found = true;
+ $option .= (empty($option) ? '' : '_') . 'nodeposit';
+ $filter[] = 'nodeposit';
- $thirdpartiesid=explode(',', $argv[$key+1]);
- print 'Exclude thirdparties with id in list ('.join(',', $thirdpartiesid).").\n";
+ print 'Exclude deposit invoices' . "\n";
+ }
+ if ($value == 'filter=noreplacement') {
+ $found = true;
+ $option .= (empty($option) ? '' : '_') . 'noreplacement';
+ $filter[] = 'noreplacement';
- $option.=(empty($option)?'':'_').'excludethirdparties'.join('-', $thirdpartiesid);
- }
- if ($value == 'filter=onlythirdparties')
- {
- $found=true;
- $filter[]='onlythirdparties';
+ print 'Exclude replacement invoices' . "\n";
+ }
+ if ($value == 'filter=nocreditnote') {
+ $found = true;
+ $option .= (empty($option) ? '' : '_') . 'nocreditnote';
+ $filter[] = 'nocreditnote';
- $thirdpartiesid=explode(',', $argv[$key+1]);
- print 'Only thirdparties with id in list ('.join(',', $thirdpartiesid).").\n";
+ print 'Exclude credit note invoices' . "\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();
- exit(-1);
+ exit(- 1);
}
}
// Check if an option and a filter has been provided
-if (empty($option) && count($filter) <= 0)
-{
+if (empty($option) && count($filter) <= 0) {
usage();
- exit(-1);
+ exit(- 1);
}
// 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();
- exit(-1);
+ exit(- 1);
}
-if (in_array('bank', $filter) && in_array('nopayment', $filter))
-{
+if (in_array('bank', $filter) && in_array('nopayment', $filter)) {
usage();
- exit(-1);
+ exit(- 1);
}
-
// Define SQL and SQL request to select invoices
// 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 --------------------
-if ($result >= 0)
-{
- $error=0;
- print '--- end ok'."\n";
-}
-else
-{
- $error=$result;
- print '--- end error code='.$error."\n";
+if ($result >= 0) {
+ $error = 0;
+ print '--- end ok' . "\n";
+} else {
+ $error = $result;
+ print '--- end error code=' . $error . "\n";
}
$db->close();
exit($error);
-
-
/**
* Show usage of script
*
@@ -272,29 +238,29 @@ function usage()
{
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 "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 "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 "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 "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 "Usage: ".$script_file." filter=nopayment\n";
- print "To exclude credit notes, use filter=nocreditnote\n";
- print "To exclude replacement invoices, use filter=noreplacement\n";
- print "To exclude deposit invoices, use filter=nodeposit\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 regenerate existing PDF, use regenerate=templatename\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 "\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 "Usage: " . $script_file . " filter=nopayment\n";
+ print "To exclude credit notes, use filter=nocreditnote\n";
+ print "To exclude replacement invoices, use filter=noreplacement\n";
+ print "To exclude deposit invoices, use filter=nodeposit\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 regenerate existing PDF, use regenerate=templatename\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 "\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 "\n";
print "Note that some filters can be cumulated.\n";
}
diff --git a/scripts/members/sync_members_dolibarr2ldap.php b/scripts/members/sync_members_dolibarr2ldap.php
index 598098e240a..82d9a68a1b1 100755
--- a/scripts/members/sync_members_dolibarr2ldap.php
+++ b/scripts/members/sync_members_dolibarr2ldap.php
@@ -1,8 +1,8 @@
#!/usr/bin/env php
- * Copyright (C) 2006-2008 Laurent Destailleur
+ * Copyright (C) 2005 Rodolphe Quiedeville
+ * Copyright (C) 2006-2008 Laurent Destailleur
*
* 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
@@ -11,7 +11,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -19,74 +19,71 @@
*/
/**
- * \file scripts/members/sync_members_dolibarr2ldap.php
- * \ingroup ldap member
- * \brief Script de mise a jour des adherents dans LDAP depuis base Dolibarr
+ * \file scripts/members/sync_members_dolibarr2ldap.php
+ * \ingroup ldap member
+ * \brief Script de mise a jour des adherents dans LDAP depuis base Dolibarr
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test if batch mode
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";
- exit(-1);
+ 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);
}
-require_once $path."../../htdocs/master.inc.php";
-require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php";
-require_once DOL_DOCUMENT_ROOT."/adherents/class/adherent.class.php";
+require_once $path . "../../htdocs/master.inc.php";
+require_once DOL_DOCUMENT_ROOT . "/core/class/ldap.class.php";
+require_once DOL_DOCUMENT_ROOT . "/adherents/class/adherent.class.php";
$langs->load("main");
// Global variables
-$version=DOL_VERSION;
-$error=0;
-$confirmed=0;
-
+$version = DOL_VERSION;
+$error = 0;
+$confirmed = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
if (! isset($argv[1]) || ! $argv[1]) {
- print "Usage: $script_file now [-y]\n";
- exit(-1);
+ print "Usage: $script_file now [-y]\n";
+ exit(- 1);
}
-foreach($argv as $key => $val)
-{
- if (preg_match('/-y$/', $val, $reg)) $confirmed=1;
+foreach ($argv as $key => $val) {
+ if (preg_match('/-y$/', $val, $reg))
+ $confirmed = 1;
}
-$now=$argv[1];
+$now = $argv[1];
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 "----- Synchronize all records from Dolibarr database:\n";
-print "type=".$conf->db->type."\n";
-print "host=".$conf->db->host."\n";
-print "port=".$conf->db->port."\n";
-print "login=".$conf->db->user."\n";
-//print "pass=".preg_replace('/./i','*',$conf->db->password)."\n"; // Not defined for security reasons
-print "database=".$conf->db->name."\n";
+print "type=" . $conf->db->type . "\n";
+print "host=" . $conf->db->host . "\n";
+print "port=" . $conf->db->port . "\n";
+print "login=" . $conf->db->user . "\n";
+// print "pass=".preg_replace('/./i','*',$conf->db->password)."\n"; // Not defined for security reasons
+print "database=" . $conf->db->name . "\n";
print "\n";
print "----- To LDAP database:\n";
-print "host=".$conf->global->LDAP_SERVER_HOST."\n";
-print "port=".$conf->global->LDAP_SERVER_PORT."\n";
-print "login=".$conf->global->LDAP_ADMIN_DN."\n";
-print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n";
-print "DN target=".$conf->global->LDAP_MEMBER_DN."\n";
+print "host=" . $conf->global->LDAP_SERVER_HOST . "\n";
+print "port=" . $conf->global->LDAP_SERVER_PORT . "\n";
+print "login=" . $conf->global->LDAP_ADMIN_DN . "\n";
+print "pass=" . preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS) . "\n";
+print "DN target=" . $conf->global->LDAP_MEMBER_DN . "\n";
print "\n";
-if (! $confirmed)
-{
+if (! $confirmed) {
print "Press a key to confirm...\n";
$input = trim(fgets(STDIN));
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)
-{
- print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
- exit(-1);
-}
-*/
+ * if (! $conf->global->LDAP_MEMBER_ACTIVE)
+ * {
+ * print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
+ * exit(-1);
+ * }
+ */
$sql = "SELECT rowid";
-$sql .= " FROM ".MAIN_DB_PREFIX."adherent";
+$sql .= " FROM " . MAIN_DB_PREFIX . "adherent";
$resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
$num = $db->num_rows($resql);
$i = 0;
- $ldap=new Ldap();
+ $ldap = new Ldap();
$ldap->connect_bind();
- while ($i < $num)
- {
- $ldap->error="";
+ while ($i < $num) {
+ $ldap->error = "";
$obj = $db->fetch_object($resql);
$member = new Adherent($db);
- $result=$member->fetch($obj->rowid);
- if ($result < 0)
- {
+ $result = $member->fetch($obj->rowid);
+ if ($result < 0) {
dol_print_error($db, $member->error);
- exit(-1);
+ exit(- 1);
}
- $result=$member->fetch_subscriptions();
- if ($result < 0)
- {
+ $result = $member->fetch_subscriptions();
+ if ($result < 0) {
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();
- $olddn=$oldobject->_load_ldap_dn($oldinfo);
+ $oldinfo = $oldobject->_load_ldap_info();
+ $olddn = $oldobject->_load_ldap_dn($oldinfo);
- $info=$member->_load_ldap_info();
- $dn=$member->_load_ldap_dn($info);
+ $info = $member->_load_ldap_info();
+ $dn = $member->_load_ldap_dn($info);
- $result=$ldap->add($dn, $info, $user); // Wil fail if already exists
- $result=$ldap->update($dn, $info, $user, $olddn);
- if ($result > 0)
- {
- print " - ".$langs->transnoentities("OK");
- }
- else
- {
- $error++;
- print " - ".$langs->transnoentities("KO").' - '.$ldap->error;
+ $result = $ldap->add($dn, $info, $user); // Wil fail if already exists
+ $result = $ldap->update($dn, $info, $user, $olddn);
+ if ($result > 0) {
+ print " - " . $langs->transnoentities("OK");
+ } else {
+ $error ++;
+ print " - " . $langs->transnoentities("KO") . ' - ' . $ldap->error;
}
print "\n";
- $i++;
+ $i ++;
}
$ldap->unbind();
$ldap->close();
-}
-else
-{
+} else {
dol_print_error($db);
}
diff --git a/scripts/members/sync_members_ldap2dolibarr.php b/scripts/members/sync_members_ldap2dolibarr.php
index 2a9036ca0b2..3a7aee9c5df 100755
--- a/scripts/members/sync_members_ldap2dolibarr.php
+++ b/scripts/members/sync_members_ldap2dolibarr.php
@@ -1,8 +1,8 @@
#!/usr/bin/env php
- * Copyright (C) 2006-2015 Laurent Destailleur
+ * Copyright (C) 2005 Rodolphe Quiedeville
+ * Copyright (C) 2006-2015 Laurent Destailleur
*
* 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
@@ -11,7 +11,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -19,322 +19,265 @@
*/
/**
- * \file scripts/members/sync_members_ldap2dolibarr.php
- * \ingroup ldap member
- * \brief Script de mise a jour des adherents dans Dolibarr depuis LDAP
+ * \file scripts/members/sync_members_ldap2dolibarr.php
+ * \ingroup ldap member
+ * \brief Script de mise a jour des adherents dans Dolibarr depuis LDAP
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test if batch mode
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";
- exit(-1);
+ 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);
}
-require_once $path."../../htdocs/master.inc.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."/adherents/class/adherent.class.php";
-require_once DOL_DOCUMENT_ROOT."/adherents/class/subscription.class.php";
+require_once $path . "../../htdocs/master.inc.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 . "/adherents/class/adherent.class.php";
+require_once DOL_DOCUMENT_ROOT . "/adherents/class/subscription.class.php";
-$langs->loadLangs(array("main", "errors"));
+$langs->loadLangs(array("main","errors"));
// Global variables
-$version=DOL_VERSION;
-$error=0;
-$forcecommit=0;
-$confirmed=0;
-
+$version = DOL_VERSION;
+$error = 0;
+$forcecommit = 0;
+$confirmed = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
// List of fields to get from LDAP
-$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,
+$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,
// Subscriptions
- $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_DATE,$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
-$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])) {
- print "Usage: $script_file (nocommitiferror|commitiferror) id_member_type [--server=ldapserverhost] [-y]\n";
- exit(-1);
+ print "Usage: $script_file (nocommitiferror|commitiferror) id_member_type [--server=ldapserverhost] [-y]\n";
+ exit(- 1);
}
-$typeid=$argv[2];
-foreach($argv as $key => $val)
-{
- if ($val == 'commitiferror') $forcecommit=1;
- if (preg_match('/--server=([^\s]+)$/', $val, $reg)) $conf->global->LDAP_SERVER_HOST=$reg[1];
- if (preg_match('/-y$/', $val, $reg)) $confirmed=1;
+$typeid = $argv[2];
+foreach ($argv as $key => $val) {
+ if ($val == 'commitiferror')
+ $forcecommit = 1;
+ if (preg_match('/--server=([^\s]+)$/', $val, $reg))
+ $conf->global->LDAP_SERVER_HOST = $reg[1];
+ if (preg_match('/-y$/', $val, $reg))
+ $confirmed = 1;
}
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 "----- Synchronize all records from LDAP database:\n";
-print "host=".$conf->global->LDAP_SERVER_HOST."\n";
-print "port=".$conf->global->LDAP_SERVER_PORT."\n";
-print "login=".$conf->global->LDAP_ADMIN_DN."\n";
-print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\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
-else print 'Filter=('.$conf->global->LDAP_KEY_MEMBERS.'=*)'."\n";
+print "host=" . $conf->global->LDAP_SERVER_HOST . "\n";
+print "port=" . $conf->global->LDAP_SERVER_PORT . "\n";
+print "login=" . $conf->global->LDAP_ADMIN_DN . "\n";
+print "pass=" . preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS) . "\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
+else
+ print 'Filter=(' . $conf->global->LDAP_KEY_MEMBERS . '=*)' . "\n";
print "----- To Dolibarr database:\n";
-print "type=".$conf->db->type."\n";
-print "host=".$conf->db->host."\n";
-print "port=".$conf->db->port."\n";
-print "login=".$conf->db->user."\n";
-print "database=".$conf->db->name."\n";
+print "type=" . $conf->db->type . "\n";
+print "host=" . $conf->db->host . "\n";
+print "port=" . $conf->db->port . "\n";
+print "login=" . $conf->db->user . "\n";
+print "database=" . $conf->db->name . "\n";
print "----- Options:\n";
-print "commitiferror=".$forcecommit."\n";
-print "Mapped LDAP fields=".join(',', $required_fields)."\n";
+print "commitiferror=" . $forcecommit . "\n";
+print "Mapped LDAP fields=" . join(',', $required_fields) . "\n";
print "\n";
// Check parameters
-if (empty($conf->global->LDAP_MEMBER_DN))
-{
- print $langs->trans("Error").': '.$langs->trans("LDAP setup for members not defined inside Dolibarr")."\n";
- exit(-1);
+if (empty($conf->global->LDAP_MEMBER_DN)) {
+ print $langs->trans("Error") . ': ' . $langs->trans("LDAP setup for members not defined inside Dolibarr") . "\n";
+ exit(- 1);
}
-if ($typeid <= 0)
-{
- print $langs->trans("Error").': Parameter id_member_type is not a valid ref of an existing member type'."\n";
- exit(-2);
+if ($typeid <= 0) {
+ print $langs->trans("Error") . ': Parameter id_member_type is not a valid ref of an existing member type' . "\n";
+ exit(- 2);
}
-
-if (! $confirmed)
-{
+if (! $confirmed) {
print "Hit Enter to continue or CTRL+C to stop...\n";
$input = trim(fgets(STDIN));
}
// Load table of correspondence of countries
-$hashlib2rowid=array();
-$countries=array();
+$hashlib2rowid = array();
+$countries = array();
$sql = "SELECT rowid, code, label, active";
-$sql.= " FROM ".MAIN_DB_PREFIX."c_country";
-$sql.= " WHERE active = 1";
-$sql.= " ORDER BY code ASC";
-$resql=$db->query($sql);
-if ($resql)
-{
+$sql .= " FROM " . MAIN_DB_PREFIX . "c_country";
+$sql .= " WHERE active = 1";
+$sql .= " ORDER BY code ASC";
+$resql = $db->query($sql);
+if ($resql) {
$num = $db->num_rows($resql);
$i = 0;
- if ($num)
- {
- while ($i < $num)
- {
+ if ($num) {
+ while ($i < $num) {
$obj = $db->fetch_object($resql);
- if ($obj)
- {
- //print 'Load cache for country '.strtolower($obj->label).' rowid='.$obj->rowid."\n";
- $hashlib2rowid[strtolower($obj->label)]=$obj->rowid;
- $countries[$obj->rowid]=array('rowid' => $obj->rowid, 'label' => $obj->label, 'code' => $obj->code);
+ if ($obj) {
+ // print 'Load cache for country '.strtolower($obj->label).' rowid='.$obj->rowid."\n";
+ $hashlib2rowid[strtolower($obj->label)] = $obj->rowid;
+ $countries[$obj->rowid] = array('rowid' => $obj->rowid,'label' => $obj->label,'code' => $obj->code);
}
- $i++;
+ $i ++;
}
}
-}
-else
-{
+} else {
dol_print_error($db);
- exit(-1);
+ exit(- 1);
}
-
-
$ldap = new Ldap();
$result = $ldap->connect_bind();
-if ($result >= 0)
-{
- $justthese=array();
-
+if ($result >= 0) {
+ $justthese = array();
// 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
- if (is_array($ldaprecords))
- {
+ $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)) {
$db->begin();
// Warning $ldapuser has a key in lowercase
- foreach ($ldaprecords as $key => $ldapuser)
- {
+ foreach ($ldaprecords as $key => $ldapuser) {
$member = new Adherent($db);
// Propriete membre
- $member->firstname=$ldapuser[$conf->global->LDAP_FIELD_FIRSTNAME];
- $member->lastname=$ldapuser[$conf->global->LDAP_FIELD_NAME];
- $member->login=$ldapuser[$conf->global->LDAP_FIELD_LOGIN];
- $member->pass=$ldapuser[$conf->global->LDAP_FIELD_PASSWORD];
+ $member->firstname = $ldapuser[$conf->global->LDAP_FIELD_FIRSTNAME];
+ $member->lastname = $ldapuser[$conf->global->LDAP_FIELD_NAME];
+ $member->login = $ldapuser[$conf->global->LDAP_FIELD_LOGIN];
+ $member->pass = $ldapuser[$conf->global->LDAP_FIELD_PASSWORD];
- //$member->societe;
- $member->address=$ldapuser[$conf->global->LDAP_FIELD_ADDRESS];
- $member->zip=$ldapuser[$conf->global->LDAP_FIELD_ZIP];
- $member->town=$ldapuser[$conf->global->LDAP_FIELD_TOWN];
- $member->country=$ldapuser[$conf->global->LDAP_FIELD_COUNTRY];
- $member->country_id=$countries[$hashlib2rowid[strtolower($member->country)]]['rowid'];
- $member->country_code=$countries[$hashlib2rowid[strtolower($member->country)]]['code'];
+ // $member->societe;
+ $member->address = $ldapuser[$conf->global->LDAP_FIELD_ADDRESS];
+ $member->zip = $ldapuser[$conf->global->LDAP_FIELD_ZIP];
+ $member->town = $ldapuser[$conf->global->LDAP_FIELD_TOWN];
+ $member->country = $ldapuser[$conf->global->LDAP_FIELD_COUNTRY];
+ $member->country_id = $countries[$hashlib2rowid[strtolower($member->country)]]['rowid'];
+ $member->country_code = $countries[$hashlib2rowid[strtolower($member->country)]]['code'];
- $member->phone=$ldapuser[$conf->global->LDAP_FIELD_PHONE];
- $member->phone_perso=$ldapuser[$conf->global->LDAP_FIELD_PHONE_PERSO];
- $member->phone_mobile=$ldapuser[$conf->global->LDAP_FIELD_MOBILE];
- $member->email=$ldapuser[$conf->global->LDAP_FIELD_MAIL];
+ $member->phone = $ldapuser[$conf->global->LDAP_FIELD_PHONE];
+ $member->phone_perso = $ldapuser[$conf->global->LDAP_FIELD_PHONE_PERSO];
+ $member->phone_mobile = $ldapuser[$conf->global->LDAP_FIELD_MOBILE];
+ $member->email = $ldapuser[$conf->global->LDAP_FIELD_MAIL];
- $member->note=$ldapuser[$conf->global->LDAP_FIELD_DESCRIPTION];
- $member->morphy='phy';
- $member->photo='';
- $member->public=1;
- $member->birth=dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_BIRTHDATE]);
+ $member->note = $ldapuser[$conf->global->LDAP_FIELD_DESCRIPTION];
+ $member->morphy = 'phy';
+ $member->photo = '';
+ $member->public = 1;
+ $member->birth = dol_stringtotime($ldapuser[$conf->global->LDAP_FIELD_BIRTHDATE]);
- $member->statut=-1;
- if (isset($ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS]))
- {
- $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->statut=$ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS];
+ $member->statut = - 1;
+ if (isset($ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS])) {
+ $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->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
- $member->typeid=$typeid;
+ $member->typeid = $typeid;
// Creation membre
- print $langs->transnoentities("MemberCreate").' # '.$key.': login='.$member->login.', fullname='.$member->getFullName($langs);
- print ', datec='.$member->datec;
- $member_id=$member->create($user);
- if ($member_id > 0)
- {
- print ' --> Created member id='.$member_id.' login='.$member->login;
- }
- else
- {
- $error++;
- print ' --> '.$member->error;
+ print $langs->transnoentities("MemberCreate") . ' # ' . $key . ': login=' . $member->login . ', fullname=' . $member->getFullName($langs);
+ print ', datec=' . $member->datec;
+ $member_id = $member->create($user);
+ if ($member_id > 0) {
+ print ' --> Created member id=' . $member_id . ' login=' . $member->login;
+ } else {
+ $error ++;
+ print ' --> ' . $member->error;
}
print "\n";
- //print_r($member);
+ // print_r($member);
- $datefirst='';
- if ($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]);
+ $datefirst = '';
+ if ($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]);
}
- $datelast='';
- if ($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]);
- }
- 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;
- $pricelast=price2num($ldapuser[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT]);
+ $datelast = '';
+ if ($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]);
+ } 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;
+ $pricelast = price2num($ldapuser[$conf->global->LDAP_FIELD_MEMBER_LASTSUBSCRIPTION_AMOUNT]);
// Cas special ou date derniere <= date premiere
- if ($datefirst && $datelast && $datelast <= $datefirst)
- {
+ if ($datefirst && $datelast && $datelast <= $datefirst) {
// On ne va inserer que la premiere
- $datelast=0;
- if (! $pricefirst && $pricelast) $pricefirst = $pricelast;
+ $datelast = 0;
+ if (! $pricefirst && $pricelast)
+ $pricefirst = $pricelast;
}
}
-
// Insert first subscription
- if ($datefirst)
- {
+ if ($datefirst) {
// Cree premiere cotisation et met a jour datefin dans adherent
- //print "xx".$datefirst."\n";
- $crowid=$member->subscription($datefirst, $pricefirst, 0);
+ // print "xx".$datefirst."\n";
+ $crowid = $member->subscription($datefirst, $pricefirst, 0);
}
// Insert last subscription
- if ($datelast)
- {
+ if ($datelast) {
// Cree derniere cotisation et met a jour datefin dans adherent
- //print "yy".dol_print_date($datelast)."\n";
- $crowid=$member->subscription($datelast, $pricelast, 0);
+ // print "yy".dol_print_date($datelast)."\n";
+ $crowid = $member->subscription($datelast, $pricelast, 0);
}
}
- if (! $error || $forcecommit)
- {
- if (! $error) print $langs->transnoentities("NoErrorCommitIsDone")."\n";
- else print $langs->transnoentities("ErrorButCommitIsDone")."\n";
+ if (! $error || $forcecommit) {
+ if (! $error)
+ print $langs->transnoentities("NoErrorCommitIsDone") . "\n";
+ else
+ print $langs->transnoentities("ErrorButCommitIsDone") . "\n";
$db->commit();
- }
- else
- {
- print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
+ } else {
+ print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error) . "\n";
$db->rollback();
}
print "\n";
- }
- else
- {
+ } else {
dol_print_error('', $ldap->error);
- $error++;
+ $error ++;
}
-}
-else
-{
+} else {
dol_print_error('', $ldap->error);
- $error++;
+ $error ++;
}
-
exit($error);
-
/**
* Function to say if a value is empty or not
*
- * @param string $element Value to test
- * @return boolean True of false
+ * @param string $element
+ * Value to test
+ * @return boolean True of false
*/
function dolValidElement($element)
{
diff --git a/scripts/members/sync_members_types_dolibarr2ldap.php b/scripts/members/sync_members_types_dolibarr2ldap.php
index 0c0da924f98..a5e2f5ace94 100755
--- a/scripts/members/sync_members_types_dolibarr2ldap.php
+++ b/scripts/members/sync_members_types_dolibarr2ldap.php
@@ -1,9 +1,9 @@
#!/usr/bin/env php
- * Copyright (C) 2006 Laurent Destailleur
- * Copyright (C) 2017 Regis Houssin
+ * Copyright (C) 2005 Rodolphe Quiedeville
+ * Copyright (C) 2006 Laurent Destailleur
+ * Copyright (C) 2017 Regis Houssin
*
* 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
@@ -12,7 +12,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -20,69 +20,64 @@
*/
/**
- * \file scripts/user/sync_members_types_dolibarr2ldap.php
- * \ingroup ldap core
- * \brief Script de mise a jour des types de membres dans LDAP depuis base Dolibarr
+ * \file scripts/user/sync_members_types_dolibarr2ldap.php
+ * \ingroup ldap core
+ * \brief Script de mise a jour des types de membres dans LDAP depuis base Dolibarr
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test if batch mode
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";
- exit(-1);
+ 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);
}
if (! isset($argv[1]) || ! $argv[1]) {
- print "Usage: ".$script_file." now\n";
- exit(-1);
+ print "Usage: " . $script_file . " now\n";
+ exit(- 1);
}
-$now=$argv[1];
+$now = $argv[1];
-require_once $path."../../htdocs/master.inc.php";
-require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php";
-require_once DOL_DOCUMENT_ROOT."/adherents/class/adherent_type.class.php";
+require_once $path . "../../htdocs/master.inc.php";
+require_once DOL_DOCUMENT_ROOT . "/core/class/ldap.class.php";
+require_once DOL_DOCUMENT_ROOT . "/adherents/class/adherent_type.class.php";
// Global variables
-$version=DOL_VERSION;
-$error=0;
-
+$version = DOL_VERSION;
+$error = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
/*
-if (! $conf->global->LDAP_SYNCHRO_ACTIVE)
-{
- print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
- exit(-1);
-}
-*/
+ * if (! $conf->global->LDAP_SYNCHRO_ACTIVE)
+ * {
+ * print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
+ * exit(-1);
+ * }
+ */
$sql = "SELECT rowid";
-$sql .= " FROM ".MAIN_DB_PREFIX."adherent_type";
+$sql .= " FROM " . MAIN_DB_PREFIX . "adherent_type";
$resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
$num = $db->num_rows($resql);
$i = 0;
- $ldap=new Ldap();
- $result=$ldap->connect_bind();
+ $ldap = new Ldap();
+ $result = $ldap->connect_bind();
- if ($result > 0)
- {
- while ($i < $num)
- {
- $ldap->error="";
+ if ($result > 0) {
+ while ($i < $num) {
+ $ldap->error = "";
$obj = $db->fetch_object($resql);
@@ -90,41 +85,35 @@ if ($resql)
$membertype->id = $obj->rowid;
$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();
- $olddn=$membertype->_load_ldap_dn($oldinfo);
+ $oldinfo = $membertype->_load_ldap_info();
+ $olddn = $membertype->_load_ldap_dn($oldinfo);
- $info=$membertype->_load_ldap_info();
- $dn=$membertype->_load_ldap_dn($info);
+ $info = $membertype->_load_ldap_info();
+ $dn = $membertype->_load_ldap_dn($info);
- $result=$ldap->add($dn, $info, $user); // Wil fail if already exists
- $result=$ldap->update($dn, $info, $user, $olddn);
- if ($result > 0)
- {
- print " - ".$langs->trans("OK");
- }
- else
- {
- $error++;
- print " - ".$langs->trans("KO").' - '.$ldap->error;
+ $result = $ldap->add($dn, $info, $user); // Wil fail if already exists
+ $result = $ldap->update($dn, $info, $user, $olddn);
+ if ($result > 0) {
+ print " - " . $langs->trans("OK");
+ } else {
+ $error ++;
+ print " - " . $langs->trans("KO") . ' - ' . $ldap->error;
}
print "\n";
- $i++;
+ $i ++;
}
$ldap->unbind();
$ldap->close();
- }
- else {
+ } else {
print $ldap->error;
}
-}
-else
-{
+} else {
dol_print_error($db);
}
diff --git a/scripts/members/sync_members_types_ldap2dolibarr.php b/scripts/members/sync_members_types_ldap2dolibarr.php
index 3ce15cab13a..fe9a07e14da 100755
--- a/scripts/members/sync_members_types_ldap2dolibarr.php
+++ b/scripts/members/sync_members_types_ldap2dolibarr.php
@@ -1,10 +1,10 @@
#!/usr/bin/env php
- * Copyright (C) 2006-2012 Laurent Destailleur
- * Copyright (C) 2013 Maxime Kohlhaas
- * Copyright (C) 2017 Regis Houssin
+ * Copyright (C) 2005 Rodolphe Quiedeville
+ * Copyright (C) 2006-2012 Laurent Destailleur
+ * Copyright (C) 2013 Maxime Kohlhaas
+ * Copyright (C) 2017 Regis Houssin
*
* 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
@@ -13,7 +13,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -21,196 +21,172 @@
*/
/**
- * \file scripts/user/sync_members_types_ldap2dolibarr.php
- * \ingroup ldap member
- * \brief Script to update members types into Dolibarr from LDAP
+ * \file scripts/user/sync_members_types_ldap2dolibarr.php
+ * \ingroup ldap member
+ * \brief Script to update members types into Dolibarr from LDAP
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test if batch mode
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";
- exit(-1);
+ 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);
}
-require_once $path."../../htdocs/master.inc.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."/adherents/class/adherent_type.class.php";
+require_once $path . "../../htdocs/master.inc.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 . "/adherents/class/adherent_type.class.php";
-$langs->loadLangs(array("main", "errors"));
+$langs->loadLangs(array("main","errors"));
// Global variables
-$version=DOL_VERSION;
-$error=0;
-$forcecommit=0;
-$confirmed=0;
-
+$version = DOL_VERSION;
+$error = 0;
+$forcecommit = 0;
+$confirmed = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
// List of fields to get from LDAP
-$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
-);
+$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);
// 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])) {
- //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";
- exit(-1);
+ exit(- 1);
}
-foreach($argv as $key => $val)
-{
- if ($val == 'commitiferror') $forcecommit=1;
- if (preg_match('/--server=([^\s]+)$/', $val, $reg)) $conf->global->LDAP_SERVER_HOST=$reg[1];
- if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg)) $excludeuser=explode(',', $reg[1]);
- if (preg_match('/-y$/', $val, $reg)) $confirmed=1;
+foreach ($argv as $key => $val) {
+ if ($val == 'commitiferror')
+ $forcecommit = 1;
+ if (preg_match('/--server=([^\s]+)$/', $val, $reg))
+ $conf->global->LDAP_SERVER_HOST = $reg[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";
-$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 "----- Synchronize all records from LDAP database:\n";
-print "host=".$conf->global->LDAP_SERVER_HOST."\n";
-print "port=".$conf->global->LDAP_SERVER_PORT."\n";
-print "login=".$conf->global->LDAP_ADMIN_DN."\n";
-print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n";
-print "DN to extract=".$conf->global->LDAP_MEMBER_TYPE_DN."\n";
-print 'Filter=('.$conf->global->LDAP_KEY_MEMBERS_TYPES.'=*)'."\n";
+print "host=" . $conf->global->LDAP_SERVER_HOST . "\n";
+print "port=" . $conf->global->LDAP_SERVER_PORT . "\n";
+print "login=" . $conf->global->LDAP_ADMIN_DN . "\n";
+print "pass=" . preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS) . "\n";
+print "DN to extract=" . $conf->global->LDAP_MEMBER_TYPE_DN . "\n";
+print 'Filter=(' . $conf->global->LDAP_KEY_MEMBERS_TYPES . '=*)' . "\n";
print "----- To Dolibarr database:\n";
-print "type=".$conf->db->type."\n";
-print "host=".$conf->db->host."\n";
-print "port=".$conf->db->port."\n";
-print "login=".$conf->db->user."\n";
-print "database=".$conf->db->name."\n";
+print "type=" . $conf->db->type . "\n";
+print "host=" . $conf->db->host . "\n";
+print "port=" . $conf->db->port . "\n";
+print "login=" . $conf->db->user . "\n";
+print "database=" . $conf->db->name . "\n";
print "----- Options:\n";
-print "commitiferror=".$forcecommit."\n";
-print "Mapped LDAP fields=".join(',', $required_fields)."\n";
+print "commitiferror=" . $forcecommit . "\n";
+print "Mapped LDAP fields=" . join(',', $required_fields) . "\n";
print "\n";
-if (! $confirmed)
-{
+if (! $confirmed) {
print "Hit Enter to continue or CTRL+C to stop...\n";
$input = trim(fgets(STDIN));
}
-if (empty($conf->global->LDAP_MEMBER_TYPE_DN))
-{
- print $langs->trans("Error").': '.$langs->trans("LDAP setup for members types not defined inside Dolibarr");
- exit(-1);
+if (empty($conf->global->LDAP_MEMBER_TYPE_DN)) {
+ print $langs->trans("Error") . ': ' . $langs->trans("LDAP setup for members types not defined inside Dolibarr");
+ exit(- 1);
}
-
$ldap = new Ldap();
$result = $ldap->connect_bind();
-if ($result >= 0)
-{
- $justthese=array();
-
+if ($result >= 0) {
+ $justthese = array();
// 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));
- if (is_array($ldaprecords))
- {
+ if (is_array($ldaprecords)) {
$db->begin();
// Warning $ldapuser has a key in lowercase
- foreach ($ldaprecords as $key => $ldapgroup)
- {
+ foreach ($ldaprecords as $key => $ldapgroup) {
$membertype = new AdherentType($db);
$membertype->fetch('', $ldapgroup[$conf->global->LDAP_KEY_MEMBERS_TYPES]);
$membertype->label = $ldapgroup[$conf->global->LDAP_MEMBER_TYPE_FIELD_FULLNAME];
$membertype->description = $ldapgroup[$conf->global->LDAP_MEMBER_TYPE_FIELD_DESCRIPTION];
$membertype->entity = $conf->entity;
- //print_r($ldapgroup);
+ // print_r($ldapgroup);
if ($membertype->id > 0) { // Member type update
- print $langs->transnoentities("MemberTypeUpdate").' # '.$key.': name='.$membertype->label;
- $res=$membertype->update($user);
+ print $langs->transnoentities("MemberTypeUpdate") . ' # ' . $key . ': name=' . $membertype->label;
+ $res = $membertype->update($user);
- if ($res > 0)
- {
- print ' --> Updated member type id='.$membertype->id.' name='.$membertype->label;
- }
- else
- {
- $error++;
- print ' --> '.$res.' '.$membertype->error;
+ if ($res > 0) {
+ print ' --> Updated member type id=' . $membertype->id . ' name=' . $membertype->label;
+ } else {
+ $error ++;
+ print ' --> ' . $res . ' ' . $membertype->error;
}
print "\n";
} else { // Member type creation
- print $langs->transnoentities("MemberTypeCreate").' # '.$key.': name='.$membertype->label;
- $res=$membertype->create($user);
+ print $langs->transnoentities("MemberTypeCreate") . ' # ' . $key . ': name=' . $membertype->label;
+ $res = $membertype->create($user);
- if ($res > 0)
- {
- print ' --> Created member type id='.$membertype->id.' name='.$membertype->label;
- }
- else
- {
- $error++;
- print ' --> '.$res.' '.$membertype->error;
+ if ($res > 0) {
+ print ' --> Created member type id=' . $membertype->id . ' name=' . $membertype->label;
+ } else {
+ $error ++;
+ print ' --> ' . $res . ' ' . $membertype->error;
}
print "\n";
}
- //print_r($membertype);
+ // print_r($membertype);
}
- if (! $error || $forcecommit)
- {
- if (! $error) print $langs->transnoentities("NoErrorCommitIsDone")."\n";
- else print $langs->transnoentities("ErrorButCommitIsDone")."\n";
+ if (! $error || $forcecommit) {
+ if (! $error)
+ print $langs->transnoentities("NoErrorCommitIsDone") . "\n";
+ else
+ print $langs->transnoentities("ErrorButCommitIsDone") . "\n";
$db->commit();
- }
- else
- {
- print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
+ } else {
+ print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error) . "\n";
$db->rollback();
}
print "\n";
- }
- else
- {
+ } else {
dol_print_error('', $ldap->error);
- $error++;
+ $error ++;
}
-}
-else
-{
+} else {
dol_print_error('', $ldap->error);
- $error++;
+ $error ++;
}
-
exit($error);
-
/**
* Function to say if a value is empty or not
*
- * @param string $element Value to test
- * @return boolean True of false
+ * @param string $element
+ * Value to test
+ * @return boolean True of false
*/
function dolValidElementType($element)
{
diff --git a/scripts/modulebuilder/builddoc.php b/scripts/modulebuilder/builddoc.php
deleted file mode 100755
index c0b44a0bed8..00000000000
--- a/scripts/modulebuilder/builddoc.php
+++ /dev/null
@@ -1,111 +0,0 @@
-#!/usr/bin/env php
-
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see .
- */
-
-
-/**
- * \file scripts/modulebuilder/builddoc.php
- * \ingroup modulebuilder
- * \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.
- * 
- * image:img/dolimed_screenshot_patientcard.png[Screenshot patient card]
- */
-
-
-$sapi_type = php_sapi_name();
-$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
-
-// Test if batch mode
-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";
- exit(-1);
-}
-
-if (! isset($argv[1]) || ! $argv[1]) {
- print "Usage: ".$script_file." ModuleName\n";
- exit(-1);
-}
-$modulename=$argv[1];
-
-require_once $path."../../htdocs/master.inc.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/class/html.formadmin.class.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/utils.class.php';
-
-$langs->loadLangs(array("admin", "modulebuilder", "other", "cron"));
-
-
-// Global variables
-$version=DOL_VERSION;
-$error=0;
-
-// Dir for custom dirs
-$tmp=explode(',', $dolibarr_main_document_root_alt);
-$dirins = $tmp[0];
-$dirread = $dirins;
-$forceddirread = 0;
-
-$tmpdir = explode('@', $module);
-if (! empty($tmpdir[1]))
-{
- $module=$tmpdir[0];
- $dirread=$tmpdir[1];
- $forceddirread=1;
-}
-
-$FILEFLAG='modulebuilder.txt';
-
-$now=dol_now();
-$newmask = 0;
-if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
-if (empty($newmask)) // This should no happen
-{
- $newmask='0664';
-}
-
-
-/*
- * Main
- */
-
-@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-print "modulename=".$modulename."\n";
-print "dirins=".$dirins."\n";
-
-$FILENAMEDOC=strtolower($module).'.html'; // TODO Use/text PDF
-$dirofmodule = dol_buildpath(strtolower($module), 0).'/doc';
-$outputfiledoc = $dirofmodule.'/'.$FILENAMEDOC;
-
-$util = new Utils($db);
-$result = $util->generateDoc($module);
-
-if ($result <= 0)
-{
- print $util->errors;
- exit(1);
-}
-
-print $langs->trans("DocFileGeneratedInto", $outputfiledoc);
-exit(0);
diff --git a/scripts/modulebuilder/initmodule.php b/scripts/modulebuilder/initmodule.php
deleted file mode 100755
index 46d3e6a7032..00000000000
--- a/scripts/modulebuilder/initmodule.php
+++ /dev/null
@@ -1,174 +0,0 @@
-#!/usr/bin/env php
-
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see .
- */
-
-
-/**
- * \file scripts/modulebuilder/initmodule.php
- * \ingroup modulebuilder
- * \brief Script to initialize a module.
- */
-
-
-$sapi_type = php_sapi_name();
-$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
-
-// Test if batch mode
-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";
- exit(-1);
-}
-
-if (! isset($argv[1]) || ! $argv[1]) {
- print "Usage: ".$script_file." ModuleName\n";
- exit(-1);
-}
-$modulename=$argv[1];
-
-require_once $path."../../htdocs/master.inc.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/class/html.formadmin.class.php';
-require_once DOL_DOCUMENT_ROOT.'/core/lib/modulebuilder.lib.php';
-require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
-
-$langs->loadLangs(array("admin", "modulebuilder", "other", "cron"));
-
-
-// Global variables
-$version=DOL_VERSION;
-$error=0;
-
-// Dir for custom dirs
-$tmp=explode(',', $dolibarr_main_document_root_alt);
-$dirins = $tmp[0];
-$dirread = $dirins;
-$forceddirread = 0;
-
-$tmpdir = explode('@', $module);
-if (! empty($tmpdir[1]))
-{
- $module=$tmpdir[0];
- $dirread=$tmpdir[1];
- $forceddirread=1;
-}
-
-$FILEFLAG='modulebuilder.txt';
-
-$now=dol_now();
-$newmask = 0;
-if (empty($newmask) && ! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
-if (empty($newmask)) // This should no happen
-{
- $newmask='0664';
-}
-
-
-/*
- * Main
- */
-
-@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-print "modulename=".$modulename."\n";
-print "dirins=".$dirins."\n";
-
-if (preg_match('/[^a-z0-9_]/i', $modulename))
-{
- $error++;
- print 'Error '.$langs->trans("SpaceOrSpecialCharAreNotAllowed")."\n";
- exit(1);
-}
-
-if (! $error)
-{
- $srcdir = DOL_DOCUMENT_ROOT.'/modulebuilder/template';
- $destdir = $dirins.'/'.strtolower($modulename);
-
- $arrayreplacement=array(
- 'mymodule'=>strtolower($modulename),
- 'MyModule'=>$modulename
- );
-
- $result = dolCopyDir($srcdir, $destdir, 0, 0, $arrayreplacement);
- //dol_mkdir($destfile);
- if ($result <= 0)
- {
- if ($result < 0)
- {
- $error++;
- $langs->load("errors");
- print $langs->trans("ErrorFailToCopyDir", $srcdir, $destdir)."\n";
- exit(2);
- }
- else // $result == 0
- {
- print $langs->trans("AllFilesDidAlreadyExist", $srcdir, $destdir)."\n";
- }
- }
-
- // Delete some files
- dol_delete_file($destdir.'/myobject_card.php');
- dol_delete_file($destdir.'/myobject_note.php');
- dol_delete_file($destdir.'/myobject_document.php');
- dol_delete_file($destdir.'/myobject_agenda.php');
- dol_delete_file($destdir.'/myobject_list.php');
- dol_delete_file($destdir.'/lib/myobject.lib.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_extrafields.sql');
- dol_delete_file($destdir.'/sql/llx_mymodule_myobject.key.sql');
- dol_delete_file($destdir.'/scripts/myobject.php');
- dol_delete_file($destdir.'/img/object_myobject.png');
- dol_delete_file($destdir.'/class/myobject.class.php');
- dol_delete_file($destdir.'/class/api_mymodule.class.php');
-}
-
-// Edit PHP files
-if (! $error)
-{
- $listofphpfilestoedit = dol_dir_list($destdir, 'files', 1, '\.(php|MD|js|sql|txt|xml|lang)$', '', 'fullname', SORT_ASC, 0, 1);
- foreach($listofphpfilestoedit as $phpfileval)
- {
- //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.'>':'')
- );
-
-
- $result=dolReplaceInFile($phpfileval['fullname'], $arrayreplacement);
- //var_dump($result);
- if ($result < 0)
- {
- print $langs->trans("ErrorFailToMakeReplacementInto", $phpfileval['fullname'])."\n";
- exit(3);
- }
- }
-}
-
-print 'Module initialized'."\n";
-exit(0);
diff --git a/scripts/product/migrate_picture_path.php b/scripts/product/migrate_picture_path.php
index a0a17632357..7abbcc59cc5 100755
--- a/scripts/product/migrate_picture_path.php
+++ b/scripts/product/migrate_picture_path.php
@@ -1,7 +1,8 @@
#!/usr/bin/env php
- * Copyright (C) 2015 Jean Heimburger
+/*
+ * Copyright (C) 2007-2016 Laurent Destailleur
+ * Copyright (C) 2015 Jean Heimburger
*
* 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
@@ -10,7 +11,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -18,86 +19,76 @@
*/
/**
- * \file scripts/product/migrate_picture_path.php
- * \ingroup scripts
- * \brief Migrate pictures from old system prior to 3.7 to new path for 3.7+
+ * \file scripts/product/migrate_picture_path.php
+ * \ingroup scripts
+ * \brief Migrate pictures from old system prior to 3.7 to new path for 3.7+
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test if batch mode
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";
- exit(-1);
+ 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);
}
-@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".
+@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".
// Include and load Dolibarr environment variables
-require_once $path."../../htdocs/master.inc.php";
-require_once DOL_DOCUMENT_ROOT."/product/class/product.class.php";
-require_once DOL_DOCUMENT_ROOT."/core/lib/files.lib.php";
+require_once $path . "../../htdocs/master.inc.php";
+require_once DOL_DOCUMENT_ROOT . "/product/class/product.class.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).
// $user is created but empty.
-//$langs->setDefaultLang('en_US'); // To change default language of $langs
-$langs->load("main"); // To load language file for default language
-
+// $langs->setDefaultLang('en_US'); // To change default language of $langs
+$langs->load("main"); // To load language file for default language
// Global variables
-$version=DOL_VERSION;
-$error=0;
-$forcecommit=0;
+$version = DOL_VERSION;
+$error = 0;
+$forcecommit = 0;
-
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
if (! isset($argv[1]) || $argv[1] != 'product') {
- print "Usage: $script_file product\n";
- exit(-1);
+ print "Usage: $script_file product\n";
+ exit(- 1);
}
-print '--- start'."\n";
+print '--- start' . "\n";
// Case to migrate products path
-if ($argv[1] == 'product')
-{
+if ($argv[1] == 'product') {
$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);
- if ($resql)
- {
- while ($obj = $db->fetch_object($resql))
- {
+ if ($resql) {
+ while ($obj = $db->fetch_object($resql)) {
$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);
}
- }
- else
- {
- print "\n sql error ".$sql;
- exit;
+ } else {
+ print "\n sql error " . $sql;
+ exit();
}
}
-
-$db->close(); // Close $db database opened handler
+$db->close(); // Close $db database opened handler
exit($error);
-
-
/**
* Migrate file from old path to new one for product $product
*
- * @param Product $product Object product
- * @return void
+ * @param Product $product
+ * Object product
+ * @return void
*/
function migrate_product_photospath($product)
{
@@ -105,43 +96,34 @@ function migrate_product_photospath($product)
$dir = $conf->product->multidir_output[$product->entity];
$conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO = 1;
- $origin = $dir .'/'. get_exdir($product->id, 2, 0, 0, $product, 'product') . $product->id ."/photos";
- $destin = $dir.'/'.dol_sanitizeFileName($product->ref);
+ $origin = $dir . '/' . get_exdir($product->id, 2, 0, 0, $product, 'product') . $product->id . "/photos";
+ $destin = $dir . '/' . dol_sanitizeFileName($product->ref);
$error = 0;
- $origin_osencoded=dol_osencode($origin);
- $destin_osencoded=dol_osencode($destin);
+ $origin_osencoded = dol_osencode($origin);
+ $destin_osencoded = dol_osencode($destin);
dol_mkdir($destin);
- if (dol_is_dir($origin))
- {
- $handle=opendir($origin_osencoded);
- if (is_resource($handle))
- {
- while (($file = readdir($handle)) !== false)
- {
- if ($file != '.' && $file != '..' && is_dir($origin_osencoded.'/'.$file))
- {
- $thumbs = opendir($origin_osencoded.'/'.$file);
- if (is_resource($thumbs))
- {
- dol_mkdir($destin.'/'.$file);
- while (($thumb = readdir($thumbs)) !== false)
- {
- dol_move($origin.'/'.$file.'/'.$thumb, $destin.'/'.$file.'/'.$thumb);
- }
-// dol_delete_dir($origin.'/'.$file);
- }
- }
- else
- {
- if (dol_is_file($origin.'/'.$file) )
- {
- dol_move($origin.'/'.$file, $destin.'/'.$file);
- }
- }
- }
- }
+ if (dol_is_dir($origin)) {
+ $handle = opendir($origin_osencoded);
+ if (is_resource($handle)) {
+ while (($file = readdir($handle)) !== false) {
+ if ($file != '.' && $file != '..' && is_dir($origin_osencoded . '/' . $file)) {
+ $thumbs = opendir($origin_osencoded . '/' . $file);
+ if (is_resource($thumbs)) {
+ dol_mkdir($destin . '/' . $file);
+ while (($thumb = readdir($thumbs)) !== false) {
+ dol_move($origin . '/' . $file . '/' . $thumb, $destin . '/' . $file . '/' . $thumb);
+ }
+ // dol_delete_dir($origin.'/'.$file);
+ }
+ } else {
+ if (dol_is_file($origin . '/' . $file)) {
+ dol_move($origin . '/' . $file, $destin . '/' . $file);
+ }
+ }
+ }
+ }
}
}
diff --git a/scripts/product/regenerate_thumbs.php b/scripts/product/regenerate_thumbs.php
index 84f30b3950f..d034cec1ec9 100755
--- a/scripts/product/regenerate_thumbs.php
+++ b/scripts/product/regenerate_thumbs.php
@@ -1,7 +1,8 @@
#!/usr/bin/env php
- * Copyright (C) 2015 Jean Heimburger
+/*
+ * Copyright (C) 2007-2016 Laurent Destailleur
+ * Copyright (C) 2015 Jean Heimburger
*
* 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
@@ -10,7 +11,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -18,90 +19,85 @@
*/
/**
- * \file scripts/product/migrate_picture_path.php
- * \ingroup scripts
- * \brief Migrate pictures from old system prior to 3.7 to new path for 3.7+
+ * \file scripts/product/migrate_picture_path.php
+ * \ingroup scripts
+ * \brief Migrate pictures from old system prior to 3.7 to new path for 3.7+
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test if batch mode
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";
- exit(-1);
+ 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);
}
-@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".
+@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".
// Include and load Dolibarr environment variables
-require_once $path."../../htdocs/master.inc.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/images.lib.php";
+require_once $path . "../../htdocs/master.inc.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/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).
// $user is created but empty.
-//$langs->setDefaultLang('en_US'); // To change default language of $langs
-$langs->load("main"); // To load language file for default language
-
+// $langs->setDefaultLang('en_US'); // To change default language of $langs
+$langs->load("main"); // To load language file for default language
// Global variables
-$version=DOL_VERSION;
-$error=0;
-$forcecommit=0;
+$version = DOL_VERSION;
+$error = 0;
+$forcecommit = 0;
-
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
if (empty($argv[1])) {
- print "Usage: $script_file subdirtoscan\n";
- print "Example: $script_file produit\n";
- exit(-1);
+ print "Usage: $script_file subdirtoscan\n";
+ print "Example: $script_file produit\n";
+ exit(- 1);
}
-print '--- start'."\n";
+print '--- start' . "\n";
$dir = DOL_DATA_ROOT;
-$subdir=$argv[1];
-if (empty($dir) || empty($subdir))
-{
+$subdir = $argv[1];
+if (empty($dir) || empty($subdir)) {
dol_print_error('', 'dir not defined');
exit(1);
}
-if (! dol_is_dir($dir.'/'.$subdir))
-{
- print 'Directory '.$dir.'/'.$subdir.' not found.'."\n";
+if (! dol_is_dir($dir . '/' . $subdir)) {
+ print 'Directory ' . $dir . '/' . $subdir . ' not found.' . "\n";
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;
-foreach($filearray as $keyf => $valf)
-{
- $ref=basename($valf['name']);
- $filearrayimg=dol_dir_list($valf['fullname'], "files", 0, '(\.gif|\.png|\.jpg|\.jpeg|\.bmp)$', '(\.meta|_preview.*\.png)$');
- foreach($filearrayimg as $keyi => $vali)
- {
- print 'Process image for ref '.$ref.' : '.$vali['name']."\n";
+foreach ($filearray as $keyf => $valf) {
+ $ref = basename($valf['name']);
+ $filearrayimg = dol_dir_list($valf['fullname'], "files", 0, '(\.gif|\.png|\.jpg|\.jpeg|\.bmp)$', '(\.meta|_preview.*\.png)$');
+ foreach ($filearrayimg as $keyi => $vali) {
+ print 'Process image for ref ' . $ref . ' : ' . $vali['name'] . "\n";
// Create small thumbs for image
// Used on logon for example
$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)
// Used on menu or for setup page for example
$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);
diff --git a/scripts/user/sync_groups_dolibarr2ldap.php b/scripts/user/sync_groups_dolibarr2ldap.php
index 2d6a074d9c2..23ca994799f 100755
--- a/scripts/user/sync_groups_dolibarr2ldap.php
+++ b/scripts/user/sync_groups_dolibarr2ldap.php
@@ -2,7 +2,7 @@
- * Copyright (C) 2006 Laurent Destailleur
+ * Copyright (C) 2006 Laurent Destailleur
*
* 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
@@ -11,7 +11,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -19,67 +19,63 @@
*/
/**
- * \file scripts/user/sync_groups_dolibarr2ldap.php
- * \ingroup ldap core
- * \brief Script de mise a jour des groupes dans LDAP depuis base Dolibarr
+ * \file scripts/user/sync_groups_dolibarr2ldap.php
+ * \ingroup ldap core
+ * \brief Script de mise a jour des groupes dans LDAP depuis base Dolibarr
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test if batch mode
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";
- exit(-1);
+ 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);
}
if (! isset($argv[1]) || ! $argv[1]) {
- print "Usage: ".$script_file." now\n";
- exit(-1);
+ print "Usage: " . $script_file . " now\n";
+ exit(- 1);
}
-$now=$argv[1];
+$now = $argv[1];
-require_once $path."../../htdocs/master.inc.php";
-require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php";
-require_once DOL_DOCUMENT_ROOT."/user/class/usergroup.class.php";
+require_once $path . "../../htdocs/master.inc.php";
+require_once DOL_DOCUMENT_ROOT . "/core/class/ldap.class.php";
+require_once DOL_DOCUMENT_ROOT . "/user/class/usergroup.class.php";
// Global variables
-$version=DOL_VERSION;
-$error=0;
-
+$version = DOL_VERSION;
+$error = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
/*
-if (! $conf->global->LDAP_SYNCHRO_ACTIVE)
-{
- print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
- exit(-1);
-}
-*/
+ * if (! $conf->global->LDAP_SYNCHRO_ACTIVE)
+ * {
+ * print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
+ * exit(-1);
+ * }
+ */
$sql = "SELECT rowid";
-$sql .= " FROM ".MAIN_DB_PREFIX."usergroup";
+$sql .= " FROM " . MAIN_DB_PREFIX . "usergroup";
$resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
$num = $db->num_rows($resql);
$i = 0;
- $ldap=new Ldap();
+ $ldap = new Ldap();
$ldap->connect_bind();
- while ($i < $num)
- {
- $ldap->error="";
+ while ($i < $num) {
+ $ldap->error = "";
$obj = $db->fetch_object($resql);
@@ -87,37 +83,32 @@ if ($resql)
$fgroup->id = $obj->rowid;
$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();
- $olddn=$oldobject->_load_ldap_dn($oldinfo);
+ $oldinfo = $oldobject->_load_ldap_info();
+ $olddn = $oldobject->_load_ldap_dn($oldinfo);
- $info=$fgroup->_load_ldap_info();
- $dn=$fgroup->_load_ldap_dn($info);
+ $info = $fgroup->_load_ldap_info();
+ $dn = $fgroup->_load_ldap_dn($info);
- $result=$ldap->add($dn, $info, $user); // Wil fail if already exists
- $result=$ldap->update($dn, $info, $user, $olddn);
- if ($result > 0)
- {
- print " - ".$langs->trans("OK");
- }
- else
- {
- $error++;
- print " - ".$langs->trans("KO").' - '.$ldap->error;
+ $result = $ldap->add($dn, $info, $user); // Wil fail if already exists
+ $result = $ldap->update($dn, $info, $user, $olddn);
+ if ($result > 0) {
+ print " - " . $langs->trans("OK");
+ } else {
+ $error ++;
+ print " - " . $langs->trans("KO") . ' - ' . $ldap->error;
}
print "\n";
- $i++;
+ $i ++;
}
$ldap->unbind();
$ldap->close();
-}
-else
-{
+} else {
dol_print_error($db);
}
diff --git a/scripts/user/sync_groups_ldap2dolibarr.php b/scripts/user/sync_groups_ldap2dolibarr.php
index 8fca8f9df9b..393a866de5e 100755
--- a/scripts/user/sync_groups_ldap2dolibarr.php
+++ b/scripts/user/sync_groups_ldap2dolibarr.php
@@ -1,9 +1,9 @@
#!/usr/bin/env php
- * Copyright (C) 2006-2012 Laurent Destailleur
- * Copyright (C) 2013 Maxime Kohlhaas
+ * Copyright (C) 2005 Rodolphe Quiedeville
+ * Copyright (C) 2006-2012 Laurent Destailleur
+ * Copyright (C) 2013 Maxime Kohlhaas
*
* 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
@@ -12,7 +12,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -20,182 +20,166 @@
*/
/**
- * \file scripts/user/sync_groups_ldap2dolibarr.php
- * \ingroup ldap member
- * \brief Script to update groups into Dolibarr from LDAP
+ * \file scripts/user/sync_groups_ldap2dolibarr.php
+ * \ingroup ldap member
+ * \brief Script to update groups into Dolibarr from LDAP
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test if batch mode
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";
- exit(-1);
+ 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);
}
-require_once $path."../../htdocs/master.inc.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."/user/class/user.class.php";
-require_once DOL_DOCUMENT_ROOT."/user/class/usergroup.class.php";
+require_once $path . "../../htdocs/master.inc.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 . "/user/class/user.class.php";
+require_once DOL_DOCUMENT_ROOT . "/user/class/usergroup.class.php";
-$langs->loadLangs(array("main", "errors"));
+$langs->loadLangs(array("main","errors"));
// Global variables
-$version=DOL_VERSION;
-$error=0;
-$forcecommit=0;
-$confirmed=0;
-
+$version = DOL_VERSION;
+$error = 0;
+$forcecommit = 0;
+$confirmed = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
// List of fields to get from LDAP
-$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
-);
+$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);
// 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])) {
- //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";
- exit(-1);
+ exit(- 1);
}
-foreach($argv as $key => $val)
-{
- if ($val == 'commitiferror') $forcecommit=1;
- if (preg_match('/--server=([^\s]+)$/', $val, $reg)) $conf->global->LDAP_SERVER_HOST=$reg[1];
- if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg)) $excludeuser=explode(',', $reg[1]);
- if (preg_match('/-y$/', $val, $reg)) $confirmed=1;
+foreach ($argv as $key => $val) {
+ if ($val == 'commitiferror')
+ $forcecommit = 1;
+ if (preg_match('/--server=([^\s]+)$/', $val, $reg))
+ $conf->global->LDAP_SERVER_HOST = $reg[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";
-$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 "----- Synchronize all records from LDAP database:\n";
-print "host=".$conf->global->LDAP_SERVER_HOST."\n";
-print "port=".$conf->global->LDAP_SERVER_PORT."\n";
-print "login=".$conf->global->LDAP_ADMIN_DN."\n";
-print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\n";
-print "DN to extract=".$conf->global->LDAP_GROUP_DN."\n";
-print 'Filter=('.$conf->global->LDAP_KEY_GROUPS.'=*)'."\n";
+print "host=" . $conf->global->LDAP_SERVER_HOST . "\n";
+print "port=" . $conf->global->LDAP_SERVER_PORT . "\n";
+print "login=" . $conf->global->LDAP_ADMIN_DN . "\n";
+print "pass=" . preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS) . "\n";
+print "DN to extract=" . $conf->global->LDAP_GROUP_DN . "\n";
+print 'Filter=(' . $conf->global->LDAP_KEY_GROUPS . '=*)' . "\n";
print "----- To Dolibarr database:\n";
-print "type=".$conf->db->type."\n";
-print "host=".$conf->db->host."\n";
-print "port=".$conf->db->port."\n";
-print "login=".$conf->db->user."\n";
-print "database=".$conf->db->name."\n";
+print "type=" . $conf->db->type . "\n";
+print "host=" . $conf->db->host . "\n";
+print "port=" . $conf->db->port . "\n";
+print "login=" . $conf->db->user . "\n";
+print "database=" . $conf->db->name . "\n";
print "----- Options:\n";
-print "commitiferror=".$forcecommit."\n";
-print "Mapped LDAP fields=".join(',', $required_fields)."\n";
+print "commitiferror=" . $forcecommit . "\n";
+print "Mapped LDAP fields=" . join(',', $required_fields) . "\n";
print "\n";
-if (! $confirmed)
-{
+if (! $confirmed) {
print "Hit Enter to continue or CTRL+C to stop...\n";
$input = trim(fgets(STDIN));
}
-if (empty($conf->global->LDAP_GROUP_DN))
-{
- print $langs->trans("Error").': '.$langs->trans("LDAP setup for groups not defined inside Dolibarr");
- exit(-1);
+if (empty($conf->global->LDAP_GROUP_DN)) {
+ print $langs->trans("Error") . ': ' . $langs->trans("LDAP setup for groups not defined inside Dolibarr");
+ exit(- 1);
}
-
$ldap = new Ldap();
$result = $ldap->connect_bind();
-if ($result >= 0)
-{
- $justthese=array();
-
+if ($result >= 0) {
+ $justthese = array();
// 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));
- if (is_array($ldaprecords))
- {
+ if (is_array($ldaprecords)) {
$db->begin();
// Warning $ldapuser has a key in lowercase
- foreach ($ldaprecords as $key => $ldapgroup)
- {
+ foreach ($ldaprecords as $key => $ldapgroup) {
$group = new UserGroup($db);
$group->fetch('', $ldapgroup[$conf->global->LDAP_KEY_GROUPS]);
$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->entity = $conf->entity;
- //print_r($ldapgroup);
+ // print_r($ldapgroup);
- if($group->id > 0) { // Group update
- print $langs->transnoentities("GroupUpdate").' # '.$key.': name='.$group->name;
- $res=$group->update();
+ if ($group->id > 0) { // Group update
+ print $langs->transnoentities("GroupUpdate") . ' # ' . $key . ': name=' . $group->name;
+ $res = $group->update();
- if ($res > 0)
- {
- print ' --> Updated group id='.$group->id.' name='.$group->name;
- }
- else
- {
- $error++;
- print ' --> '.$res.' '.$group->error;
+ if ($res > 0) {
+ print ' --> Updated group id=' . $group->id . ' name=' . $group->name;
+ } else {
+ $error ++;
+ print ' --> ' . $res . ' ' . $group->error;
}
print "\n";
} else { // Group creation
- print $langs->transnoentities("GroupCreate").' # '.$key.': name='.$group->name;
- $res=$group->create();
+ print $langs->transnoentities("GroupCreate") . ' # ' . $key . ': name=' . $group->name;
+ $res = $group->create();
- if ($res > 0)
- {
- print ' --> Created group id='.$group->id.' name='.$group->name;
- }
- else
- {
- $error++;
- print ' --> '.$res.' '.$group->error;
+ if ($res > 0) {
+ print ' --> Created group id=' . $group->id . ' name=' . $group->name;
+ } else {
+ $error ++;
+ print ' --> ' . $res . ' ' . $group->error;
}
print "\n";
}
- //print_r($group);
+ // print_r($group);
// Gestion des utilisateurs associés au groupe
// 1 - Association des utilisateurs du groupe LDAP au groupe Dolibarr
$userList = array();
$userIdList = array();
- foreach($ldapgroup[$conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS] as $key => $userdn) {
- if($key === 'count') continue;
- if(empty($userList[$userdn])) { // Récupération de l'utilisateur
- // 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'){
+ foreach ($ldapgroup[$conf->global->LDAP_GROUP_FIELD_GROUPMEMBERS] as $key => $userdn) {
+ if ($key === 'count')
+ continue;
+ if (empty($userList[$userdn])) { // Récupération de l'utilisateur
+ // 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);
} else { // Pour les autres schémas, les membres sont listés sous forme de DN complets
$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);
- 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
} elseif ($conf->global->LDAP_KEY_USERS == $conf->global->LDAP_FIELD_LOGIN) {
$fuser->fetch('', $userKey[0]); // Chargement du user concerné par le login
@@ -209,55 +193,49 @@ if ($result >= 0)
$userIdList[$userdn] = $fuser->id;
// 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);
- 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
foreach ($group->members as $guser) {
- if(!in_array($guser->id, $userIdList)) {
+ if (! in_array($guser->id, $userIdList)) {
$guser->RemoveFromGroup($group->id, $group->entity);
- echo $guser->login.' removed'."\n";
+ echo $guser->login . ' removed' . "\n";
}
}
}
- if (! $error || $forcecommit)
- {
- if (! $error) print $langs->transnoentities("NoErrorCommitIsDone")."\n";
- else print $langs->transnoentities("ErrorButCommitIsDone")."\n";
+ if (! $error || $forcecommit) {
+ if (! $error)
+ print $langs->transnoentities("NoErrorCommitIsDone") . "\n";
+ else
+ print $langs->transnoentities("ErrorButCommitIsDone") . "\n";
$db->commit();
- }
- else
- {
- print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
+ } else {
+ print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error) . "\n";
$db->rollback();
}
print "\n";
- }
- else
- {
+ } else {
dol_print_error('', $ldap->error);
- $error++;
+ $error ++;
}
-}
-else
-{
+} else {
dol_print_error('', $ldap->error);
- $error++;
+ $error ++;
}
-
exit($error);
-
/**
* Function to say if a value is empty or not
*
- * @param string $element Value to test
- * @return boolean True of false
+ * @param string $element
+ * Value to test
+ * @return boolean True of false
*/
function dolValidElement($element)
{
diff --git a/scripts/user/sync_users_dolibarr2ldap.php b/scripts/user/sync_users_dolibarr2ldap.php
index 64536f24a14..9fb613efd0d 100755
--- a/scripts/user/sync_users_dolibarr2ldap.php
+++ b/scripts/user/sync_users_dolibarr2ldap.php
@@ -2,7 +2,7 @@
- * Copyright (C) 2006 Laurent Destailleur
+ * Copyright (C) 2006 Laurent Destailleur
*
* 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
@@ -11,7 +11,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -19,104 +19,95 @@
*/
/**
- * \file scripts/user/sync_users_dolibarr2ldap.php
- * \ingroup ldap core
- * \brief Script de mise a jour des users dans LDAP depuis base Dolibarr
+ * \file scripts/user/sync_users_dolibarr2ldap.php
+ * \ingroup ldap core
+ * \brief Script de mise a jour des users dans LDAP depuis base Dolibarr
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test if batch mode
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";
- exit(-1);
+ 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);
}
if (! isset($argv[1]) || ! $argv[1]) {
- print "Usage: $script_file now\n";
- exit(-1);
+ print "Usage: $script_file now\n";
+ exit(- 1);
}
-$now=$argv[1];
+$now = $argv[1];
-require_once $path."../../htdocs/master.inc.php";
-require_once DOL_DOCUMENT_ROOT."/core/class/ldap.class.php";
-require_once DOL_DOCUMENT_ROOT."/user/class/user.class.php";
+require_once $path . "../../htdocs/master.inc.php";
+require_once DOL_DOCUMENT_ROOT . "/core/class/ldap.class.php";
+require_once DOL_DOCUMENT_ROOT . "/user/class/user.class.php";
// Global variables
-$version=DOL_VERSION;
-$error=0;
-
+$version = DOL_VERSION;
+$error = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
/*
-if (! $conf->global->LDAP_SYNCHRO_ACTIVE)
-{
- print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
- exit(-1);
-}
-*/
+ * if (! $conf->global->LDAP_SYNCHRO_ACTIVE)
+ * {
+ * print $langs->trans("LDAPSynchronizationNotSetupInDolibarr");
+ * exit(-1);
+ * }
+ */
$sql = "SELECT rowid";
-$sql .= " FROM ".MAIN_DB_PREFIX."user";
+$sql .= " FROM " . MAIN_DB_PREFIX . "user";
$resql = $db->query($sql);
-if ($resql)
-{
+if ($resql) {
$num = $db->num_rows($resql);
$i = 0;
- $ldap=new Ldap();
+ $ldap = new Ldap();
$ldap->connect_bind();
- while ($i < $num)
- {
- $ldap->error="";
+ while ($i < $num) {
+ $ldap->error = "";
$obj = $db->fetch_object($resql);
$fuser = new User($db);
$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();
- $olddn=$oldobject->_load_ldap_dn($oldinfo);
+ $oldinfo = $oldobject->_load_ldap_info();
+ $olddn = $oldobject->_load_ldap_dn($oldinfo);
- $info=$fuser->_load_ldap_info();
- $dn=$fuser->_load_ldap_dn($info);
+ $info = $fuser->_load_ldap_info();
+ $dn = $fuser->_load_ldap_dn($info);
- $result=$ldap->add($dn, $info, $user); // Wil fail if already exists
- $result=$ldap->update($dn, $info, $user, $olddn);
- if ($result > 0)
- {
- print " - ".$langs->trans("OK");
- }
- else
- {
- $error++;
- print " - ".$langs->trans("KO").' - '.$ldap->error;
+ $result = $ldap->add($dn, $info, $user); // Wil fail if already exists
+ $result = $ldap->update($dn, $info, $user, $olddn);
+ if ($result > 0) {
+ print " - " . $langs->trans("OK");
+ } else {
+ $error ++;
+ print " - " . $langs->trans("KO") . ' - ' . $ldap->error;
}
print "\n";
- $i++;
+ $i ++;
}
$ldap->unbind();
$ldap->close();
-}
-else
-{
+} else {
dol_print_error($db);
}
diff --git a/scripts/user/sync_users_ldap2dolibarr.php b/scripts/user/sync_users_ldap2dolibarr.php
index 5a7f7ad5f53..75925b109bf 100755
--- a/scripts/user/sync_users_ldap2dolibarr.php
+++ b/scripts/user/sync_users_ldap2dolibarr.php
@@ -1,8 +1,8 @@
#!/usr/bin/env php
- * Copyright (C) 2006-2012 Laurent Destailleur
+ * Copyright (C) 2005 Rodolphe Quiedeville
+ * Copyright (C) 2006-2012 Laurent Destailleur
*
* 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
@@ -11,7 +11,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -19,301 +19,266 @@
*/
/**
- * \file scripts/user/sync_users_ldap2dolibarr.php
- * \ingroup ldap member
- * \brief Script to update users into Dolibarr from LDAP
+ * \file scripts/user/sync_users_ldap2dolibarr.php
+ * \ingroup ldap member
+ * \brief Script to update users into Dolibarr from LDAP
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test if batch mode
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";
- exit(-1);
+ 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);
}
-require_once $path."../../htdocs/master.inc.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."/user/class/user.class.php";
+require_once $path . "../../htdocs/master.inc.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 . "/user/class/user.class.php";
-$langs->loadLangs(array("main", "errors"));
+$langs->loadLangs(array("main","errors"));
// Global variables
-$version=DOL_VERSION;
-$error=0;
-$forcecommit=0;
-$excludeuser=array();
-$confirmed=0;
+$version = DOL_VERSION;
+$error = 0;
+$forcecommit = 0;
+$excludeuser = array();
+$confirmed = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
// List of fields to get from LDAP
-$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_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
-);
+$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_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
-$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])) {
print "Usage: $script_file (nocommitiferror|commitiferror) [--server=ldapserverhost] [--excludeuser=user1,user2...] [-y]\n";
- exit(-1);
+ exit(- 1);
}
-foreach($argv as $key => $val)
-{
- if ($val == 'commitiferror') $forcecommit=1;
- if (preg_match('/--server=([^\s]+)$/', $val, $reg)) $conf->global->LDAP_SERVER_HOST=$reg[1];
- if (preg_match('/--excludeuser=([^\s]+)$/', $val, $reg)) $excludeuser=explode(',', $reg[1]);
- if (preg_match('/-y$/', $val, $reg)) $confirmed=1;
+foreach ($argv as $key => $val) {
+ if ($val == 'commitiferror')
+ $forcecommit = 1;
+ if (preg_match('/--server=([^\s]+)$/', $val, $reg))
+ $conf->global->LDAP_SERVER_HOST = $reg[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";
-$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 "----- Synchronize all records from LDAP database:\n";
-print "host=".$conf->global->LDAP_SERVER_HOST."\n";
-print "port=".$conf->global->LDAP_SERVER_PORT."\n";
-print "login=".$conf->global->LDAP_ADMIN_DN."\n";
-print "pass=".preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS)."\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
-else print 'Filter=('.$conf->global->LDAP_KEY_USERS.'=*)'."\n";
+print "host=" . $conf->global->LDAP_SERVER_HOST . "\n";
+print "port=" . $conf->global->LDAP_SERVER_PORT . "\n";
+print "login=" . $conf->global->LDAP_ADMIN_DN . "\n";
+print "pass=" . preg_replace('/./i', '*', $conf->global->LDAP_ADMIN_PASS) . "\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
+else
+ print 'Filter=(' . $conf->global->LDAP_KEY_USERS . '=*)' . "\n";
print "----- To Dolibarr database:\n";
-print "type=".$conf->db->type."\n";
-print "host=".$conf->db->host."\n";
-print "port=".$conf->db->port."\n";
-print "login=".$conf->db->user."\n";
-print "database=".$conf->db->name."\n";
+print "type=" . $conf->db->type . "\n";
+print "host=" . $conf->db->host . "\n";
+print "port=" . $conf->db->port . "\n";
+print "login=" . $conf->db->user . "\n";
+print "database=" . $conf->db->name . "\n";
print "----- Options:\n";
-print "commitiferror=".$forcecommit."\n";
-print "excludeuser=".join(',', $excludeuser)."\n";
-print "Mapped LDAP fields=".join(',', $required_fields)."\n";
+print "commitiferror=" . $forcecommit . "\n";
+print "excludeuser=" . join(',', $excludeuser) . "\n";
+print "Mapped LDAP fields=" . join(',', $required_fields) . "\n";
print "\n";
-if (! $confirmed)
-{
+if (! $confirmed) {
print "Hit Enter to continue or CTRL+C to stop...\n";
$input = trim(fgets(STDIN));
}
-if (empty($conf->global->LDAP_USER_DN))
-{
- print $langs->trans("Error").': '.$langs->trans("LDAP setup for users not defined inside Dolibarr");
- exit(-1);
+if (empty($conf->global->LDAP_USER_DN)) {
+ print $langs->trans("Error") . ': ' . $langs->trans("LDAP setup for users not defined inside Dolibarr");
+ exit(- 1);
}
-
// Load table of correspondence of countries
-$hashlib2rowid=array();
-$countries=array();
+$hashlib2rowid = array();
+$countries = array();
$sql = "SELECT rowid, code, label, active";
-$sql.= " FROM ".MAIN_DB_PREFIX."c_country";
-$sql.= " WHERE active = 1";
-$sql.= " ORDER BY code ASC";
-$resql=$db->query($sql);
-if ($resql)
-{
+$sql .= " FROM " . MAIN_DB_PREFIX . "c_country";
+$sql .= " WHERE active = 1";
+$sql .= " ORDER BY code ASC";
+$resql = $db->query($sql);
+if ($resql) {
$num = $db->num_rows($resql);
$i = 0;
- if ($num)
- {
- while ($i < $num)
- {
+ if ($num) {
+ while ($i < $num) {
$obj = $db->fetch_object($resql);
- if ($obj)
- {
- //print 'Load cache for country '.strtolower($obj->label).' rowid='.$obj->rowid."\n";
- $hashlib2rowid[strtolower($obj->label)]=$obj->rowid;
- $countries[$obj->rowid]=array('rowid' => $obj->rowid, 'label' => $obj->label, 'code' => $obj->code);
+ if ($obj) {
+ // print 'Load cache for country '.strtolower($obj->label).' rowid='.$obj->rowid."\n";
+ $hashlib2rowid[strtolower($obj->label)] = $obj->rowid;
+ $countries[$obj->rowid] = array('rowid' => $obj->rowid,'label' => $obj->label,'code' => $obj->code);
}
- $i++;
+ $i ++;
}
}
-}
-else
-{
+} else {
dol_print_error($db);
- exit(-1);
+ exit(- 1);
}
-
-
$ldap = new Ldap();
$result = $ldap->connect_bind();
-if ($result >= 0)
-{
- $justthese=array();
-
+if ($result >= 0) {
+ $justthese = array();
// 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
- if (is_array($ldaprecords))
- {
+ $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)) {
$db->begin();
// 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 (in_array($ldapuser[$conf->global->LDAP_FIELD_LOGIN], $excludeuser))
- {
- print $langs->transnoentities("UserDiscarded").' # '.$key.': login='.$ldapuser[$conf->global->LDAP_FIELD_LOGIN].' --> Discarded'."\n";
+ if (in_array($ldapuser[$conf->global->LDAP_FIELD_LOGIN], $excludeuser)) {
+ print $langs->transnoentities("UserDiscarded") . ' # ' . $key . ': login=' . $ldapuser[$conf->global->LDAP_FIELD_LOGIN] . ' --> Discarded' . "\n";
continue;
}
$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
} 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
}
// Propriete membre
- $fuser->firstname=$ldapuser[$conf->global->LDAP_FIELD_FIRSTNAME];
- $fuser->lastname=$ldapuser[$conf->global->LDAP_FIELD_NAME];
- $fuser->login=$ldapuser[$conf->global->LDAP_FIELD_LOGIN];
- $fuser->pass=$ldapuser[$conf->global->LDAP_FIELD_PASSWORD];
- $fuser->pass_indatabase_crypted=$ldapuser[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED];
+ $fuser->firstname = $ldapuser[$conf->global->LDAP_FIELD_FIRSTNAME];
+ $fuser->lastname = $ldapuser[$conf->global->LDAP_FIELD_NAME];
+ $fuser->login = $ldapuser[$conf->global->LDAP_FIELD_LOGIN];
+ $fuser->pass = $ldapuser[$conf->global->LDAP_FIELD_PASSWORD];
+ $fuser->pass_indatabase_crypted = $ldapuser[$conf->global->LDAP_FIELD_PASSWORD_CRYPTED];
- //$user->societe;
+ // $user->societe;
/*
- $fuser->address=$ldapuser[$conf->global->LDAP_FIELD_ADDRESS];
- $fuser->zip=$ldapuser[$conf->global->LDAP_FIELD_ZIP];
- $fuser->town=$ldapuser[$conf->global->LDAP_FIELD_TOWN];
- $fuser->country=$ldapuser[$conf->global->LDAP_FIELD_COUNTRY];
- $fuser->country_id=$countries[$hashlib2rowid[strtolower($fuser->country)]]['rowid'];
- $fuser->country_code=$countries[$hashlib2rowid[strtolower($fuser->country)]]['code'];
- */
+ * $fuser->address=$ldapuser[$conf->global->LDAP_FIELD_ADDRESS];
+ * $fuser->zip=$ldapuser[$conf->global->LDAP_FIELD_ZIP];
+ * $fuser->town=$ldapuser[$conf->global->LDAP_FIELD_TOWN];
+ * $fuser->country=$ldapuser[$conf->global->LDAP_FIELD_COUNTRY];
+ * $fuser->country_id=$countries[$hashlib2rowid[strtolower($fuser->country)]]['rowid'];
+ * $fuser->country_code=$countries[$hashlib2rowid[strtolower($fuser->country)]]['code'];
+ */
- $fuser->office_phone=$ldapuser[$conf->global->LDAP_FIELD_PHONE];
- $fuser->user_mobile=$ldapuser[$conf->global->LDAP_FIELD_MOBILE];
- $fuser->office_fax=$ldapuser[$conf->global->LDAP_FIELD_FAX];
- $fuser->email=$ldapuser[$conf->global->LDAP_FIELD_MAIL];
- $fuser->ldap_sid=$ldapuser[$conf->global->LDAP_FIELD_SID];
+ $fuser->office_phone = $ldapuser[$conf->global->LDAP_FIELD_PHONE];
+ $fuser->user_mobile = $ldapuser[$conf->global->LDAP_FIELD_MOBILE];
+ $fuser->office_fax = $ldapuser[$conf->global->LDAP_FIELD_FAX];
+ $fuser->email = $ldapuser[$conf->global->LDAP_FIELD_MAIL];
+ $fuser->ldap_sid = $ldapuser[$conf->global->LDAP_FIELD_SID];
- $fuser->job=$ldapuser[$conf->global->LDAP_FIELD_TITLE];
- $fuser->note=$ldapuser[$conf->global->LDAP_FIELD_DESCRIPTION];
- $fuser->admin=0;
- $fuser->societe_id=0;
- $fuser->contact_id=0;
- $fuser->fk_member=0;
+ $fuser->job = $ldapuser[$conf->global->LDAP_FIELD_TITLE];
+ $fuser->note = $ldapuser[$conf->global->LDAP_FIELD_DESCRIPTION];
+ $fuser->admin = 0;
+ $fuser->societe_id = 0;
+ $fuser->contact_id = 0;
+ $fuser->fk_member = 0;
- $fuser->statut=1;
+ $fuser->statut = 1;
// TODO : revoir la gestion du 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->statut=$ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS];
- }*/
- //if ($fuser->statut > 1) $fuser->statut=1;
+ /*
+ * 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->statut=$ldapuser[$conf->global->LDAP_FIELD_MEMBER_STATUS];
+ * }
+ */
+ // if ($fuser->statut > 1) $fuser->statut=1;
- //print_r($ldapuser);
+ // print_r($ldapuser);
- if($fuser->id > 0) { // User update
- print $langs->transnoentities("UserUpdate").' # '.$key.': login='.$fuser->login.', fullname='.$fuser->getFullName($langs);
- $res=$fuser->update($user);
+ if ($fuser->id > 0) { // User update
+ print $langs->transnoentities("UserUpdate") . ' # ' . $key . ': login=' . $fuser->login . ', fullname=' . $fuser->getFullName($langs);
+ $res = $fuser->update($user);
- if ($res < 0)
- {
- $error++;
- print ' --> '.$res.' '.$fuser->error;
- }
- else
- {
- print ' --> Updated user id='.$fuser->id.' login='.$fuser->login;
+ if ($res < 0) {
+ $error ++;
+ print ' --> ' . $res . ' ' . $fuser->error;
+ } else {
+ print ' --> Updated user id=' . $fuser->id . ' login=' . $fuser->login;
}
} else { // User creation
- print $langs->transnoentities("UserCreate").' # '.$key.': login='.$fuser->login.', fullname='.$fuser->getFullName($langs);
- $res=$fuser->create($user);
+ print $langs->transnoentities("UserCreate") . ' # ' . $key . ': login=' . $fuser->login . ', fullname=' . $fuser->getFullName($langs);
+ $res = $fuser->create($user);
- if ($res > 0)
- {
- print ' --> Created user id='.$fuser->id.' login='.$fuser->login;
- }
- else
- {
- $error++;
- print ' --> '.$res.' '.$fuser->error;
+ if ($res > 0) {
+ print ' --> Created user id=' . $fuser->id . ' login=' . $fuser->login;
+ } else {
+ $error ++;
+ print ' --> ' . $res . ' ' . $fuser->error;
}
}
print "\n";
- //print_r($fuser);
+ // print_r($fuser);
// Gestion des groupes
// TODO : revoir la gestion des groupes (ou script de sync groupes)
- /*if(!$error) {
- foreach ($ldapuser[$conf->global->LDAP_FIELD_USERGROUPS] as $groupdn) {
- $groupdn;
- }
- }*/
+ /*
+ * if(!$error) {
+ * foreach ($ldapuser[$conf->global->LDAP_FIELD_USERGROUPS] as $groupdn) {
+ * $groupdn;
+ * }
+ * }
+ */
}
- if (! $error || $forcecommit)
- {
- if (! $error) print $langs->transnoentities("NoErrorCommitIsDone")."\n";
- else print $langs->transnoentities("ErrorButCommitIsDone")."\n";
+ if (! $error || $forcecommit) {
+ if (! $error)
+ print $langs->transnoentities("NoErrorCommitIsDone") . "\n";
+ else
+ print $langs->transnoentities("ErrorButCommitIsDone") . "\n";
$db->commit();
- }
- else
- {
- print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error)."\n";
+ } else {
+ print $langs->transnoentities("ErrorSomeErrorWereFoundRollbackIsDone", $error) . "\n";
$db->rollback();
}
print "\n";
- }
- else
- {
+ } else {
dol_print_error('', $ldap->error);
- $error++;
+ $error ++;
}
-}
-else
-{
+} else {
dol_print_error('', $ldap->error);
- $error++;
+ $error ++;
}
-
exit($error);
-
/**
* Function to say if a value is empty or not
*
- * @param string $element Value to test
- * @return boolean True of false
+ * @param string $element
+ * Value to test
+ * @return boolean True of false
*/
function dolValidElement($element)
{
diff --git a/scripts/withdrawals/build_withdrawal_file.php b/scripts/withdrawals/build_withdrawal_file.php
index c834847a272..a83fc7d7b22 100755
--- a/scripts/withdrawals/build_withdrawal_file.php
+++ b/scripts/withdrawals/build_withdrawal_file.php
@@ -1,8 +1,8 @@
#!/usr/bin/env php
- * Copyright (C) 2005-2010 Laurent Destailleur
+ * Copyright (C) 2005 Rodolphe Quiedeville
+ * Copyright (C) 2005-2010 Laurent Destailleur
*
* 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
@@ -11,7 +11,7 @@
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
@@ -19,39 +19,37 @@
*/
/**
- * \file scripts/withdrawals/build_withdrawal_file.php
- * \ingroup prelevement
- * \brief Script de prelevement
+ * \file scripts/withdrawals/build_withdrawal_file.php
+ * \ingroup prelevement
+ * \brief Script de prelevement
*/
-
$sapi_type = php_sapi_name();
$script_file = basename(__FILE__);
-$path=dirname(__FILE__).'/';
+$path = __DIR__ . '/';
// Test if batch mode
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";
- exit(-1);
+ 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);
}
-require_once $path."../../htdocs/master.inc.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."/societe/class/societe.class.php";
-require_once DOL_DOCUMENT_ROOT."/compta/paiement/class/paiement.class.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/facture/class/facture.class.php";
+require_once DOL_DOCUMENT_ROOT . "/societe/class/societe.class.php";
+require_once DOL_DOCUMENT_ROOT . "/compta/paiement/class/paiement.class.php";
// Global variables
-$version=DOL_VERSION;
-$error=0;
-
+$version = DOL_VERSION;
+$error = 0;
/*
* Main
*/
@set_time_limit(0);
-print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." *****\n";
-dol_syslog($script_file." launched with arg ".join(',', $argv));
+print "***** " . $script_file . " (" . $version . ") pid=" . dol_getmypid() . " *****\n";
+dol_syslog($script_file . " launched with arg " . join(',', $argv));
$datetimeprev = dol_now();
@@ -61,18 +59,16 @@ $year = strftime("%Y", $datetimeprev);
$user = new user($db);
$user->fetch($conf->global->PRELEVEMENT_USER);
-if (! isset($argv[1])) { // Check parameters
- print "This script check invoices with a withdrawal request and\n";
- print "then create payment and build a withdraw file.\n";
- print "Usage: ".$script_file." simu|real\n";
- exit(-1);
+if (! isset($argv[1])) { // Check parameters
+ print "This script check invoices with a withdrawal request and\n";
+ print "then create payment and build a withdraw file.\n";
+ print "Usage: " . $script_file . " simu|real\n";
+ exit(- 1);
}
-
-$withdrawreceipt=new BonPrelevement($db);
+$withdrawreceipt = new BonPrelevement($db);
// $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();