From f72ac3cf456d11b66c99bb38100ee3ab89e94fa0 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 22 May 2017 10:07:29 +0200 Subject: [PATCH 01/20] Fix php7 compatibility --- htdocs/api/class/api_documents.class.php | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/htdocs/api/class/api_documents.class.php b/htdocs/api/class/api_documents.class.php index 9794dad4a12..eb6380a19e4 100644 --- a/htdocs/api/class/api_documents.class.php +++ b/htdocs/api/class/api_documents.class.php @@ -49,20 +49,23 @@ class Documents extends DolibarrApi $this->db = $db; } + /** * Return a document * * @param string $module_part Module part for file * @param string $filename File name - * + * + * @url GET {module_part}/{filename} + * * @return array Array with data of file * @throws RestException */ - public function index($module_part, $filename) { - return array('note'=>'FeatureNotYetAvailable'); - } - - + public function get($module_part, $filename) { + return array('note'=>'FeatureNotYetAvailable'); + } + + /** * Push a file. * Test sample 1: { "filename": "mynewfile.txt", "modulepart": "facture", "ref": "FA1701-001", "subdir": "", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }. From 8301e24261a5c5660ed2d018dbe93c6f2028c7f3 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 22 May 2017 10:40:24 +0200 Subject: [PATCH 02/20] PHP7 compatibility --- htdocs/api/class/api.class.php | 3 +- htdocs/api/class/api_documents.class.php | 38 ++++++++++++------- .../bank/class/api_bankaccounts.class.php | 3 +- 3 files changed, 29 insertions(+), 15 deletions(-) diff --git a/htdocs/api/class/api.class.php b/htdocs/api/class/api.class.php index 082e6188379..190e24d326c 100644 --- a/htdocs/api/class/api.class.php +++ b/htdocs/api/class/api.class.php @@ -66,6 +66,7 @@ class DolibarrApi * * @return array */ + /* Disabled, most APIs does not share same signature for method index function index() { return array( @@ -74,7 +75,7 @@ class DolibarrApi 'message' => __class__.' is up and running!' ) ); - } + }*/ /** diff --git a/htdocs/api/class/api_documents.class.php b/htdocs/api/class/api_documents.class.php index eb6380a19e4..e26486981fa 100644 --- a/htdocs/api/class/api_documents.class.php +++ b/htdocs/api/class/api_documents.class.php @@ -36,8 +36,7 @@ class Documents extends DolibarrApi * @var array $DOCUMENT_FIELDS Mandatory fields, checked when create and update object */ static $DOCUMENT_FIELDS = array( - 'modulepart', - 'filename' + 'modulepart' ); /** @@ -49,23 +48,36 @@ class Documents extends DolibarrApi $this->db = $db; } - + /** - * Return a document + * Return list of documents. + * + * @param string $module_part Name of module or area concerned by file download ('facture', ...) + * @param string $ref Reference of object (This will define subdir automatically) + * @param string $subdir Subdirectory (Only if ref not provided) + * @return array List of documents * - * @param string $module_part Module part for file - * @param string $filename File name - * - * @url GET {module_part}/{filename} - * - * @return array Array with data of file * @throws RestException */ - public function get($module_part, $filename) { + public function index($module_part, $ref='', $subdir='') { return array('note'=>'FeatureNotYetAvailable'); } - - + + + /** + * Return a document. + * + * @param int $id ID of document + * @return array Array with data of file + * + * @throws RestException + */ + /* + public function get($id) { + return array('note'=>'xxx'); + }*/ + + /** * Push a file. * Test sample 1: { "filename": "mynewfile.txt", "modulepart": "facture", "ref": "FA1701-001", "subdir": "", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }. diff --git a/htdocs/compta/bank/class/api_bankaccounts.class.php b/htdocs/compta/bank/class/api_bankaccounts.class.php index 7eaf673c2e7..10994d7d525 100644 --- a/htdocs/compta/bank/class/api_bankaccounts.class.php +++ b/htdocs/compta/bank/class/api_bankaccounts.class.php @@ -98,7 +98,8 @@ class BankAccounts extends DolibarrApi if ($result) { $num = $this->db->num_rows($result); - for ($i = 0; $i < min($num, ($limit <= 0 ? $num : $limit)); $i++) { + $minnum = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $minnum; $i++) { $obj = $this->db->fetch_object($result); $account = new Account($this->db); if ($account->fetch($obj->rowid) > 0) { From f5e29d6c86ad885301fa96528baa4c853269e3d0 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 22 May 2017 10:45:02 +0200 Subject: [PATCH 03/20] Fix phpcs warning --- htdocs/categories/class/api_categories.class.php | 6 ++++-- htdocs/categories/class/api_deprecated_category.class.php | 6 ++++-- htdocs/comm/action/class/api_agendaevents.class.php | 3 ++- htdocs/comm/propal/class/api_proposals.class.php | 3 ++- htdocs/commande/class/api_deprecated_commande.class.php | 3 ++- htdocs/commande/class/api_orders.class.php | 3 ++- htdocs/compta/bank/class/api_bankaccounts.class.php | 4 ++-- .../compta/facture/class/api_deprecated_invoice.class.php | 3 ++- htdocs/compta/facture/class/api_invoices.class.php | 3 ++- htdocs/expensereport/class/api_expensereports.class.php | 3 ++- htdocs/fourn/class/api_supplier_invoices.class.php | 3 ++- htdocs/product/class/api_deprecated_product.class.php | 6 ++++-- htdocs/product/class/api_products.class.php | 3 ++- htdocs/product/stock/class/api_stockmovements.class.php | 3 ++- htdocs/product/stock/class/api_warehouses.class.php | 3 ++- htdocs/projet/class/api_projects.class.php | 3 ++- htdocs/projet/class/api_tasks.class.php | 3 ++- htdocs/societe/class/api_contacts.class.php | 3 ++- htdocs/societe/class/api_deprecated_contact.class.php | 3 ++- htdocs/societe/class/api_deprecated_thirdparty.class.php | 3 ++- htdocs/societe/class/api_thirdparties.class.php | 3 ++- htdocs/user/class/api_users.class.php | 3 ++- 22 files changed, 50 insertions(+), 26 deletions(-) diff --git a/htdocs/categories/class/api_categories.class.php b/htdocs/categories/class/api_categories.class.php index a08abdfc545..fc7aca368f4 100644 --- a/htdocs/categories/class/api_categories.class.php +++ b/htdocs/categories/class/api_categories.class.php @@ -146,7 +146,8 @@ class Categories extends DolibarrApi { $i=0; $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $category_static = new Categorie($db); @@ -232,7 +233,8 @@ class Categories extends DolibarrApi { $i=0; $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $category_static = new Categorie($db); diff --git a/htdocs/categories/class/api_deprecated_category.class.php b/htdocs/categories/class/api_deprecated_category.class.php index 271f2900502..efbcac82124 100644 --- a/htdocs/categories/class/api_deprecated_category.class.php +++ b/htdocs/categories/class/api_deprecated_category.class.php @@ -147,7 +147,8 @@ class CategoryApi extends DolibarrApi { $i=0; $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $category_static = new Categorie($db); @@ -228,7 +229,8 @@ class CategoryApi extends DolibarrApi { $i=0; $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $category_static = new Categorie($db); diff --git a/htdocs/comm/action/class/api_agendaevents.class.php b/htdocs/comm/action/class/api_agendaevents.class.php index 5eeca63a4aa..376df238a95 100644 --- a/htdocs/comm/action/class/api_agendaevents.class.php +++ b/htdocs/comm/action/class/api_agendaevents.class.php @@ -147,7 +147,8 @@ class AgendaEvents extends DolibarrApi if ($result) { $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $actioncomm_static = new ActionComm($db); diff --git a/htdocs/comm/propal/class/api_proposals.class.php b/htdocs/comm/propal/class/api_proposals.class.php index fd508b03256..190f6cdca87 100644 --- a/htdocs/comm/propal/class/api_proposals.class.php +++ b/htdocs/comm/propal/class/api_proposals.class.php @@ -148,7 +148,8 @@ class Proposals extends DolibarrApi if ($result) { $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $propal_static = new Propal($db); diff --git a/htdocs/commande/class/api_deprecated_commande.class.php b/htdocs/commande/class/api_deprecated_commande.class.php index aa1584c4fed..c0b3a634825 100644 --- a/htdocs/commande/class/api_deprecated_commande.class.php +++ b/htdocs/commande/class/api_deprecated_commande.class.php @@ -163,7 +163,8 @@ class CommandeApi extends DolibarrApi { $i=0; $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $commande_static = new Commande($db); diff --git a/htdocs/commande/class/api_orders.class.php b/htdocs/commande/class/api_orders.class.php index 81a2ad79d69..1bd4e44a877 100644 --- a/htdocs/commande/class/api_orders.class.php +++ b/htdocs/commande/class/api_orders.class.php @@ -152,7 +152,8 @@ class Orders extends DolibarrApi if ($result) { $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $commande_static = new Commande($db); diff --git a/htdocs/compta/bank/class/api_bankaccounts.class.php b/htdocs/compta/bank/class/api_bankaccounts.class.php index 10994d7d525..98ee2672d3b 100644 --- a/htdocs/compta/bank/class/api_bankaccounts.class.php +++ b/htdocs/compta/bank/class/api_bankaccounts.class.php @@ -98,8 +98,8 @@ class BankAccounts extends DolibarrApi if ($result) { $num = $this->db->num_rows($result); - $minnum = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $minnum; $i++) { + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { $obj = $this->db->fetch_object($result); $account = new Account($this->db); if ($account->fetch($obj->rowid) > 0) { diff --git a/htdocs/compta/facture/class/api_deprecated_invoice.class.php b/htdocs/compta/facture/class/api_deprecated_invoice.class.php index b638a46b920..36aa232de9e 100644 --- a/htdocs/compta/facture/class/api_deprecated_invoice.class.php +++ b/htdocs/compta/facture/class/api_deprecated_invoice.class.php @@ -161,7 +161,8 @@ class InvoiceApi extends DolibarrApi { $i=0; $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $invoice_static = new Facture($db); diff --git a/htdocs/compta/facture/class/api_invoices.class.php b/htdocs/compta/facture/class/api_invoices.class.php index 4efc997cc42..e2842df0530 100644 --- a/htdocs/compta/facture/class/api_invoices.class.php +++ b/htdocs/compta/facture/class/api_invoices.class.php @@ -155,7 +155,8 @@ class Invoices extends DolibarrApi { $i=0; $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $invoice_static = new Facture($db); diff --git a/htdocs/expensereport/class/api_expensereports.class.php b/htdocs/expensereport/class/api_expensereports.class.php index 03ecb51de79..763b550d34e 100644 --- a/htdocs/expensereport/class/api_expensereports.class.php +++ b/htdocs/expensereport/class/api_expensereports.class.php @@ -134,7 +134,8 @@ class ExpenseReports extends DolibarrApi if ($result) { $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $expensereport_static = new ExpenseReport($db); diff --git a/htdocs/fourn/class/api_supplier_invoices.class.php b/htdocs/fourn/class/api_supplier_invoices.class.php index 3bf5c3f5934..1eb1872126c 100644 --- a/htdocs/fourn/class/api_supplier_invoices.class.php +++ b/htdocs/fourn/class/api_supplier_invoices.class.php @@ -155,7 +155,8 @@ class SupplierInvoices extends DolibarrApi { $i = 0; $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $invoice_static = new FactureFournisseur($db); diff --git a/htdocs/product/class/api_deprecated_product.class.php b/htdocs/product/class/api_deprecated_product.class.php index e2ee97e0100..e33c7dd3e32 100644 --- a/htdocs/product/class/api_deprecated_product.class.php +++ b/htdocs/product/class/api_deprecated_product.class.php @@ -149,7 +149,8 @@ class ProductApi extends DolibarrApi { $i=0; $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $product_static = new Product($db); @@ -235,7 +236,8 @@ class ProductApi extends DolibarrApi { $i=0; $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $product_static = new Product($db); diff --git a/htdocs/product/class/api_products.class.php b/htdocs/product/class/api_products.class.php index 14885532952..a733a554fd5 100644 --- a/htdocs/product/class/api_products.class.php +++ b/htdocs/product/class/api_products.class.php @@ -146,7 +146,8 @@ class Products extends DolibarrApi if ($result) { $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $product_static = new Product($db); diff --git a/htdocs/product/stock/class/api_stockmovements.class.php b/htdocs/product/stock/class/api_stockmovements.class.php index 677d34d9fcb..79e17749991 100644 --- a/htdocs/product/stock/class/api_stockmovements.class.php +++ b/htdocs/product/stock/class/api_stockmovements.class.php @@ -133,7 +133,8 @@ class StockMovements extends DolibarrApi { $i=0; $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $stockmovement_static = new MouvementStock($db); diff --git a/htdocs/product/stock/class/api_warehouses.class.php b/htdocs/product/stock/class/api_warehouses.class.php index d09c7bc527f..d50f590c30c 100644 --- a/htdocs/product/stock/class/api_warehouses.class.php +++ b/htdocs/product/stock/class/api_warehouses.class.php @@ -131,7 +131,8 @@ class Warehouses extends DolibarrApi { $i=0; $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $warehouse_static = new Entrepot($db); diff --git a/htdocs/projet/class/api_projects.class.php b/htdocs/projet/class/api_projects.class.php index 5bb7e8dfc7e..0f4f85c05af 100644 --- a/htdocs/projet/class/api_projects.class.php +++ b/htdocs/projet/class/api_projects.class.php @@ -153,7 +153,8 @@ class Projects extends DolibarrApi if ($result) { $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $project_static = new Project($db); diff --git a/htdocs/projet/class/api_tasks.class.php b/htdocs/projet/class/api_tasks.class.php index ad72a36fa45..d2d7b81d865 100644 --- a/htdocs/projet/class/api_tasks.class.php +++ b/htdocs/projet/class/api_tasks.class.php @@ -160,7 +160,8 @@ class Tasks extends DolibarrApi if ($result) { $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $task_static = new Task($db); diff --git a/htdocs/societe/class/api_contacts.class.php b/htdocs/societe/class/api_contacts.class.php index de50799e430..02c1410fcbf 100644 --- a/htdocs/societe/class/api_contacts.class.php +++ b/htdocs/societe/class/api_contacts.class.php @@ -153,7 +153,8 @@ class Contacts extends DolibarrApi if ($result) { $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $contact_static = new Contact($db); diff --git a/htdocs/societe/class/api_deprecated_contact.class.php b/htdocs/societe/class/api_deprecated_contact.class.php index 196a1386b5d..8cb61fa3eb0 100644 --- a/htdocs/societe/class/api_deprecated_contact.class.php +++ b/htdocs/societe/class/api_deprecated_contact.class.php @@ -167,7 +167,8 @@ class ContactApi extends DolibarrApi { $i = 0; $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $contact_static = new Contact($db); diff --git a/htdocs/societe/class/api_deprecated_thirdparty.class.php b/htdocs/societe/class/api_deprecated_thirdparty.class.php index 96a2ebac321..a8146f4cca6 100644 --- a/htdocs/societe/class/api_deprecated_thirdparty.class.php +++ b/htdocs/societe/class/api_deprecated_thirdparty.class.php @@ -214,7 +214,8 @@ class ThirdpartyApi extends DolibarrApi { $i = 0; $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $soc_static = new Societe($db); diff --git a/htdocs/societe/class/api_thirdparties.class.php b/htdocs/societe/class/api_thirdparties.class.php index f8e96d82e47..df7965d6d8c 100644 --- a/htdocs/societe/class/api_thirdparties.class.php +++ b/htdocs/societe/class/api_thirdparties.class.php @@ -156,7 +156,8 @@ class Thirdparties extends DolibarrApi if ($result) { $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $soc_static = new Societe($db); diff --git a/htdocs/user/class/api_users.class.php b/htdocs/user/class/api_users.class.php index 80065f8d8d2..aa2569fb3ca 100644 --- a/htdocs/user/class/api_users.class.php +++ b/htdocs/user/class/api_users.class.php @@ -106,7 +106,8 @@ class Users extends DolibarrApi if ($result) { $num = $db->num_rows($result); - while ($i < min($num, ($limit <= 0 ? $num : $limit))) + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { $obj = $db->fetch_object($result); $user_static = new User($db); From 82560b912614a139b60ab0e6d9168d123d213478 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 22 May 2017 10:58:20 +0200 Subject: [PATCH 04/20] Look and feel v6 --- htdocs/adherents/card.php | 2 +- htdocs/adherents/subscription.php | 2 +- htdocs/langs/en_US/main.lang | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/adherents/card.php b/htdocs/adherents/card.php index 270430c899f..1234f75e059 100644 --- a/htdocs/adherents/card.php +++ b/htdocs/adherents/card.php @@ -1273,7 +1273,7 @@ else */ $head = member_prepare_head($object); - dol_fiche_head($head, 'general', $langs->trans("Member"), 0, 'user'); + dol_fiche_head($head, 'general', $langs->trans("Member"), -1, 'user'); // Confirm create user if ($action == 'create_user') diff --git a/htdocs/adherents/subscription.php b/htdocs/adherents/subscription.php index 658cdfee323..1874a0b37a7 100644 --- a/htdocs/adherents/subscription.php +++ b/htdocs/adherents/subscription.php @@ -578,7 +578,7 @@ if ($rowid > 0) print ''; print ''; - dol_fiche_head($head, 'subscription', $langs->trans("Member"), 0, 'user'); + dol_fiche_head($head, 'subscription', $langs->trans("Member"), -1, 'user'); $linkback = ''.$langs->trans("BackToList").''; diff --git a/htdocs/langs/en_US/main.lang b/htdocs/langs/en_US/main.lang index 01aa5537c13..77b5af78f81 100644 --- a/htdocs/langs/en_US/main.lang +++ b/htdocs/langs/en_US/main.lang @@ -762,7 +762,7 @@ Calendar=Calendar GroupBy=Group by... ViewFlatList=View flat list RemoveString=Remove string '%s' -SomeTranslationAreUncomplete=Some languages may be partially translated or may contains errors. If you detect some, you can fix language files registering to http://transifex.com/projects/p/dolibarr/. +SomeTranslationAreUncomplete=Some languages may be partially translated or may contains errors. If you detect some, you can fix language files registering to https://transifex.com/projects/p/dolibarr/. DirectDownloadLink=Direct download link Download=Download ActualizeCurrency=Update currency rate From 1a8884bbbee037f128875d5d138a98571b0be2f9 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 22 May 2017 15:20:52 +0200 Subject: [PATCH 05/20] NEW Can filter on year and product tags on the product statistic page --- htdocs/categories/class/categorie.class.php | 26 +- htdocs/core/class/html.form.class.php | 2 +- htdocs/langs/en_US/other.lang | 24 +- htdocs/product/ajax/products.php | 4 +- htdocs/product/card.php | 3 +- htdocs/product/class/product.class.php | 57 +- htdocs/product/composition/card.php | 81 ++- htdocs/product/list.php | 68 +- htdocs/product/stats/card.php | 631 +++++++++--------- htdocs/product/stats/commande.php | 2 +- htdocs/product/stats/commande_fournisseur.php | 2 +- htdocs/product/stats/contrat.php | 2 +- htdocs/product/stats/facture.php | 2 +- htdocs/product/stats/facture_fournisseur.php | 2 +- htdocs/product/stats/propal.php | 2 +- 15 files changed, 500 insertions(+), 408 deletions(-) diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index 518c3faa683..142cc22fe75 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -792,11 +792,12 @@ class Categorie extends CommonObject /** * Return list of fetched instance of elements having this category * - * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member') - * - * @return mixed -1 if KO, array of instance of object if OK + * @param string $type Type of category ('customer', 'supplier', 'contact', 'product', 'member') + * @param int $onlyids Return only ids of objects (consume less memory) + * @return mixed -1 if KO, array of instance of object if OK + * @see containsObject */ - function getObjectsInCateg($type) + function getObjectsInCateg($type, $onlyids=0) { $objs = array(); @@ -813,10 +814,18 @@ class Categorie extends CommonObject $resql = $this->db->query($sql); if ($resql) { - while ($rec = $this->db->fetch_array($resql)) { - $obj = new $this->MAP_OBJ_CLASS[$type]( $this->db ); - $obj->fetch( $rec['fk_' . $this->MAP_CAT_FK[$type]]); - $objs[] = $obj; + while ($rec = $this->db->fetch_array($resql)) + { + if ($onlyids) + { + $objs[] = $rec['fk_' . $this->MAP_CAT_FK[$type]]; + } + else + { + $obj = new $this->MAP_OBJ_CLASS[$type]( $this->db ); + $obj->fetch( $rec['fk_' . $this->MAP_CAT_FK[$type]]); + $objs[] = $obj; + } } return $objs; } @@ -834,6 +843,7 @@ class Categorie extends CommonObject * @param int $object_id id of the object to search * * @return int number of occurrences + * @see getObjectsInCateg */ function containsObject($type, $object_id ) { diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index f58e96087b8..561504f7845 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -4783,7 +4783,7 @@ class Form { $retstring.=''; - for ($year = $syear - 5; $year < $syear + 10 ; $year++) + for ($year = $syear - 10; $year < $syear + 10 ; $year++) { $retstring.=''; } diff --git a/htdocs/langs/en_US/other.lang b/htdocs/langs/en_US/other.lang index 11a09af3373..02fa209c340 100644 --- a/htdocs/langs/en_US/other.lang +++ b/htdocs/langs/en_US/other.lang @@ -160,18 +160,18 @@ ProfIdShortDesc=Prof Id %s is an information depending on third party cou DolibarrDemo=Dolibarr ERP/CRM demo StatsByNumberOfUnits=Statistics in number of products/services units StatsByNumberOfEntities=Statistics in number of referring entities -NumberOfProposals=Number of proposals in past 12 months -NumberOfCustomerOrders=Number of customer orders in past 12 months -NumberOfCustomerInvoices=Number of customer invoices in past 12 months -NumberOfSupplierProposals=Number of supplier proposals in past 12 months -NumberOfSupplierOrders=Number of supplier orders in past 12 months -NumberOfSupplierInvoices=Number of supplier invoices in past 12 months -NumberOfUnitsProposals=Number of units on proposals in past 12 months -NumberOfUnitsCustomerOrders=Number of units on customer orders in past 12 months -NumberOfUnitsCustomerInvoices=Number of units on customer invoices in past 12 months -NumberOfUnitsSupplierProposals=Number of units on supplier proposals in past 12 months -NumberOfUnitsSupplierOrders=Number of units on supplier orders in past 12 months -NumberOfUnitsSupplierInvoices=Number of units on supplier invoices in past 12 months +NumberOfProposals=Number of proposals +NumberOfCustomerOrders=Number of customer orders +NumberOfCustomerInvoices=Number of customer invoices +NumberOfSupplierProposals=Number of supplier proposals +NumberOfSupplierOrders=Number of supplier orders +NumberOfSupplierInvoices=Number of supplier invoices +NumberOfUnitsProposals=Number of units on proposals +NumberOfUnitsCustomerOrders=Number of units on customer orders +NumberOfUnitsCustomerInvoices=Number of units on customer invoices +NumberOfUnitsSupplierProposals=Number of units on supplier proposals +NumberOfUnitsSupplierOrders=Number of units on supplier orders +NumberOfUnitsSupplierInvoices=Number of units on supplier invoices EMailTextInterventionAddedContact=A newintervention %s has been assigned to you. EMailTextInterventionValidated=The intervention %s has been validated. EMailTextInvoiceValidated=The invoice %s has been validated. diff --git a/htdocs/product/ajax/products.php b/htdocs/product/ajax/products.php index 0510299fbd7..8867011101b 100644 --- a/htdocs/product/ajax/products.php +++ b/htdocs/product/ajax/products.php @@ -178,11 +178,11 @@ else $idprod = (! empty($match[0]) ? $match[0] : ''); - if (! GETPOST($htmlname) && ! GETPOST($idprod)) + if (! $htmlname && (! $idprod || ! GETPOST($idprod,'alpha'))) return; // When used from jQuery, the search term is added as GET param "term". - $searchkey = (GETPOST($idprod) ? GETPOST($idprod) : (GETPOST($htmlname) ? GETPOST($htmlname) : '')); + $searchkey = (($idprod && GETPOST($idprod,'alpha')) ? GETPOST($idprod,'alpha') : (GETPOST($htmlname, 'alpha') ? GETPOST($htmlname, 'alpha') : '')); $form = new Form($db); if (empty($mode) || $mode == 1) { // mode=1: customer diff --git a/htdocs/product/card.php b/htdocs/product/card.php index 71f7cd8e7f6..7cd86404afa 100644 --- a/htdocs/product/card.php +++ b/htdocs/product/card.php @@ -1448,7 +1448,8 @@ else $head=product_prepare_head($object); $titre=$langs->trans("CardProduct".$object->type); $picto=($object->type== Product::TYPE_SERVICE?'service':'product'); - dol_fiche_head($head, 'card', $titre, 0, $picto); + + dol_fiche_head($head, 'card', $titre, -1, $picto); $linkback = ''.$langs->trans("BackToList").''; $object->next_prev_filter=" fk_product_type = ".$object->type; diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php index 1225eb82696..d866e3ec2ae 100644 --- a/htdocs/product/class/product.class.php +++ b/htdocs/product/class/product.class.php @@ -2459,9 +2459,10 @@ class Product extends CommonObject * * @param string $sql Request to execute * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities + * @param int $year Year (0=current year) * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11 */ - function _get_stats($sql,$mode) + function _get_stats($sql, $mode, $year=0) { $resql = $this->db->query($sql); if ($resql) @@ -2482,8 +2483,15 @@ class Product extends CommonObject return -1; } - $year = strftime('%Y',time()); - $month = strftime('%m',time()); + if (empty($year)) + { + $year = strftime('%Y',time()); + $month = strftime('%m',time()); + } + else + { + $month=12; // We imagine we are at end of year, so we get last 12 month before, so all correct year. + } $result = array(); for ($j = 0 ; $j < 12 ; $j++) @@ -2516,9 +2524,11 @@ class Product extends CommonObject * @param int $socid Limit count on a particular third party id * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only + * @param int $year Year (0=last 12 month) + * @param string $morefilter More sql filters * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11 */ - function get_nb_vente($socid, $mode, $filteronproducttype=-1) + function get_nb_vente($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='') { global $conf; global $user; @@ -2536,10 +2546,11 @@ class Product extends CommonObject $sql.= " AND f.entity IN (".getEntity('facture', 1).")"; if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; if ($socid > 0) $sql.= " AND f.fk_soc = $socid"; + $sql.=$morefilter; $sql.= " GROUP BY date_format(f.datef,'%Y%m')"; $sql.= " ORDER BY date_format(f.datef,'%Y%m') DESC"; - return $this->_get_stats($sql,$mode); + return $this->_get_stats($sql,$mode, $year); } @@ -2549,9 +2560,11 @@ class Product extends CommonObject * @param int $socid Limit count on a particular third party id * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only + * @param int $year Year (0=last 12 month) + * @param string $morefilter More sql filters * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11 */ - function get_nb_achat($socid, $mode, $filteronproducttype=-1) + function get_nb_achat($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='') { global $conf; global $user; @@ -2569,11 +2582,11 @@ class Product extends CommonObject $sql.= " AND f.entity IN (".getEntity('facture_fourn', 1).")"; if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; if ($socid > 0) $sql.= " AND f.fk_soc = $socid"; + $sql.=$morefilter; $sql.= " GROUP BY date_format(f.datef,'%Y%m')"; $sql.= " ORDER BY date_format(f.datef,'%Y%m') DESC"; - $resarray=$this->_get_stats($sql,$mode); - return $resarray; + return $this->_get_stats($sql,$mode, $year); } /** @@ -2582,9 +2595,11 @@ class Product extends CommonObject * @param int $socid Limit count on a particular third party id * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only + * @param int $year Year (0=last 12 month) + * @param string $morefilter More sql filters * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11 */ - function get_nb_propal($socid, $mode, $filteronproducttype=-1) + function get_nb_propal($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='') { global $conf; global $user; @@ -2602,10 +2617,11 @@ class Product extends CommonObject $sql.= " AND p.entity IN (".getEntity('propal', 1).")"; if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; if ($socid > 0) $sql.= " AND p.fk_soc = ".$socid; + $sql.=$morefilter; $sql.= " GROUP BY date_format(p.datep,'%Y%m')"; $sql.= " ORDER BY date_format(p.datep,'%Y%m') DESC"; - return $this->_get_stats($sql,$mode); + return $this->_get_stats($sql,$mode, $year); } /** @@ -2614,9 +2630,11 @@ class Product extends CommonObject * @param int $socid Limit count on a particular third party id * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only + * @param int $year Year (0=last 12 month) + * @param string $morefilter More sql filters * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11 */ - function get_nb_propalsupplier($socid, $mode, $filteronproducttype=-1) + function get_nb_propalsupplier($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='') { global $conf; global $user; @@ -2634,10 +2652,11 @@ class Product extends CommonObject $sql.= " AND p.entity IN (".getEntity('propal', 1).")"; if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; if ($socid > 0) $sql.= " AND p.fk_soc = ".$socid; + $sql.=$morefilter; $sql.= " GROUP BY date_format(p.date_valid,'%Y%m')"; $sql.= " ORDER BY date_format(p.date_valid,'%Y%m') DESC"; - return $this->_get_stats($sql,$mode); + return $this->_get_stats($sql,$mode, $year); } /** @@ -2646,9 +2665,11 @@ class Product extends CommonObject * @param int $socid Limit count on a particular third party id * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only + * @param int $year Year (0=last 12 month) + * @param string $morefilter More sql filters * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11 */ - function get_nb_order($socid, $mode, $filteronproducttype=-1) + function get_nb_order($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='') { global $conf, $user; @@ -2665,10 +2686,11 @@ class Product extends CommonObject $sql.= " AND c.entity IN (".getEntity('commande', 1).")"; if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; if ($socid > 0) $sql.= " AND c.fk_soc = ".$socid; + $sql.=$morefilter; $sql.= " GROUP BY date_format(c.date_commande,'%Y%m')"; $sql.= " ORDER BY date_format(c.date_commande,'%Y%m') DESC"; - return $this->_get_stats($sql,$mode); + return $this->_get_stats($sql,$mode, $year); } /** @@ -2677,9 +2699,11 @@ class Product extends CommonObject * @param int $socid Limit count on a particular third party id * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only + * @param int $year Year (0=last 12 month) + * @param string $morefilter More sql filters * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11 */ - function get_nb_ordersupplier($socid, $mode, $filteronproducttype=-1) + function get_nb_ordersupplier($socid, $mode, $filteronproducttype=-1, $year=0, $morefilter='') { global $conf, $user; @@ -2696,10 +2720,11 @@ class Product extends CommonObject $sql.= " AND c.entity IN (".getEntity('supplier_order', 1).")"; if (!$user->rights->societe->client->voir && !$socid) $sql.= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = " .$user->id; if ($socid > 0) $sql.= " AND c.fk_soc = ".$socid; + $sql.=$morefilter; $sql.= " GROUP BY date_format(c.date_commande,'%Y%m')"; $sql.= " ORDER BY date_format(c.date_commande,'%Y%m') DESC"; - return $this->_get_stats($sql,$mode); + return $this->_get_stats($sql,$mode, $year); } /** diff --git a/htdocs/product/composition/card.php b/htdocs/product/composition/card.php index 37068a1daca..aa1cf4137e9 100644 --- a/htdocs/product/composition/card.php +++ b/htdocs/product/composition/card.php @@ -193,7 +193,7 @@ llxHeader('', $title, $helpurl); $head=product_prepare_head($object); $titre=$langs->trans("CardProduct".$object->type); $picto=($object->type==Product::TYPE_SERVICE?'service':'product'); -dol_fiche_head($head, 'subproduct', $titre, 0, $picto); +dol_fiche_head($head, 'subproduct', $titre, -1, $picto); if ($id > 0 || ! empty($ref)) @@ -209,48 +209,47 @@ if ($id > 0 || ! empty($ref)) if ($object->type!=Product::TYPE_SERVICE || empty($conf->global->PRODUIT_MULTIPRICES)) { + print '
'; print '
'; print ''; - } - // Nature - if ($object->type!=Product::TYPE_SERVICE) - { - print ''; - } + // Nature + if ($object->type!=Product::TYPE_SERVICE) + { + print ''; + } + + if (empty($conf->global->PRODUIT_MULTIPRICES)) + { + // Price + print ''; + + // Price minimum + print ''; + } - if (empty($conf->global->PRODUIT_MULTIPRICES)) - { - // Price - print ''; - - // Price minimum - print ''; - } - - if ($object->type!=Product::TYPE_SERVICE || empty($conf->global->PRODUIT_MULTIPRICES)) - { - print '
'.$langs->trans("Nature").''; - print $object->getLibFinished(); - print '
'.$langs->trans("Nature").''; + print $object->getLibFinished(); + print '
'.$langs->trans("SellingPrice").''; + if ($object->price_base_type == 'TTC') + { + print price($object->price_ttc).' '.$langs->trans($object->price_base_type); + } + else + { + print price($object->price).' '.$langs->trans($object->price_base_type?$object->price_base_type:'HT'); + } + print '
'.$langs->trans("MinPrice").''; + if ($object->price_base_type == 'TTC') + { + print price($object->price_min_ttc).' '.$langs->trans($object->price_base_type); + } + else + { + print price($object->price_min).' '.$langs->trans($object->price_base_type?$object->price_base_type:'HT'); + } + print '
'.$langs->trans("SellingPrice").''; - if ($object->price_base_type == 'TTC') - { - print price($object->price_ttc).' '.$langs->trans($object->price_base_type); - } - else - { - print price($object->price).' '.$langs->trans($object->price_base_type?$object->price_base_type:'HT'); - } - print '
'.$langs->trans("MinPrice").''; - if ($object->price_base_type == 'TTC') - { - print price($object->price_min_ttc).' '.$langs->trans($object->price_base_type); - } - else - { - print price($object->price_min).' '.$langs->trans($object->price_base_type?$object->price_base_type:'HT'); - } - print '
'; + print ''; + print '
'; } dol_fiche_end(); @@ -271,7 +270,7 @@ if ($id > 0 || ! empty($ref)) //if (count($prodsfather) > 0) //{ - print load_fiche_titre($langs->trans("ProductParentList"),'','').'
'; + print load_fiche_titre($langs->trans("ProductParentList"),'',''); print ''; print ''; print ''; @@ -320,7 +319,7 @@ if ($id > 0 || ! empty($ref)) //if (count($prods_arbo) > 0) //{ $atleastonenotdefined=0; - print load_fiche_titre($langs->trans("ProductAssociationList"),'','').'
'; + print load_fiche_titre($langs->trans("ProductAssociationList"),'',''); print ''; print ''; diff --git a/htdocs/product/list.php b/htdocs/product/list.php index 7e6ae9b47f4..74f9c59cff3 100644 --- a/htdocs/product/list.php +++ b/htdocs/product/list.php @@ -55,6 +55,7 @@ $sall=GETPOST('sall', 'alphanohtml'); $sref=GETPOST("sref"); $sbarcode=GETPOST("sbarcode"); $snom=GETPOST("snom"); +$search_type = GETPOST("search_type",'int'); $search_sale = GETPOST("search_sale"); $search_categ = GETPOST("search_categ",'int'); $tosell = GETPOST("tosell", 'int'); @@ -65,7 +66,7 @@ $search_tobatch = GETPOST("search_tobatch",'int'); $search_accountancy_code_sell = GETPOST("search_accountancy_code_sell",'alpha'); $search_accountancy_code_buy = GETPOST("search_accountancy_code_buy",'alpha'); $optioncss = GETPOST('optioncss','alpha'); -$type= (int) GETPOST("type","int"); +$type=(int) GETPOST("type","int"); //Show/hide child products. Hidden by default if (!$_POST) { @@ -114,8 +115,8 @@ if (! empty($canvas)) } // Security check -if ($type=='0') $result=restrictedArea($user,'produit','','','','','',$objcanvas); -else if ($type=='1') $result=restrictedArea($user,'service','','','','','',$objcanvas); +if ($search_type=='0') $result=restrictedArea($user,'produit','','','','','',$objcanvas); +else if ($search_type=='1') $result=restrictedArea($user,'service','','','','','',$objcanvas); else $result=restrictedArea($user,'produit|service','','','','','',$objcanvas); // Define virtualdiffersfromphysical @@ -158,7 +159,8 @@ $arrayfields=array( 'p.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), //'pfp.ref_fourn'=>array('label'=>$langs->trans("RefSupplier"), 'checked'=>1, 'enabled'=>(! empty($conf->barcode->enabled))), 'p.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), - 'p.barcode'=>array('label'=>$langs->trans("Gencod"), 'checked'=>($contextpage != 'servicelist'), 'enabled'=>(! empty($conf->barcode->enabled))), + 'p.fk_product_type'=>array('label'=>$langs->trans("Type"), 'checked'=>0, 'enabled'=>(! empty($conf->produit->enabled) && ! empty($conf->service->enabled))), + 'p.barcode'=>array('label'=>$langs->trans("Gencod"), 'checked'=>($contextpage != 'servicelist'), 'enabled'=>(! empty($conf->barcode->enabled))), 'p.duration'=>array('label'=>$langs->trans("Duration"), 'checked'=>($contextpage != 'productlist'), 'enabled'=>(! empty($conf->service->enabled))), 'p.sellprice'=>array('label'=>$langs->trans("SellingPrice"), 'checked'=>1, 'enabled'=>empty($conf->global->PRODUIT_MULTIPRICES)), 'p.minbuyprice'=>array('label'=>$langs->trans("BuyingPriceMinShort"), 'checked'=>1, 'enabled'=>(! empty($user->rights->fournisseur->lire))), @@ -212,6 +214,7 @@ if (empty($reshook)) $tosell=""; $tobuy=""; $search_tobatch=''; + $search_type=''; $search_accountancy_code_sell=''; $search_accountancy_code_buy=''; $search_array_options=array(); @@ -219,8 +222,8 @@ if (empty($reshook)) // Mass actions $objectclass='Product'; - if ((string) $type == '1') { $objectlabel='Services'; } - if ((string) $type == '0') { $objectlabel='Products'; } + if ((string) $search_type == '1') { $objectlabel='Services'; } + if ((string) $search_type == '0') { $objectlabel='Products'; } $permtoread = $user->rights->produit->lire; $permtodelete = $user->rights->produit->supprimer; @@ -244,9 +247,9 @@ else { $title=$langs->trans("ProductsAndServices"); - if (isset($type)) + if ($search_type != '' && $search_type != '-1') { - if ($type==1) + if ($search_type==1) { $texte = $langs->trans("Services"); } @@ -260,13 +263,13 @@ else $texte = $langs->trans("ProductsAndServices"); } - $sql = 'SELECT DISTINCT p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,'; + $sql = 'SELECT DISTINCT p.rowid, p.ref, p.label, p.fk_product_type, p.barcode, p.price, p.price_ttc, p.price_base_type, p.entity,'; $sql.= ' p.fk_product_type, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock,'; $sql.= ' p.tobatch, p.accountancy_code_sell, p.accountancy_code_buy,'; $sql.= ' p.datec as date_creation, p.tms as date_update,'; //$sql.= ' pfp.ref_fourn as ref_supplier, '; $sql.= ' MIN(pfp.unitprice) as minsellprice'; - if (!empty($conf->variants->enabled) && $search_hidechildproducts && ($type === 0)) { + if (!empty($conf->variants->enabled) && $search_hidechildproducts && ($search_type === 0)) { $sql .= ', pac.rowid prod_comb_id'; } // Add fields from extrafields @@ -281,17 +284,17 @@ else $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product"; // multilang if (! empty($conf->global->MAIN_MULTILANGS)) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang = '".$langs->getDefaultLang() ."'"; - if (!empty($conf->variants->enabled) && $search_hidechildproducts && ($type === 0)) { + if (!empty($conf->variants->enabled) && $search_hidechildproducts && ($search_type === 0)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid"; } $sql.= ' WHERE p.entity IN ('.getEntity('product', 1).')'; if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); // if the type is not 1, we show all products (type = 0,2,3) - if (dol_strlen($type)) + if (dol_strlen($search_type) && $search_type != '-1') { - if ($type == 1) $sql.= " AND p.fk_product_type = '1'"; - else $sql.= " AND p.fk_product_type <> '1'"; + if ($search_type == 1) $sql.= " AND p.fk_product_type = 1"; + else $sql.= " AND p.fk_product_type <> 1"; } if ($sref) $sql .= natural_search('p.ref', $sref); if ($snom) $sql .= natural_search('p.label', $snom); @@ -309,7 +312,7 @@ else if ($search_accountancy_code_sell) $sql.= natural_search('p.accountancy_code_buy', $search_accountancy_code_buy); // Add where from extra fields - if (!empty($conf->variants->enabled) && $search_hidechildproducts && ($type === 0)) { + if (!empty($conf->variants->enabled) && $search_hidechildproducts && ($search_type === 0)) { $sql .= " AND pac.rowid IS NULL"; } @@ -333,7 +336,7 @@ else $sql.= " GROUP BY p.rowid, p.ref, p.label, p.barcode, p.price, p.price_ttc, p.price_base_type,"; $sql.= " p.fk_product_type, p.duration, p.tosell, p.tobuy, p.seuil_stock_alerte, p.desiredstock,"; $sql.= ' p.datec, p.tms, p.entity, p.tobatch, p.accountancy_code_sell, p.accountancy_code_buy'; - if (!empty($conf->variants->enabled) && $search_hidechildproducts && ($type === 0)) { + if (!empty($conf->variants->enabled) && $search_hidechildproducts && ($search_type === 0)) { $sql .= ', pac.rowid'; } // Add fields from extrafields @@ -368,13 +371,13 @@ else } $helpurl=''; - if (isset($type)) + if ($search_type != '') { - if ($type == 0) + if ($search_type == 0) { $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; } - else if ($type == 1) + else if ($search_type == 1) { $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; } @@ -401,7 +404,8 @@ else if ($fourn_id > 0) $param.=($fourn_id?"&fourn_id=".$fourn_id:""); if ($seach_categ) $param.=($search_categ?"&search_categ=".urlencode($search_categ):""); if ($type != '') $param.='&type='.urlencode($type); - if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); + if ($search_type != '') $param.='&search_type='.urlencode($search_type); + if ($optioncss != '') $param.='&optioncss='.urlencode($optioncss); if ($search_tobatch) $param="&search_ref_supplier=".urlencode($search_ref_supplier); if ($search_accountancy_code_sell) $param="&search_accountancy_code_sell=".urlencode($search_accountancy_code_sell); if ($search_accountancy_code_buy) $param="&search_accountancy_code_buy=".urlencode($search_accountancy_code_buy); @@ -430,7 +434,8 @@ else print ''; print ''; print ''; - print ''; + print ''; + if (empty($arrayfields['p.fk_product_type']['checked'])) print ''; print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_products.png', 0, '', '', $limit); @@ -480,7 +485,7 @@ else } //Show/hide child products. Hidden by default - if (!empty($conf->variants->enabled) && $type === 0) { + if (!empty($conf->variants->enabled) && $search_type === 0) { $moreforfilter.='
'; $moreforfilter.= ''; $moreforfilter.= ' '; @@ -524,6 +529,14 @@ else print ''; print ''; } + // Type + if (! empty($arrayfields['p.fk_product_type']['checked'])) + { + print '
'; + } // Barcode if (! empty($arrayfields['p.barcode']['checked'])) { @@ -622,6 +635,7 @@ else if (! empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"],"p.ref","",$param,"",$sortfield,$sortorder); if (! empty($arrayfields['pfp.ref_fourn']['checked'])) print_liste_field_titre($arrayfields['pfp.ref_fourn']['label'], $_SERVER["PHP_SELF"],"pfp.ref_fourn","",$param,"",$sortfield,$sortorder); if (! empty($arrayfields['p.label']['checked'])) print_liste_field_titre($arrayfields['p.label']['label'], $_SERVER["PHP_SELF"],"p.label","",$param,"",$sortfield,$sortorder); + if (! empty($arrayfields['p.fk_product_type']['checked'])) print_liste_field_titre($arrayfields['p.fk_product_type']['label'], $_SERVER["PHP_SELF"],"p.fk_product_type","",$param,"",$sortfield,$sortorder); if (! empty($arrayfields['p.barcode']['checked'])) print_liste_field_titre($arrayfields['p.barcode']['label'], $_SERVER["PHP_SELF"],"p.barcode","",$param,"",$sortfield,$sortorder); if (! empty($arrayfields['p.duration']['checked'])) print_liste_field_titre($arrayfields['p.duration']['label'], $_SERVER["PHP_SELF"],"p.duration","",$param,'align="center"',$sortfield,$sortorder); if (! empty($arrayfields['p.sellprice']['checked'])) print_liste_field_titre($arrayfields['p.sellprice']['label'], $_SERVER["PHP_SELF"],"","",$param,'align="right"',$sortfield,$sortorder); @@ -690,7 +704,7 @@ else $product_static->status = $obj->tosell; $product_static->entity = $obj->entity; - if (! empty($conf->stock->enabled) && $user->rights->stock->lire && $type != 1) // To optimize call of load_stock + if (! empty($conf->stock->enabled) && $user->rights->stock->lire && $search_type != 1) // To optimize call of load_stock { if ($obj->fk_product_type != 1) // Not a service { @@ -721,7 +735,13 @@ else print ''; } - // Barcode + // Type + if (! empty($arrayfields['p.fk_product_type']['checked'])) + { + print ''; + } + + // Barcode if (! empty($arrayfields['p.barcode']['checked'])) { print ''; diff --git a/htdocs/product/stats/card.php b/htdocs/product/stats/card.php index d0a85756c04..0477491518c 100644 --- a/htdocs/product/stats/card.php +++ b/htdocs/product/stats/card.php @@ -1,6 +1,6 @@ - * Copyright (c) 2004-2015 Laurent Destailleur + * Copyright (c) 2004-2017 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2005 Eric Seigne * Copyright (C) 2013 Juanjo Menent @@ -30,6 +30,8 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; +require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; $WIDTH=DolGraph::getDefaultGraphSizeForStats('width',380); $HEIGHT=DolGraph::getDefaultGraphSizeForStats('height',160); @@ -43,6 +45,9 @@ $langs->load("other"); $id = GETPOST('id','int'); // For this page, id can also be 'all' $ref = GETPOST('ref'); $mode = (GETPOST('mode') ? GETPOST('mode') : 'byunit'); +$search_year = GETPOST('search_year','int'); +$search_categ = GETPOST('search_categ','int'); + $error = 0; $mesg = ''; $graphfiles=array(); @@ -55,348 +60,380 @@ $fieldvalue = (! empty($id) ? $id : $ref); $fieldtype = (! empty($ref) ? 'ref' : 'rowid'); $result=restrictedArea($user,'produit|service',$fieldvalue,'product&product','','',$fieldtype); +$tmp=dol_getdate(dol_now()); +$currentyear=$tmp['year']; +if (empty($search_year)) $search_year=$currentyear; + + +/* + * Actions + */ + +// None + /* * View */ $form = new Form($db); +$htmlother = new FormOther($db); -if (! empty($id) || ! empty($ref) || GETPOST('id') == 'all') +$object = new Product($db); +if (! $id) { - $object = new Product($db); - if (GETPOST('id') == 'all') + llxHeader("",$langs->trans("ProductStatistics")); + + $type = GETPOST('type','int'); + + $helpurl=''; + if ($type == '0') { - llxHeader("",$langs->trans("ProductStatistics")); - - $type = GETPOST('type'); - - $helpurl=''; - if ($type == '0') - { - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; - //$title=$langs->trans("StatisticsOfProducts"); - $title=$langs->trans("Statistics"); - } - else if ($type == '1') - { - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; - //$title=$langs->trans("StatisticsOfServices"); - $title=$langs->trans("Statistics"); - } - else - { - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; - //$title=$langs->trans("StatisticsOfProductsOrServices"); - $title=$langs->trans("Statistics"); - } - - print load_fiche_titre($title, $mesg,'title_products.png'); + $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + //$title=$langs->trans("StatisticsOfProducts"); + $title=$langs->trans("Statistics"); + } + else if ($type == '1') + { + $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + //$title=$langs->trans("StatisticsOfServices"); + $title=$langs->trans("Statistics"); } else { - $result = $object->fetch($id,$ref); - - $title = $langs->trans('ProductServiceCard'); - $helpurl = ''; - $shortlabel = dol_trunc($object->label,16); - if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) - { - $title = $langs->trans('Product')." ". $shortlabel ." - ".$langs->trans('Statistics'); - $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; - } - if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) - { - $title = $langs->trans('Service')." ". $shortlabel ." - ".$langs->trans('Statistics'); - $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; - } - - llxHeader('', $title, $helpurl); + $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + //$title=$langs->trans("StatisticsOfProductsOrServices"); + $title=$langs->trans("Statistics"); } + print load_fiche_titre($title, $mesg,'title_products.png'); +} +else +{ + $result = $object->fetch($id,$ref); - if ($result && (! empty($id) || ! empty($ref))) + $title = $langs->trans('ProductServiceCard'); + $helpurl = ''; + $shortlabel = dol_trunc($object->label,16); + if (GETPOST("type") == '0' || ($object->type == Product::TYPE_PRODUCT)) { - $head=product_prepare_head($object); - $titre=$langs->trans("CardProduct".$object->type); - $picto=($object->type==Product::TYPE_SERVICE?'service':'product'); + $title = $langs->trans('Product')." ". $shortlabel ." - ".$langs->trans('Statistics'); + $helpurl='EN:Module_Products|FR:Module_Produits|ES:Módulo_Productos'; + } + if (GETPOST("type") == '1' || ($object->type == Product::TYPE_SERVICE)) + { + $title = $langs->trans('Service')." ". $shortlabel ." - ".$langs->trans('Statistics'); + $helpurl='EN:Module_Services_En|FR:Module_Services|ES:Módulo_Servicios'; + } - dol_fiche_head($head, 'stats', $titre, 0, $picto); + llxHeader('', $title, $helpurl); +} - $linkback = ''.$langs->trans("BackToList").''; + +if ($result && (! empty($id) || ! empty($ref))) +{ + $head=product_prepare_head($object); + $titre=$langs->trans("CardProduct".$object->type); + $picto=($object->type==Product::TYPE_SERVICE?'service':'product'); + + dol_fiche_head($head, 'stats', $titre, -1, $picto); + + $linkback = ''.$langs->trans("BackToList").''; + + dol_banner_tab($object, 'ref', $linkback, ($user->societe_id?0:1), 'ref', '', '', '', 0, '', '', 1); + + dol_fiche_end(); +} +if (empty($id) & empty($ref)) +{ + $h=0; + $head = array(); + + $head[$h][0] = DOL_URL_ROOT.'/product/stats/card.php'.($type != ''?'?type='.$type:''); + $head[$h][1] = $langs->trans("Chart"); + $head[$h][2] = 'chart'; + $h++; + + $title = $langs->trans("ListProductServiceByPopularity"); + if ((string) $type == '1') { + $title = $langs->trans("ListServiceByPopularity"); + } + if ((string) $type == '0') { + $title = $langs->trans("ListProductByPopularity"); + } + + $head[$h][0] = DOL_URL_ROOT.'/product/popuprop.php'.($type != ''?'?type='.$type:''); + $head[$h][1] = $title; + $head[$h][2] = 'popularityprop'; + $h++; + + dol_fiche_head($head, 'chart', $langs->trans("Statistics"), -1); +} + + +if ($result || empty($id)) +{ + print ''; + print ''; + + print '
'.$langs->trans('ParentProducts').'
'; + $array=array('-1'=>' ', '0'=>$langs->trans('Product'), '1'=>$langs->trans('Service')); + print $form->selectarray('search_type', $array, $search_type); + print ''.dol_trunc($obj->label,40).''.$obj->fk_product_type.''.$obj->barcode.'
'; + print ''; + + if (empty($id)) + { + // Type + print ''; - dol_banner_tab($object, 'ref', $linkback, ($user->societe_id?0:1), 'ref', '', '', '', 0, '', '', 1); - - dol_fiche_end(); - } - if (GETPOST('id') == 'all') - { - $h=0; - $head = array(); - - $head[$h][0] = DOL_URL_ROOT.'/product/stats/card.php?id=all'; - $head[$h][1] = $langs->trans("Chart"); - $head[$h][2] = 'chart'; - $h++; - - $title = $langs->trans("ListProductServiceByPopularity"); - if ((string) $type == '1') { - $title = $langs->trans("ListServiceByPopularity"); - } - if ((string) $type == '0') { - $title = $langs->trans("ListProductByPopularity"); - } - - $head[$h][0] = DOL_URL_ROOT.'/product/popuprop.php'.($type != ''?'?type='.$type:''); - $head[$h][1] = $title; - $head[$h][2] = 'popularityprop'; - $h++; - - dol_fiche_head($head,'chart',$langs->trans("Statistics")); - } - - - if ($result || GETPOST('id') == 'all') - { - if (GETPOST('id') == 'all') - { - // Choice of type of product - if (! empty($conf->dol_use_jmobile)) print "\n".'
'."\n".'
'."\n"; - else print '   /   '; - - if ((string) $type != '1') print 'id).'&type=1'.($mode?'&mode='.$mode:'').'">'; - else print img_picto('','tick').' '; - print $langs->trans("Services"); - if ((string) $type != '1') print ''; - - if (! empty($conf->dol_use_jmobile)) print '
'."\n".'
'."\n"; - else print '   /   '; - - if ((string) $type == '0' || (string) $type == '1') print 'id).($mode?'&mode='.$mode:'').'">'; - else print img_picto('','tick').' '; - print $langs->trans("ProductsAndServices"); - if ((string) $type == '0' || (string) $type == '1') print ''; - - if (! empty($conf->dol_use_jmobile)) print '
'; - else print '
'; - print '
'; - } - - // Choice of stats mode (byunit or bynumber) - if (! empty($conf->dol_use_jmobile)) print "\n".''; - else print '
'; - print '
'; - - //print '
'.$langs->trans("Filter").'
'.$langs->trans("ProductsAndServices").''; + $array=array('-1'=>' ', '0'=>$langs->trans('Product'), '1'=>$langs->trans('Service')); + print $form->selectarray('type', $array, $type); + print '
'; - - // Generation des graphs - $dir = (! empty($conf->product->multidir_temp[$object->entity])?$conf->product->multidir_temp[$object->entity]:$conf->service->multidir_temp[$object->entity]); - if ($object->id > 0) // We are on statistics for a dedicated product - { - if (! file_exists($dir.'/'.$object->id)) + // Tag + if ($conf->categorie->enabled) { - if (dol_mkdir($dir.'/'.$object->id) < 0) - { - $mesg = $langs->trans("ErrorCanNotCreateDir",$dir); - $error++; - } + print ''; } - } - - if($conf->propal->enabled) { - $graphfiles['propal']=array('modulepart'=>'productstats_proposals', - 'file' => $object->id.'/propal12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.'.png', - 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsProposals"):$langs->transnoentitiesnoconv("NumberOfProposals"))); - } - - if($conf->supplier_proposal->enabled) { - $graphfiles['proposalssuppliers']=array('modulepart'=>'productstats_proposalssuppliers', - 'file' => $object->id.'/proposalssuppliers12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.'.png', - 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsSupplierProposals"):$langs->transnoentitiesnoconv("NumberOfSupplierProposals"))); - } - - if($conf->order->enabled) { - $graphfiles['orders']=array('modulepart'=>'productstats_orders', - 'file' => $object->id.'/orders12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.'.png', - 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsCustomerOrders"):$langs->transnoentitiesnoconv("NumberOfCustomerOrders"))); - } - - if($conf->fournisseur->enabled) { - $graphfiles['orderssuppliers']=array('modulepart'=>'productstats_orderssuppliers', - 'file' => $object->id.'/orderssuppliers12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.'.png', - 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsSupplierOrders"):$langs->transnoentitiesnoconv("NumberOfSupplierOrders"))); - } - - if($conf->facture->enabled) { - $graphfiles['invoices']=array('modulepart'=>'productstats_invoices', - 'file' => $object->id.'/invoices12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.'.png', - 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsCustomerInvoices"):$langs->transnoentitiesnoconv("NumberOfCustomerInvoices"))); - - $graphfiles['invoicessuppliers']=array('modulepart'=>'productstats_invoicessuppliers', - 'file' => $object->id.'/invoicessuppliers12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.'.png', - 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsSupplierInvoices"):$langs->transnoentitiesnoconv("NumberOfSupplierInvoices"))); - } - - $px = new DolGraph(); - - if (! $error && count($graphfiles)>0) + } + + // Year + print ''; + print '
'.$langs->trans("Categories").''; + //$moreforfilter.='
'; + $moreforfilter.=$htmlother->select_categories(Categorie::TYPE_PRODUCT,$search_categ,'search_categ',1); + //$moreforfilter.='
'; + print $moreforfilter; + print '
'.$langs->trans("Year").''; + $arrayyears=array(); + for ($year = $currentyear - 10; $year < $currentyear + 10 ; $year++) { - $mesg = $px->isGraphKo(); - if (! $mesg) - { - foreach($graphfiles as $key => $val) - { - if (! $graphfiles[$key]['file']) continue; - - $graph_data = array(); - - if (dol_is_file($dir . '/' . $graphfiles[$key]['file'])) - { - // TODO Load cachefile $graphfiles[$key]['file'] - } - else - { - if ($key == 'propal') $graph_data = $object->get_nb_propal($socid,$mode,((string) $type != '' ? $type : -1)); - if ($key == 'orders') $graph_data = $object->get_nb_order($socid,$mode,((string) $type != '' ? $type : -1)); - if ($key == 'invoices') $graph_data = $object->get_nb_vente($socid,$mode,((string) $type != '' ? $type : -1)); - if ($key == 'proposalssuppliers') $graph_data = $object->get_nb_propalsupplier($socid,$mode,((string) $type != '' ? $type : -1)); - if ($key == 'invoicessuppliers') $graph_data = $object->get_nb_achat($socid,$mode,((string) $type != '' ? $type : -1)); - if ($key == 'orderssuppliers') $graph_data = $object->get_nb_ordersupplier($socid,$mode,((string) $type != '' ? $type : -1)); - - // TODO Save cachefile $graphfiles[$key]['file'] - } - - if (is_array($graph_data)) - { - $px->SetData($graph_data); - $px->SetYLabel($graphfiles[$key]['label']); - $px->SetMaxValue($px->GetCeilMaxValue()<0?0:$px->GetCeilMaxValue()); - $px->SetMinValue($px->GetFloorMinValue()>0?0:$px->GetFloorMinValue()); - $px->SetWidth($WIDTH); - $px->SetHeight($HEIGHT); - $px->SetHorizTickIncrement(1); - $px->SetPrecisionY(0); - $px->SetShading(3); - //print 'x '.$key.' '.$graphfiles[$key]['file']; - - $url=DOL_URL_ROOT.'/viewimage.php?modulepart='.$graphfiles[$key]['modulepart'].'&entity='.$object->entity.'&file='.urlencode($graphfiles[$key]['file']); - $px->draw($dir."/".$graphfiles[$key]['file'],$url); - - $graphfiles[$key]['output']=$px->show(); - } - else - { - dol_print_error($db,'Error for calculating graph on key='.$key.' - '.$object->error); - } - } - } - - $mesg = $langs->trans("ChartGenerated"); + $arrayyears[$year]=$year; } + if (! in_array($year,$arrayyears)) $arrayyears[$year]=$year; + if (! in_array($nowyear,$arrayyears)) $arrayyears[$nowyear]=$nowyear; + arsort($arrayyears); + print $form->selectarray('search_year',$arrayyears,$search_year,0); + print '
'; + print '
'; + print ''; + + print '
'; + - // Show graphs - $i=0; - if ( count($graphfiles)>0) + // Choice of stats mode (byunit or bynumber) + if (! empty($conf->dol_use_jmobile)) print "\n".''; + else print '
'; + print '
'; + + //print ''; + + // Generation des graphs + $dir = (! empty($conf->product->multidir_temp[$object->entity])?$conf->product->multidir_temp[$object->entity]:$conf->service->multidir_temp[$object->entity]); + if ($object->id > 0) // We are on statistics for a dedicated product + { + if (! file_exists($dir.'/'.$object->id)) + { + if (dol_mkdir($dir.'/'.$object->id) < 0) + { + $mesg = $langs->trans("ErrorCanNotCreateDir",$dir); + $error++; + } + } + } + + if($conf->propal->enabled) { + $graphfiles['propal']=array('modulepart'=>'productstats_proposals', + 'file' => $object->id.'/propal12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year?'_year'.$search_year:'').'.png', + 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsProposals"):$langs->transnoentitiesnoconv("NumberOfProposals"))); + } + + if($conf->supplier_proposal->enabled) { + $graphfiles['proposalssuppliers']=array('modulepart'=>'productstats_proposalssuppliers', + 'file' => $object->id.'/proposalssuppliers12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year?'_year'.$search_year:'').'.png', + 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsSupplierProposals"):$langs->transnoentitiesnoconv("NumberOfSupplierProposals"))); + } + + if($conf->order->enabled) { + $graphfiles['orders']=array('modulepart'=>'productstats_orders', + 'file' => $object->id.'/orders12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year?'_year'.$search_year:'').'.png', + 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsCustomerOrders"):$langs->transnoentitiesnoconv("NumberOfCustomerOrders"))); + } + + if($conf->fournisseur->enabled) { + $graphfiles['orderssuppliers']=array('modulepart'=>'productstats_orderssuppliers', + 'file' => $object->id.'/orderssuppliers12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year?'_year'.$search_year:'').'.png', + 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsSupplierOrders"):$langs->transnoentitiesnoconv("NumberOfSupplierOrders"))); + } + + if($conf->facture->enabled) { + $graphfiles['invoices']=array('modulepart'=>'productstats_invoices', + 'file' => $object->id.'/invoices12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year?'_year'.$search_year:'').'.png', + 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsCustomerInvoices"):$langs->transnoentitiesnoconv("NumberOfCustomerInvoices"))); + + $graphfiles['invoicessuppliers']=array('modulepart'=>'productstats_invoicessuppliers', + 'file' => $object->id.'/invoicessuppliers12m'.((string) $type != '' ? '_type'.$type : '').'_'.$mode.($search_year?'_year'.$search_year:'').'.png', + 'label' => ($mode=='byunit'?$langs->transnoentitiesnoconv("NumberOfUnitsSupplierInvoices"):$langs->transnoentitiesnoconv("NumberOfSupplierInvoices"))); + } + + $px = new DolGraph(); + + if (! $error && count($graphfiles)>0) + { + $mesg = $px->isGraphKo(); + if (! $mesg) { foreach($graphfiles as $key => $val) { if (! $graphfiles[$key]['file']) continue; - - if ($graphfiles == 'propal' && ! $user->rights->propale->lire) continue; - if ($graphfiles == 'order' && ! $user->rights->commande->lire) continue; - if ($graphfiles == 'invoices' && ! $user->rights->facture->lire) continue; - if ($graphfiles == 'proposals_suppliers' && ! $user->rights->supplier_proposal->lire) continue; - if ($graphfiles == 'invoices_suppliers' && ! $user->rights->fournisseur->facture->lire) continue; - if ($graphfiles == 'orders_suppliers' && ! $user->rights->fournisseur->commande->lire) continue; - - - if ($i % 2 == 0) + + $graph_data = array(); + + if (dol_is_file($dir . '/' . $graphfiles[$key]['file'])) { - print "\n".'
'."\n"; + // TODO Load cachefile $graphfiles[$key]['file'] } else { - print "\n".'
'."\n"; + $morefilters=''; + if ($search_categ > 0) + { + $categ=new Categorie($db); + $categ->fetch($search_categ); + $listofprodids = $categ->getObjectsInCateg('product', 1); + $morefilters=' AND d.fk_product IN ('.((is_array($listofprodids) && count($listofprodids)) ? join(',',$listofprodids):'0').')'; + } + if ($search_categ == -2) + { + $morefilters=' AND d.fk_product NOT IN (SELECT cp.fk_product from '.MAIN_DB_PREFIX.'categorie_product as cp)'; + } + + if ($key == 'propal') $graph_data = $object->get_nb_propal($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); + if ($key == 'orders') $graph_data = $object->get_nb_order($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); + if ($key == 'invoices') $graph_data = $object->get_nb_vente($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); + if ($key == 'proposalssuppliers') $graph_data = $object->get_nb_propalsupplier($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); + if ($key == 'invoicessuppliers') $graph_data = $object->get_nb_achat($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); + if ($key == 'orderssuppliers') $graph_data = $object->get_nb_ordersupplier($socid, $mode, ((string) $type != '' ? $type : -1), $search_year, $morefilters); + + // TODO Save cachefile $graphfiles[$key]['file'] } - - // Date generation - if ($graphfiles[$key]['output'] && ! $px->isGraphKo()) + + if (is_array($graph_data)) { - if (file_exists($dir."/".$graphfiles[$key]['file']) && filemtime($dir."/".$graphfiles[$key]['file'])) $dategenerated=$langs->trans("GeneratedOn",dol_print_date(filemtime($dir."/".$graphfiles[$key]['file']),"dayhour")); - else $dategenerated=$langs->trans("GeneratedOn",dol_print_date(dol_now(),"dayhour")); + $px->SetData($graph_data); + $px->SetYLabel($graphfiles[$key]['label']); + $px->SetMaxValue($px->GetCeilMaxValue()<0?0:$px->GetCeilMaxValue()); + $px->SetMinValue($px->GetFloorMinValue()>0?0:$px->GetFloorMinValue()); + $px->SetWidth($WIDTH); + $px->SetHeight($HEIGHT); + $px->SetHorizTickIncrement(1); + $px->SetPrecisionY(0); + $px->SetShading(3); + //print 'x '.$key.' '.$graphfiles[$key]['file']; + + $url=DOL_URL_ROOT.'/viewimage.php?modulepart='.$graphfiles[$key]['modulepart'].'&entity='.$object->entity.'&file='.urlencode($graphfiles[$key]['file']); + $px->draw($dir."/".$graphfiles[$key]['file'],$url); + + $graphfiles[$key]['output']=$px->show(); } else { - print $dategenerated=($mesg?''.$mesg.'':$langs->trans("ChartNotGenerated")); + dol_print_error($db,'Error for calculating graph on key='.$key.' - '.$object->error); } - $linktoregenerate='id).((string) $type != ''?'&type='.$type:'').'&action=recalcul&mode='.$mode.'">'.img_picto($langs->trans("ReCalculate").' ('.$dategenerated.')','refresh').''; - - // Show graph - print '
'; - // Label - print ''; - print ''; - print ''; - // Image - print ''; - print '
'; - print $graphfiles[$key]['label']; - print ''.$linktoregenerate.'
'; - print $graphfiles[$key]['output']; - print '
'; - - if ($i % 2 == 0) - { - print "\n".''."\n"; - } - else - { - print "\n".''; - print '

'."\n"; - } - - $i++; } } - // div not closed - if ($i % 2 == 1) - { - print "\n".'
'."\n"; - print "\n".'
'; - print '

'."\n"; - } + + $mesg = $langs->trans("ChartGenerated"); } - if (GETPOST('id') == 'all') + // Show graphs + $i=0; + if ( count($graphfiles)>0) { - dol_fiche_end(); + foreach($graphfiles as $key => $val) + { + if (! $graphfiles[$key]['file']) continue; + + if ($graphfiles == 'propal' && ! $user->rights->propale->lire) continue; + if ($graphfiles == 'order' && ! $user->rights->commande->lire) continue; + if ($graphfiles == 'invoices' && ! $user->rights->facture->lire) continue; + if ($graphfiles == 'proposals_suppliers' && ! $user->rights->supplier_proposal->lire) continue; + if ($graphfiles == 'invoices_suppliers' && ! $user->rights->fournisseur->facture->lire) continue; + if ($graphfiles == 'orders_suppliers' && ! $user->rights->fournisseur->commande->lire) continue; + + + if ($i % 2 == 0) + { + print "\n".'
'."\n"; + } + else + { + print "\n".'
'."\n"; + } + + // Date generation + if ($graphfiles[$key]['output'] && ! $px->isGraphKo()) + { + if (file_exists($dir."/".$graphfiles[$key]['file']) && filemtime($dir."/".$graphfiles[$key]['file'])) $dategenerated=$langs->trans("GeneratedOn",dol_print_date(filemtime($dir."/".$graphfiles[$key]['file']),"dayhour")); + else $dategenerated=$langs->trans("GeneratedOn",dol_print_date(dol_now(),"dayhour")); + } + else + { + print $dategenerated=($mesg?''.$mesg.'':$langs->trans("ChartNotGenerated")); + } + $linktoregenerate='id).((string) $type != ''?'&type='.$type:'').'&action=recalcul&mode='.$mode.'&search_year='.$search_year.'&search_categ='.$search_categ.'">'.img_picto($langs->trans("ReCalculate").' ('.$dategenerated.')','refresh').''; + + // Show graph + print ''; + // Label + print ''; + print ''; + print ''; + // Image + print ''; + print '
'; + print $graphfiles[$key]['label']; + print ''.$linktoregenerate.'
'; + print $graphfiles[$key]['output']; + print '
'; + + if ($i % 2 == 0) + { + print "\n".'
'."\n"; + } + else + { + print "\n".'
'; + print '

'."\n"; + } + + $i++; + } + } + // div not closed + if ($i % 2 == 1) + { + print "\n".'
'."\n"; + print "\n".'
'; + print '

'."\n"; } } -else + +if (! $id) { - dol_print_error(); + dol_fiche_end(); } llxFooter(); diff --git a/htdocs/product/stats/commande.php b/htdocs/product/stats/commande.php index 341d002a1af..1c72d5f6615 100644 --- a/htdocs/product/stats/commande.php +++ b/htdocs/product/stats/commande.php @@ -94,7 +94,7 @@ if ($id > 0 || ! empty($ref)) $head=product_prepare_head($product); $titre=$langs->trans("CardProduct".$product->type); $picto=($product->type==Product::TYPE_SERVICE?'service':'product'); - dol_fiche_head($head, 'referers', $titre, 0, $picto); + dol_fiche_head($head, 'referers', $titre, -1, $picto); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$product,$action); // Note that $action and $object may have been modified by hook if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); diff --git a/htdocs/product/stats/commande_fournisseur.php b/htdocs/product/stats/commande_fournisseur.php index bed3be1892f..3201e7ed2e8 100644 --- a/htdocs/product/stats/commande_fournisseur.php +++ b/htdocs/product/stats/commande_fournisseur.php @@ -101,7 +101,7 @@ if ($id > 0 || ! empty($ref)) { $head = product_prepare_head($product); $titre = $langs->trans("CardProduct" . $product->type); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); - dol_fiche_head($head, 'referers', $titre, 0, $picto); + dol_fiche_head($head, 'referers', $titre, -1, $picto); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook if ($reshook < 0) diff --git a/htdocs/product/stats/contrat.php b/htdocs/product/stats/contrat.php index 6a8183ca7de..e2f5bccc430 100644 --- a/htdocs/product/stats/contrat.php +++ b/htdocs/product/stats/contrat.php @@ -84,7 +84,7 @@ if ($id > 0 || ! empty($ref)) $head=product_prepare_head($product); $titre=$langs->trans("CardProduct".$product->type); $picto=($product->type==Product::TYPE_SERVICE?'service':'product'); - dol_fiche_head($head, 'referers', $titre, 0, $picto); + dol_fiche_head($head, 'referers', $titre, -1, $picto); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$product,$action); // Note that $action and $object may have been modified by hook if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); diff --git a/htdocs/product/stats/facture.php b/htdocs/product/stats/facture.php index f0e5b0f13c4..506689a6001 100644 --- a/htdocs/product/stats/facture.php +++ b/htdocs/product/stats/facture.php @@ -111,7 +111,7 @@ if ($id > 0 || ! empty($ref)) $head=product_prepare_head($product); $titre=$langs->trans("CardProduct".$product->type); $picto=($product->type==Product::TYPE_SERVICE?'service':'product'); - dol_fiche_head($head, 'referers', $titre, 0, $picto); + dol_fiche_head($head, 'referers', $titre, -1, $picto); $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$product,$action); // Note that $action and $object may have been modified by hook if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); diff --git a/htdocs/product/stats/facture_fournisseur.php b/htdocs/product/stats/facture_fournisseur.php index 6fe189c7700..ac2849fefcf 100644 --- a/htdocs/product/stats/facture_fournisseur.php +++ b/htdocs/product/stats/facture_fournisseur.php @@ -96,7 +96,7 @@ if ($id > 0 || ! empty($ref)) $head = product_prepare_head($product); $titre = $langs->trans("CardProduct" . $product->type); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); - dol_fiche_head($head, 'referers', $titre, 0, $picto); + dol_fiche_head($head, 'referers', $titre, -1, $picto); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); diff --git a/htdocs/product/stats/propal.php b/htdocs/product/stats/propal.php index 289cf3d3578..06d43838bce 100644 --- a/htdocs/product/stats/propal.php +++ b/htdocs/product/stats/propal.php @@ -94,7 +94,7 @@ if ($id > 0 || ! empty($ref)) $head = product_prepare_head($product); $titre = $langs->trans("CardProduct" . $product->type); $picto = ($product->type == Product::TYPE_SERVICE ? 'service' : 'product'); - dol_fiche_head($head, 'referers', $titre, 0, $picto); + dol_fiche_head($head, 'referers', $titre, -1, $picto); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $product, $action); // Note that $action and $object may have been modified by hook if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); From 2b9f654b8cb4837a0c499ce6203c3d65b6e6c6d0 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 22 May 2017 15:31:05 +0200 Subject: [PATCH 06/20] Fix translation --- htdocs/langs/en_US/other.lang | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/langs/en_US/other.lang b/htdocs/langs/en_US/other.lang index 02fa209c340..280a1666b02 100644 --- a/htdocs/langs/en_US/other.lang +++ b/htdocs/langs/en_US/other.lang @@ -158,8 +158,8 @@ AuthenticationDoesNotAllowSendNewPassword=Authentication mode is %s.
Prof Id %s is an information depending on third party country.
For example, for country %s, it's code %s. DolibarrDemo=Dolibarr ERP/CRM demo -StatsByNumberOfUnits=Statistics in number of products/services units -StatsByNumberOfEntities=Statistics in number of referring entities +StatsByNumberOfUnits=Statistics for sum of qty of products/services +StatsByNumberOfEntities=Statistics in number of referring entities (nb of invoice, or order...) NumberOfProposals=Number of proposals NumberOfCustomerOrders=Number of customer orders NumberOfCustomerInvoices=Number of customer invoices From 0cd030d856357497860b1f64dd86399738afc65b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 23 May 2017 00:13:07 +0200 Subject: [PATCH 07/20] NEW Introduce mass actions on contacts --- htdocs/contact/list.php | 105 +++++++++++++++++++++++++++------------- htdocs/main.inc.php | 2 +- htdocs/societe/list.php | 10 ++-- 3 files changed, 79 insertions(+), 38 deletions(-) diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index fc601cf8a53..39557a6e455 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -32,8 +32,13 @@ require '../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; -$langs->load("companies"); -$langs->load("suppliers"); +$langs->loadLangs(array("companies", "suppliers")); + +$action=GETPOST('action','alpha'); +$massaction=GETPOST('massaction','alpha'); +$show_files=GETPOST('show_files','int'); +$confirm=GETPOST('confirm','alpha'); +$toselect = GETPOST('toselect', 'array'); // Security check $id = GETPOST('id','int'); @@ -177,7 +182,7 @@ if (empty($reshook)) // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - // Purge search criteria + // Did we click on purge search criteria ? if (GETPOST('button_removefilter_x') || GETPOST('button_removefilter.x') || GETPOST('button_removefilter')) // All tests are required to be compatible with all browsers { $sall=""; @@ -198,6 +203,7 @@ if (empty($reshook)) $search_categ=''; $search_categ_thirdparty=''; $search_categ_supplier=''; + $toselect=''; $search_array_options=array(); } @@ -205,7 +211,7 @@ if (empty($reshook)) $objectclass='Contact'; $objectlabel='Contact'; $permtoread = $user->rights->societe->lire; - $permtodelete = $user->rights->societe->delete; + $permtodelete = $user->rights->societe->supprimer; $uploaddir = $conf->societe->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } @@ -224,7 +230,7 @@ $contactstatic=new Contact($db); $title = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); $sql = "SELECT s.rowid as socid, s.nom as name,"; -$sql.= " p.rowid as cidp, p.lastname as lastname, p.statut, p.firstname, p.zip, p.town, p.poste, p.email, p.skype,"; +$sql.= " p.rowid, p.lastname as lastname, p.statut, p.firstname, p.zip, p.town, p.poste, p.email, p.skype,"; $sql.= " p.phone as phone_pro, p.phone_mobile, p.phone_perso, p.fax, p.fk_pays, p.priv, p.datec as date_creation, p.tms as date_update,"; $sql.= " co.code as country_code"; // Add fields from extrafields @@ -374,8 +380,6 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql.= $db->plimit($limit+1, $offset); -//print $sql; -dol_syslog("contact/list.php", LOG_DEBUG); $result = $db->query($sql); if (! $result) { @@ -385,15 +389,18 @@ if (! $result) $num = $db->num_rows($result); +$arrayofselected=is_array($toselect)?$toselect:array(); + if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) { $obj = $db->fetch_object($resql); - $id = $obj->cidp; + $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/contact/card.php?id='.$id); exit; } -llxHeader('',$title,'EN:Module_Third_Parties|FR:Module_Tiers|ES:Módulo_Empresas'); +$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Módulo_Empresas'; +llxHeader('',$title,$help_url); $param=''; if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.$contextpage; @@ -426,16 +433,26 @@ foreach ($search_array_options as $key => $val) if ($val != '') $param.='&search_options_'.$tmpkey.'='.urlencode($val); } -print '
'; +// List of mass actions available +$arrayofmassactions = array( +// 'presend'=>$langs->trans("SendByMail"), +// 'builddoc'=>$langs->trans("PDFMerge"), +); +//if($user->rights->societe->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); +if ($user->rights->societe->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete"); +if ($massaction == 'presend') $arrayofmassactions=array(); +$massactionbutton=$form->selectMassAction('', $arrayofmassactions); + +print ''; if ($optioncss != '') print ''; print ''; print ''; -print ''; print ''; print ''; print ''; +print ''; -print_barre_liste($titre, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies.png', 0, '', '', $limit); +print_barre_liste($titre, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_companies.png', 0, '', '', $limit); if ($sall) { @@ -447,6 +464,7 @@ if ($search_firstlast_only) print $langs->trans("FilterOnInto", $search_firstlast_only) . $langs->trans("Lastname").", ".$langs->trans("Firstname"); } +$moreforfilter=''; if (! empty($conf->categorie->enabled)) { require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php'; @@ -483,6 +501,7 @@ if ($moreforfilter) $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields +if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); print '
'; print ''."\n"; @@ -575,7 +594,18 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab { if (! empty($arrayfields["ef.".$key]['checked'])) { - print ''; } } @@ -596,15 +626,17 @@ if (! empty($arrayfields['p.tms']['checked'])) print ''; } +// Status if (! empty($arrayfields['p.statut']['checked'])) { print ''; } +// Action column print ''; print ''; @@ -656,7 +688,7 @@ while ($i < min($num,$limit)) $contactstatic->lastname=$obj->lastname; $contactstatic->firstname=''; - $contactstatic->id=$obj->cidp; + $contactstatic->id=$obj->rowid; $contactstatic->statut=$obj->statut; $contactstatic->poste=$obj->poste; $contactstatic->email=$obj->email; @@ -696,32 +728,32 @@ while ($i < min($num,$limit)) // Phone if (! empty($arrayfields['p.phone']['checked'])) { - print ''; + print ''; } // Phone perso if (! empty($arrayfields['p.phone_perso']['checked'])) { - print ''; + print ''; } // Phone mobile if (! empty($arrayfields['p.phone_mobile']['checked'])) { - print ''; + print ''; } // Fax if (! empty($arrayfields['p.fax']['checked'])) { - print ''; + print ''; } // EMail if (! empty($arrayfields['p.email']['checked'])) { - print ''; + print ''; } // Skype if (! empty($arrayfields['p.skype']['checked'])) { - if (! empty($conf->skype->enabled)) { print ''; } + if (! empty($conf->skype->enabled)) { print ''; } } // Company if (! empty($arrayfields['p.thirdparty']['checked'])) @@ -784,28 +816,35 @@ while ($i < min($num,$limit)) { print ''; } - // Action column - Links Add action and Export vcard - print ''; + // Action column + print ''; + if (! $i) $totalarray['nbfield']++; + print "\n"; $i++; } +$db->free($result); + +$parameters=array('arrayfields'=>$arrayfields, 'sql'=>$sql); +$reshook=$hookmanager->executeHooks('printFieldListFooter',$parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + print "
'; + $align=$extrafields->getAlignFlag($key); + $typeofextrafield=$extrafields->attribute_type[$key]; + print ''; + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + { + $crit=$val; + $tmpkey=preg_replace('/search_options_/','',$key); + $searchclass=''; + if (in_array($typeofextrafield, array('varchar', 'select'))) $searchclass='searchstring'; + if (in_array($typeofextrafield, array('int', 'double'))) $searchclass='searchnum'; + print ''; + } print ''; print ''; print $form->selectarray('search_status', array('-1'=>'', '0'=>$langs->trans('ActivityCeased'),'1'=>$langs->trans('InActivity')),$search_status); print ''; -print ''; -print ''; +$searchpicto=$form->showFilterButtons(); +print $searchpicto; print '
'.dol_print_phone($obj->phone_pro,$obj->country_code,$obj->cidp,$obj->socid,'AC_TEL').''.dol_print_phone($obj->phone_pro,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').''.dol_print_phone($obj->phone_perso,$obj->country_code,$obj->cidp,$obj->socid,'AC_TEL').''.dol_print_phone($obj->phone_perso,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').''.dol_print_phone($obj->phone_mobile,$obj->country_code,$obj->cidp,$obj->socid,'AC_TEL').''.dol_print_phone($obj->phone_mobile,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').''.dol_print_phone($obj->fax,$obj->country_code,$obj->cidp,$obj->socid,'AC_TEL').''.dol_print_phone($obj->fax,$obj->country_code,$obj->rowid,$obj->socid,'AC_TEL').''.dol_print_email($obj->email,$obj->cidp,$obj->socid,'AC_EMAIL',18).''.dol_print_email($obj->email,$obj->rowid,$obj->socid,'AC_EMAIL',18).''.dol_print_skype($obj->skype,$obj->cidp,$obj->socid,'AC_SKYPE',18).''.dol_print_skype($obj->skype,$obj->rowid,$obj->socid,'AC_SKYPE',18).''.$contactstatic->getLibStatut(3).''; - /*print ''.img_object($langs->trans("AddAction"),"action").''; - print '   '; - print ''; - print img_picto($langs->trans("VCard"),'vcard.png').' '; - print ''; */ - print ''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected=0; + if (in_array($obj->rowid, $arrayofselected)) $selected=1; + print ''; + } + print '
"; print "
"; -if ($num > $limit || $page) print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies.png', 0, '', '', $limit, 1); +//if ($num > $limit || $page) print_barre_liste('', $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_companies.png', 0, '', '', $limit, 1); print '
'; -$db->free($result); - llxFooter(); $db->close(); diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php index 73f0a815413..e674aea6d5c 100644 --- a/htdocs/main.inc.php +++ b/htdocs/main.inc.php @@ -859,7 +859,7 @@ if (! defined('NOLOGIN')) } -dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]); +dol_syslog("--- Access to ".$_SERVER["PHP_SELF"].' - action='.GETPOST('action','az09').', massaction='.GETPOST('massaction','az09')); //Another call for easy debugg //dol_syslog("Access to ".$_SERVER["PHP_SELF"].' GET='.join(',',array_keys($_GET)).'->'.join(',',$_GET).' POST:'.join(',',array_keys($_POST)).'->'.join(',',$_POST)); diff --git a/htdocs/societe/list.php b/htdocs/societe/list.php index 40ca07783c4..48e1b67a69c 100644 --- a/htdocs/societe/list.php +++ b/htdocs/societe/list.php @@ -187,6 +187,8 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab } } +$object = new Societe($db); + /* * Actions @@ -196,7 +198,7 @@ if (GETPOST('cancel')) { $action='list'; $massaction=''; } if (! GETPOST('confirmmassaction') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction=''; } $parameters=array(); -$reshook=$hookmanager->executeHooks('doActions',$parameters); // Note that $action and $object may have been modified by some hooks +$reshook=$hookmanager->executeHooks('doActions',$parameters, $object, $action); // Note that $action and $object may have been modified by some hooks if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); if (empty($reshook)) @@ -204,7 +206,7 @@ if (empty($reshook)) // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - // Do we click on purge search criteria ? + // Did we click on purge search criteria ? if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETPOST("button_removefilter")) // All tests are required to be compatible with all browsers { $search_nom=''; @@ -603,7 +605,7 @@ if ($user->rights->societe->client->voir || $socid) $moreforfilter.=$formother->select_salesrepresentatives($search_sale,'search_sale',$user, 0, 1, 'maxwidth300'); $moreforfilter.=''; } -if (! empty($moreforfilter)) +if ($moreforfilter) { print '
'; print $moreforfilter; @@ -905,7 +907,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab if (! empty($arrayfields["ef.".$key]['checked'])) { $align=$extrafields->getAlignFlag($key); - print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + print_liste_field_titre($langs->trans($extralabels[$key]),$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); } } } From 2da50f1eca2aa36fb56f540e93c8e0068e6b7417 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 23 May 2017 01:32:19 +0200 Subject: [PATCH 08/20] Look and feel v6 --- htdocs/comm/card.php | 2 +- htdocs/contact/agenda.php | 2 +- htdocs/contact/card.php | 2 +- htdocs/contact/document.php | 2 +- htdocs/contact/info.php | 2 +- htdocs/contact/ldap.php | 2 +- htdocs/contact/note.php | 50 +------------------------------------ htdocs/contact/perso.php | 2 +- htdocs/fourn/card.php | 2 +- htdocs/societe/card.php | 8 +++--- 10 files changed, 14 insertions(+), 60 deletions(-) diff --git a/htdocs/comm/card.php b/htdocs/comm/card.php index b26ce4fa7ac..7599cce4cfd 100644 --- a/htdocs/comm/card.php +++ b/htdocs/comm/card.php @@ -204,7 +204,7 @@ if ($id > 0) { $head = societe_prepare_head($object); - dol_fiche_head($head, 'customer', $langs->trans("ThirdParty"),0,'company'); + dol_fiche_head($head, 'customer', $langs->trans("ThirdParty"), -1, 'company'); $linkback = ''.$langs->trans("BackToList").''; diff --git a/htdocs/contact/agenda.php b/htdocs/contact/agenda.php index e97263ebf00..f57e088e00e 100644 --- a/htdocs/contact/agenda.php +++ b/htdocs/contact/agenda.php @@ -208,7 +208,7 @@ else dol_htmloutput_errors($error,$errors); - dol_fiche_head($head, 'agenda', $title, 0, 'contact'); + dol_fiche_head($head, 'agenda', $title, -1, 'contact'); $linkback = ''.$langs->trans("BackToList").''; diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php index dfa6eec515c..fde2e428169 100644 --- a/htdocs/contact/card.php +++ b/htdocs/contact/card.php @@ -1021,7 +1021,7 @@ else dol_htmloutput_errors($error,$errors); - dol_fiche_head($head, 'card', $title, 0, 'contact'); + dol_fiche_head($head, 'card', $title, -1, 'contact'); if ($action == 'create_user') { diff --git a/htdocs/contact/document.php b/htdocs/contact/document.php index 5d70ba7b4e1..da8ef616a4f 100644 --- a/htdocs/contact/document.php +++ b/htdocs/contact/document.php @@ -96,7 +96,7 @@ if ($object->id) $head = contact_prepare_head($object); $title = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); - dol_fiche_head($head, 'documents', $title, 0, 'contact'); + dol_fiche_head($head, 'documents', $title, -1, 'contact'); // Construit liste des fichiers diff --git a/htdocs/contact/info.php b/htdocs/contact/info.php index 0250691e88d..20d379b50d0 100644 --- a/htdocs/contact/info.php +++ b/htdocs/contact/info.php @@ -59,7 +59,7 @@ if ($id > 0) $head = contact_prepare_head($object); - dol_fiche_head($head, 'info', $title, 0, 'contact'); + dol_fiche_head($head, 'info', $title, -1, 'contact'); $linkback = ''.$langs->trans("BackToList").''; diff --git a/htdocs/contact/ldap.php b/htdocs/contact/ldap.php index 3e998b43ec5..16c00bf92cb 100644 --- a/htdocs/contact/ldap.php +++ b/htdocs/contact/ldap.php @@ -88,7 +88,7 @@ $form = new Form($db); $head = contact_prepare_head($object); -dol_fiche_head($head, 'ldap', $title, 0, 'contact'); +dol_fiche_head($head, 'ldap', $title, -1, 'contact'); dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', ''); diff --git a/htdocs/contact/note.php b/htdocs/contact/note.php index c49dbc9f787..b52f9bf8727 100644 --- a/htdocs/contact/note.php +++ b/htdocs/contact/note.php @@ -73,7 +73,7 @@ if ($id > 0) $head = contact_prepare_head($object); - dol_fiche_head($head, 'note', $title,0,'contact'); + dol_fiche_head($head, 'note', $title, -1, 'contact'); $linkback = ''.$langs->trans("BackToList").''; @@ -100,61 +100,13 @@ if ($id > 0) print ''; - // Company - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { - if ($object->socid > 0) - { - $objsoc = new Societe($db); - $objsoc->fetch($object->socid); - - print ''; - } - - else - { - print ''; - } - } - // Civility print ''; - // Date To Birth - print ''; - if (! empty($object->birthday)) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - - print ''; - } - else - { - print '"; - } - print ""; - print "
'.$langs->trans("ThirdParty").''.$objsoc->getNomUrl(1).'
'.$langs->trans("ThirdParty").''; - print $langs->trans("ContactNotLinkedToCompany"); - print '
'.$langs->trans("UserTitle").''; print $object->getCivilityLabel(); print '
'.$langs->trans("DateToBirth").''.dol_print_date($object->birthday,"day"); - - print '   '; - //var_dump($birthdatearray); - $ageyear=convertSecondToTime($now-$object->birthday,'year')-1970; - $agemonth=convertSecondToTime($now-$object->birthday,'month')-1; - if ($ageyear >= 2) print '('.$ageyear.' '.$langs->trans("DurationYears").')'; - else if ($agemonth >= 2) print '('.$agemonth.' '.$langs->trans("DurationMonths").')'; - else print '('.$agemonth.' '.$langs->trans("DurationMonth").')'; - - - print '   -   '; - if ($object->birthday_alert) print $langs->trans("BirthdayAlertOn"); - else print $langs->trans("BirthdayAlertOff"); - print ''.$langs->trans("DateToBirth").''.$langs->trans("Unknown")."
"; - print '
'; $cssclass="titlefield"; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; diff --git a/htdocs/contact/perso.php b/htdocs/contact/perso.php index bc4443dd8bf..30fa10b5ddc 100644 --- a/htdocs/contact/perso.php +++ b/htdocs/contact/perso.php @@ -229,7 +229,7 @@ else { // View mode - dol_fiche_head($head, 'perso', $title, 0, 'contact'); + dol_fiche_head($head, 'perso', $title, -1, 'contact'); $linkback = ''.$langs->trans("BackToList").''; diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index 6243a9e3a16..cfa88b187f0 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -130,7 +130,7 @@ if ($object->id > 0) */ $head = societe_prepare_head($object); - dol_fiche_head($head, 'supplier', $langs->trans("ThirdParty"),0,'company'); + dol_fiche_head($head, 'supplier', $langs->trans("ThirdParty"), -1, 'company'); $linkback = ''.$langs->trans("BackToList").''; diff --git a/htdocs/societe/card.php b/htdocs/societe/card.php index 14e8e4b4679..346f4ea38dc 100644 --- a/htdocs/societe/card.php +++ b/htdocs/societe/card.php @@ -1544,7 +1544,7 @@ else dol_fiche_head($head, 'card', $langs->trans("ThirdParty"), 0, 'company'); - + print '
'; print ''; // Ref/ID @@ -1934,7 +1934,8 @@ else print ''; print '
'; - + print '
'; + dol_fiche_end(); print '
'; @@ -1951,13 +1952,14 @@ else /* * View */ + if (!empty($object->id)) $res=$object->fetch_optionals($object->id,$extralabels); //if ($res < 0) { dol_print_error($db); exit; } $head = societe_prepare_head($object); - dol_fiche_head($head, 'card', $langs->trans("ThirdParty"), 0, 'company'); + dol_fiche_head($head, 'card', $langs->trans("ThirdParty"), -1, 'company'); // Confirm delete third party if ($action == 'delete' || ($conf->use_javascript_ajax && empty($conf->dol_use_jmobile))) From 71bd69a8048c2d16d10d31d9cb5c996e730e1864 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 23 May 2017 13:25:12 +0200 Subject: [PATCH 09/20] Better link to show part to edit --- htdocs/api/admin/index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/api/admin/index.php b/htdocs/api/admin/index.php index d7f002d02aa..c22a12fee61 100644 --- a/htdocs/api/admin/index.php +++ b/htdocs/api/admin/index.php @@ -111,7 +111,7 @@ $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain // Show message $message=''; -$url=''.$urlwithroot.'/api/index.php/login?login='.urlencode($user->login).'&password=yourpassword[&reset=1]'; +$url=$urlwithroot.'/api/index.php/login?login=auserlogin&userpassword=thepassword[&reset=1]'; $message.=$langs->trans("UrlToGetKeyToUseAPIs").':
'; $message.=img_picto('','object_globe.png').' '.$url; print $message; From 5ebe71166567ac84835d9b87b0a8f8eb93fefa28 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 23 May 2017 13:38:48 +0200 Subject: [PATCH 10/20] Look and feel v6 --- htdocs/resource/card.php | 39 +++++++++++----- htdocs/resource/class/dolresource.class.php | 51 ++++++++++++++++----- htdocs/resource/contact.php | 31 ++++++++----- htdocs/resource/document.php | 28 +++++++---- htdocs/resource/note.php | 29 ++++++++---- 5 files changed, 125 insertions(+), 53 deletions(-) diff --git a/htdocs/resource/card.php b/htdocs/resource/card.php index d2ec14efd71..7f0a96a7ab4 100644 --- a/htdocs/resource/card.php +++ b/htdocs/resource/card.php @@ -221,29 +221,41 @@ if ( $object->fetch($id) > 0 ) } else { - dol_fiche_head($head, 'resource', $langs->trans("ResourceSingular"),0,'resource'); + dol_fiche_head($head, 'resource', $langs->trans("ResourceSingular"), -1, 'resource'); + $formconfirm = ''; + // Confirm deleting resource line if ($action == 'delete') { - print $form->formconfirm("card.php?&id=".$id,$langs->trans("DeleteResource"),$langs->trans("ConfirmDeleteResource"),"confirm_delete_resource",'','',1); + $formconfirm = $form->formconfirm("card.php?&id=".$id,$langs->trans("DeleteResource"),$langs->trans("ConfirmDeleteResource"),"confirm_delete_resource",'','',1); } - + // Print form confirm + print $formconfirm; + + + $linkback = '' . $langs->trans("BackToList") . ''; + + + $morehtmlref='
'; + $morehtmlref.='
'; + + + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref); + + + print '
'; + print '
'; + /*--------------------------------------- * View object */ print ''; - print ''; - print ''; - // Resource type print ''; - print ''; + print ''; print ''; @@ -267,9 +279,14 @@ if ( $object->fetch($id) > 0 ) print ''; print '
'.$langs->trans("ResourceFormLabel_ref").''; - $linkback = $objet->ref.' '.$langs->trans("BackToList").''; - print $form->showrefnav($object, 'id', $linkback,1,"rowid"); - print '
' . $langs->trans("ResourceType") . '' . $langs->trans("ResourceType") . ''; print $object->type_label; print '
'; + + print '
'; + + print '

'; + + dol_fiche_end(); } - print '
'; /* * Boutons actions diff --git a/htdocs/resource/class/dolresource.class.php b/htdocs/resource/class/dolresource.class.php index 6e418e2e649..51024cfe7ee 100644 --- a/htdocs/resource/class/dolresource.class.php +++ b/htdocs/resource/class/dolresource.class.php @@ -30,18 +30,19 @@ require_once DOL_DOCUMENT_ROOT."/core/lib/functions2.lib.php"; */ class Dolresource extends CommonObject { - var $element='dolresource'; //!< Id that identify managed objects - var $table_element='resource'; //!< Name of table without prefix where object is stored - - var $resource_id; - var $resource_type; - var $element_id; - var $element_type; - var $busy; - var $mandatory; - var $fk_user_create; - var $type_label; - var $tms=''; + public $element='dolresource'; //!< Id that identify managed objects + public $table_element='resource'; //!< Name of table without prefix where object is stored + public $picto = 'resource'; + + public $resource_id; + public $resource_type; + public $element_id; + public $element_type; + public $busy; + public $mandatory; + public $fk_user_create; + public $type_label; + public $tms=''; /** * Constructor @@ -974,4 +975,30 @@ class Dolresource extends CommonObject $result.=$link.$this->ref.$linkend; return $result; } + + + /** + * Retourne le libelle du status d'un user (actif, inactif) + * + * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto + * @return string Label of status + */ + function getLibStatut($mode=0) + { + return $this->LibStatut($this->status,$mode); + } + + /** + * Return the status + * + * @param int $status Id status + * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 5=Long label + Picto + * @return string Label of status + */ + static function LibStatut($status,$mode=0) + { + global $langs; + + return ''; + } } diff --git a/htdocs/resource/contact.php b/htdocs/resource/contact.php index 97dbb0de1be..007ecd8025d 100644 --- a/htdocs/resource/contact.php +++ b/htdocs/resource/contact.php @@ -119,23 +119,30 @@ if ($id > 0 || ! empty($ref)) $head = resource_prepare_head($object); - dol_fiche_head($head, 'contact', $langs->trans("ResourceSingular"), 0, 'resource'); + dol_fiche_head($head, 'contact', $langs->trans("ResourceSingular"), -1, 'resource'); - /* - * Resource synthese pour rappel - */ + $linkback = '' . $langs->trans("BackToList") . ''; + + + $morehtmlref='
'; + $morehtmlref.='
'; + + + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref); + + + print '
'; + print '
'; + + + // Object + print ''; - print ''; - print ''; - // Resource type print ''; - print ''; + print ''; print ''; @@ -144,6 +151,8 @@ if ($id > 0 || ! empty($ref)) print '
'.$langs->trans("ResourceFormLabel_ref").''; - $linkback = $objet->ref.' '.$langs->trans("BackToList").''; - print $form->showrefnav($object, 'id', $linkback,1,"rowid"); - print '
' . $langs->trans("ResourceType") . '' . $langs->trans("ResourceType") . ''; print $object->type_label; print '
'; print '
'; + dol_fiche_end(); + print '
'; if (! empty($conf->global->RESOURCE_HIDE_ADD_CONTACT_USER)) $hideaddcontactforuser=1; diff --git a/htdocs/resource/document.php b/htdocs/resource/document.php index 1078e8bb94a..2d8e260d85a 100644 --- a/htdocs/resource/document.php +++ b/htdocs/resource/document.php @@ -89,7 +89,7 @@ if ($object->id) $head=resource_prepare_head($object); - dol_fiche_head($head, 'documents', $langs->trans("ResourceSingular"), 0, 'resource'); + dol_fiche_head($head, 'documents', $langs->trans("ResourceSingular"), -1, 'resource'); // Construit liste des fichiers @@ -100,19 +100,25 @@ if ($object->id) $totalsize+=$file['size']; } - + + $linkback = '' . $langs->trans("BackToList") . ''; + + + $morehtmlref='
'; + $morehtmlref.='
'; + + + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref); + + + print '
'; + print '
'; + print ''; - - print ''; - print ''; - // Resource type print ''; - print ''; + print ''; print ''; @@ -124,6 +130,8 @@ if ($object->id) print ''; + dol_fiche_end(); + $modulepart = 'dolresource'; $permission = $user->rights->resource->write; $param = '&id=' . $object->id; diff --git a/htdocs/resource/note.php b/htdocs/resource/note.php index 30e37eba77f..20d96591c7b 100644 --- a/htdocs/resource/note.php +++ b/htdocs/resource/note.php @@ -64,24 +64,35 @@ $form = new Form($db); if ($id > 0 || ! empty($ref)) { $head = resource_prepare_head($object); - dol_fiche_head($head, 'note', $langs->trans('ResourceSingular'), 0, 'resource'); + dol_fiche_head($head, 'note', $langs->trans('ResourceSingular'), -1, 'resource'); + $linkback = '' . $langs->trans("BackToList") . ''; + + + $morehtmlref='
'; + $morehtmlref.='
'; + + + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref); + + + print '
'; + print '
'; + print '
'.$langs->trans("ResourceFormLabel_ref").''; - $linkback = $objet->ref.' '.$langs->trans("BackToList").''; - print $form->showrefnav($object, 'id', $linkback,1,"rowid"); - print '
' . $langs->trans("ResourceType") . '' . $langs->trans("ResourceType") . ''; print $object->type_label; print '
'; - print ''; - print ''; // Resource type print ''; - print ''; + print ''; print ''; - print ''; print "
'.$langs->trans("ResourceFormLabel_ref").''; - $linkback = $objet->ref.' '.$langs->trans("BackToList").''; - print $form->showrefnav($object, 'id', $linkback,1,"rowid"); - print '
' . $langs->trans("ResourceType") . '' . $langs->trans("ResourceType") . ''; print $object->type_label; print '
"; + print ''; + + print ""; - print '
'; + print '
'; + $permission=$user->rights->resource->write; $cssclass='titlefield'; include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; From 3e37185b74de67d4f6cf5e77fdd5e2cb5ed06e28 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 23 May 2017 13:44:18 +0200 Subject: [PATCH 11/20] FIX download attached file on resource --- htdocs/core/lib/files.lib.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/htdocs/core/lib/files.lib.php b/htdocs/core/lib/files.lib.php index c60464ed0fd..4c492d1693e 100644 --- a/htdocs/core/lib/files.lib.php +++ b/htdocs/core/lib/files.lib.php @@ -2214,6 +2214,16 @@ function dol_check_secure_access_document($modulepart, $original_file, $entity, $original_file=$conf->don->dir_output.'/'.$original_file; } + // Wrapping pour les dons + else if ($modulepart == 'dolresource' && !empty($conf->resource->dir_output)) + { + if ($fuser->rights->resource->{$read} || preg_match('/^specimen/i',$original_file)) + { + $accessallowed=1; + } + $original_file=$conf->resource->dir_output.'/'.$original_file; + } + // Wrapping pour les remises de cheques else if ($modulepart == 'remisecheque' && !empty($conf->banque->dir_output)) { From 80ce8da7a388f157beb81e46ed465b952004a857 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 23 May 2017 15:13:52 +0200 Subject: [PATCH 12/20] Fix migration errors and responsive design --- htdocs/contrat/card.php | 67 ++++++++++--------- htdocs/core/class/html.formactions.class.php | 5 +- htdocs/install/default.css | 6 +- .../install/mysql/migration/5.0.0-6.0.0.sql | 17 +++++ .../mysql/tables/llx_opensurvey_sondage.sql | 2 +- htdocs/install/step5.php | 8 +-- htdocs/theme/eldy/style.css.php | 2 +- htdocs/theme/md/style.css.php | 17 +++-- 8 files changed, 72 insertions(+), 52 deletions(-) diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index f00816e9d4b..31e5d6f3094 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -2083,44 +2083,45 @@ else print "
"; } - // Select mail models is same action as presend - if (GETPOST('modelselected')) { - $action = 'presend'; - } - - if ($action != 'presend') - { - print '
'; - - /* - * Documents generes - */ - $filename = dol_sanitizeFileName($object->ref); - $filedir = $conf->contrat->dir_output . "/" . dol_sanitizeFileName($object->ref); - $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; - $genallowed = $user->rights->contrat->creer; - $delallowed = $user->rights->contrat->supprimer; - - $var = true; - - print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); - - - // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, array('contrat')); - $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - - - print '
'; - + + // Select mail models is same action as presend + if (GETPOST('modelselected')) { + $action = 'presend'; + } + + if ($action != 'presend') + { + print '
'; + + /* + * Documents generes + */ + $filename = dol_sanitizeFileName($object->ref); + $filedir = $conf->contrat->dir_output . "/" . dol_sanitizeFileName($object->ref); + $urlsource = $_SERVER["PHP_SELF"] . "?id=" . $object->id; + $genallowed = $user->rights->contrat->creer; + $delallowed = $user->rights->contrat->supprimer; + + $var = true; + + print $formfile->showdocuments('contract', $filename, $filedir, $urlsource, $genallowed, $delallowed, $object->modelpdf, 1, 0, 0, 28, 0, '', 0, '', $soc->default_lang); + + + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, array('contrat')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + + + print '
'; + // List of actions on element include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; $formactions = new FormActions($db); $somethingshown = $formactions->showactions($object, 'contract', $socid); - - print '
'; - } + + print '
'; + } /* * Action presend diff --git a/htdocs/core/class/html.formactions.class.php b/htdocs/core/class/html.formactions.class.php index 452ff89d914..456faa7931e 100644 --- a/htdocs/core/class/html.formactions.class.php +++ b/htdocs/core/class/html.formactions.class.php @@ -189,7 +189,9 @@ class FormActions $page=0; $param=''; $sortfield='a.datep'; - $total = 0; $var=true; + $total = 0; + + print '
'; print ''; print ''; print_liste_field_titre($langs->trans('Ref'), $_SERVER["PHP_SELF"], '', $page, $param, ''); @@ -243,6 +245,7 @@ class FormActions print ''; } print '
'; + print '
'; } return $num; diff --git a/htdocs/install/default.css b/htdocs/install/default.css index 9725b06b8bc..b3905e63a49 100644 --- a/htdocs/install/default.css +++ b/htdocs/install/default.css @@ -54,9 +54,9 @@ span.titre { font-weight: bold; background: #FFFFFF; color: #444; - border: 1px solid #999; - padding: 5px 5px 5px 5px; - margin: 0 0 0 15px; + border: 1px solid #bbb; + padding: 10px 10px 10px 10px; + margin: 0 0 10px 10px; } div.soustitre { diff --git a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql index 0bd68ddfcfb..a21c340b556 100644 --- a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql +++ b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql @@ -25,6 +25,23 @@ -- -- VMYSQL4.1 DELETE FROM llx_usergroup_user WHERE fk_usergroup NOT IN (SELECT rowid from llx_usergroup); +-- Clean corrupted values for tms +-- VMYSQL4.1 SET sql_mode = 'ALLOW_INVALID_DATES'; +-- VMYSQL4.1 update llx_opensurvey_sondage set tms = date_fin where DATE(STR_TO_DATE(tms, '%Y-%m-%d')) IS NULL; +-- VMYSQL4.1 SET sql_mode = 'NO_ZERO_DATE'; +-- VMYSQL4.1 update llx_opensurvey_sondage set tms = date_fin where DATE(STR_TO_DATE(tms, '%Y-%m-%d')) IS NULL; +-- Remove default not null on date_fin +-- VMYSQL4.3 ALTER TABLE llx_opensurvey_sondage MODIFY COLUMN date_fin DATETIME NULL DEFAULT NULL; +-- VPGSQL8.2 ALTER TABLE llx_opensurvey_sondage ALTER COLUMN date_fin DROP NOT NULL; + +ALTER TABLE llx_opensurvey_sondage MODIFY COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP; + +ALTER TABLE llx_opensurvey_sondage ADD COLUMN fk_user_creat integer NOT NULL DEFAULT 0; +ALTER TABLE llx_opensurvey_sondage ADD COLUMN status integer DEFAULT 1 after date_fin; +ALTER TABLE llx_opensurvey_sondage ADD COLUMN entity integer DEFAULT 1 NOT NULL; +ALTER TABLE llx_opensurvey_sondage ADD COLUMN allow_comments tinyint NOT NULL DEFAULT 1; + + create table llx_notify_def_object ( id integer AUTO_INCREMENT PRIMARY KEY, diff --git a/htdocs/install/mysql/tables/llx_opensurvey_sondage.sql b/htdocs/install/mysql/tables/llx_opensurvey_sondage.sql index 5ea2183758a..e9b2481757d 100644 --- a/htdocs/install/mysql/tables/llx_opensurvey_sondage.sql +++ b/htdocs/install/mysql/tables/llx_opensurvey_sondage.sql @@ -23,7 +23,7 @@ CREATE TABLE llx_opensurvey_sondage ( nom_admin VARCHAR(64), fk_user_creat integer NOT NULL, titre TEXT NOT NULL, - date_fin DATETIME NOT NULL, + date_fin DATETIME NULL, status integer DEFAULT 1, format VARCHAR(2) NOT NULL, -- 'A' = Text choice (choices are saved into sujet field), 'D' = Date choice (choices are saved into sujet field), 'F' = Form survey mailsonde tinyint NOT NULL DEFAULT 0, diff --git a/htdocs/install/step5.php b/htdocs/install/step5.php index 96cc1c4fdcf..875fd9378f2 100644 --- a/htdocs/install/step5.php +++ b/htdocs/install/step5.php @@ -1,6 +1,6 @@ - * Copyright (C) 2004-2012 Laurent Destailleur + * Copyright (C) 2004-2017 Laurent Destailleur * Copyright (C) 2004 Benoit Mortier * Copyright (C) 2004 Sebastien DiCintio * Copyright (C) 2005-2012 Regis Houssin @@ -395,11 +395,11 @@ elseif (empty($action) || preg_match('/upgrade/i',$action)) print '
'.$langs->trans("WarningRemoveInstallDir")."
"; } - print "
"; + print "

"; print ''; + print $langs->trans("GoToDolibarr").'...'; + print '
'; } else { diff --git a/htdocs/theme/eldy/style.css.php b/htdocs/theme/eldy/style.css.php index b8f31b4e224..a8eddcd825f 100644 --- a/htdocs/theme/eldy/style.css.php +++ b/htdocs/theme/eldy/style.css.php @@ -698,7 +698,7 @@ div.fiche>form>div.div-table-responsive { justify-content: flex-start; } .thumbstat { - flex: 1 1 114px; + flex: 1 1 116px; } .thumbstat150 { flex: 1 1 170px; diff --git a/htdocs/theme/md/style.css.php b/htdocs/theme/md/style.css.php index 91a4c0922d9..943540fa02f 100644 --- a/htdocs/theme/md/style.css.php +++ b/htdocs/theme/md/style.css.php @@ -544,7 +544,7 @@ textarea.centpercent { .cursorpointer { cursor: pointer; } -.cusormove { +.cursormove { cursor: move; } .badge { @@ -701,7 +701,7 @@ div.fiche>form>div.div-table-responsive { justify-content: flex-start; } .thumbstat { - flex: 1 1 114px; + flex: 1 1 116px; } .thumbstat150 { flex: 1 1 150px; @@ -1979,9 +1979,10 @@ div.tabsElem { margin-top: 6px; } /* To avoid overlap of tabs when not browser div.tabBar { color: #; - padding-top: px; - padding-left: px; - padding-right: px; + padding-top: 16px; + padding-left: 16px; + padding-right: 16px; + padding-bottom: 16px; margin: 0px 0px 16px 0px; -moz-border-radius:3px; -webkit-border-radius: 3px; @@ -1991,8 +1992,6 @@ div.tabBar { border-top: 1px solid #CCC; width: auto; background: rgb(); - - padding-bottom: 12px; border-bottom: 1px solid #aaa; } div.tabBar div.titre { @@ -4627,8 +4626,8 @@ border-top-right-radius: 6px; } div.tabBar { - padding-left: 0px; - padding-right: 0px; + padding-left: 8px; + padding-right: 8px; -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0px; From cea98ce5cbfe4baaee079cbab4923e862650c461 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 23 May 2017 15:30:56 +0200 Subject: [PATCH 13/20] Look and feel v6 --- .../install/mysql/migration/5.0.0-6.0.0.sql | 2 ++ htdocs/opensurvey/card.php | 31 ++++++++-------- .../class/opensurveysondage.class.php | 25 ++++++------- htdocs/opensurvey/results.php | 35 ++++++++++--------- 4 files changed, 47 insertions(+), 46 deletions(-) diff --git a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql index a21c340b556..6c71f279867 100644 --- a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql +++ b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql @@ -40,6 +40,8 @@ ALTER TABLE llx_opensurvey_sondage ADD COLUMN fk_user_creat integer NOT NULL DEF ALTER TABLE llx_opensurvey_sondage ADD COLUMN status integer DEFAULT 1 after date_fin; ALTER TABLE llx_opensurvey_sondage ADD COLUMN entity integer DEFAULT 1 NOT NULL; ALTER TABLE llx_opensurvey_sondage ADD COLUMN allow_comments tinyint NOT NULL DEFAULT 1; +ALTER TABLE llx_opensurvey_sondage ADD COLUMN allow_spy tinyint NOT NULL DEFAULT 1 AFTER allow_comments; +ALTER TABLE llx_opensurvey_sondage ADD COLUMN sujet TEXT; create table llx_notify_def_object diff --git a/htdocs/opensurvey/card.php b/htdocs/opensurvey/card.php index d7a466a5217..707af9f7115 100644 --- a/htdocs/opensurvey/card.php +++ b/htdocs/opensurvey/card.php @@ -212,22 +212,23 @@ print ''; $head = opensurvey_prepare_head($object); -dol_fiche_head($head,'general',$langs->trans("Survey"),0,dol_buildpath('/opensurvey/img/object_opensurvey.png',1),1); +dol_fiche_head($head,'general',$langs->trans("Survey"), -1, DOL_URL_ROOT.'/opensurvey/img/object_opensurvey.png', 1); + +$morehtmlref = ''; + +$linkback = ''.$langs->trans("BackToList").''; + +dol_banner_tab($object, 'id', $linkback, 1, 'id_sondage', 'id_sondage', $morehtmlref); + + +print '
'; +print '
'; print ''; -$linkback = ''.$langs->trans("BackToList").''; - -// Ref -print ''; -print ''; -print ''; - // Type $type=($object->format=="A")?'classic':'date'; -print ''; @@ -242,12 +243,6 @@ if ($action == 'edit') else print dol_htmlentities($object->titre); print ''; -// Status -print ''; - // Description print ''; print '
'.$langs->trans('Ref').''; -print $form->showrefnav($object, 'id', $linkback, 1, 'id_sondage', 'id_sondage'); -print '
'.$langs->trans("Type").''; +print '
'.$langs->trans("Type").''; print img_picto('',dol_buildpath('/opensurvey/img/'.($type == 'classic'?'chart-32.png':'calendar-32.png'),1),'width="16"',1); print ' '.$langs->trans($type=='classic'?"TypeClassic":"TypeDate").'
'; -print $langs->trans("Status") .''; -print $object->getLibStatut(4); -print '
'.$langs->trans("Description") .''; if ($action == 'edit') @@ -345,6 +340,8 @@ print '
'; +print '
'; + dol_fiche_end(); if ($action == 'edit') diff --git a/htdocs/opensurvey/class/opensurveysondage.class.php b/htdocs/opensurvey/class/opensurveysondage.class.php index 5ad27731d88..95af2b130d5 100644 --- a/htdocs/opensurvey/class/opensurveysondage.class.php +++ b/htdocs/opensurvey/class/opensurveysondage.class.php @@ -34,19 +34,20 @@ require_once(DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php"); */ class Opensurveysondage extends CommonObject { - var $element='opensurvey_sondage'; //!< Id that identify managed objects - var $table_element='opensurvey_sondage'; //!< Name of table without prefix where object is stored - - var $id_sondage; + public $element='opensurvey_sondage'; //!< Id that identify managed objects + public $table_element='opensurvey_sondage'; //!< Name of table without prefix where object is stored + public $picto = 'opensurvey'; + + public $id_sondage; /** * @deprecated * @see description */ - var $commentaires; + public $commentaires; public $description; - var $mail_admin; - var $nom_admin; + public $mail_admin; + public $nom_admin; /** * Id of user author of the poll @@ -54,11 +55,11 @@ class Opensurveysondage extends CommonObject */ public $fk_user_creat; - var $titre; - var $date_fin=''; - var $status=1; - var $format; - var $mailsonde; + public $titre; + public $date_fin=''; + public $status=1; + public $format; + public $mailsonde; public $sujet; diff --git a/htdocs/opensurvey/results.php b/htdocs/opensurvey/results.php index f10e21effe1..9bfb15b2c24 100644 --- a/htdocs/opensurvey/results.php +++ b/htdocs/opensurvey/results.php @@ -426,23 +426,23 @@ print '
'."\n"; $head = opensurvey_prepare_head($object); -print dol_get_fiche_head($head,'preview',$langs->trans("Survey"),0,dol_buildpath('/opensurvey/img/object_opensurvey.png',1),1); +dol_fiche_head($head,'preview',$langs->trans("Survey"), -1, DOL_URL_ROOT.'/opensurvey/img/object_opensurvey.png', 1); +$morehtmlref = ''; + +$linkback = ''.$langs->trans("BackToList").''; + +dol_banner_tab($object, 'id', $linkback, 1, 'id_sondage', 'id_sondage', $morehtmlref); + + +print '
'; +print '
'; print ''; -$linkback = ''.$langs->trans("BackToList").''; - -// Ref -print ''; -print ''; -print ''; - // Type $type=($object->format=="A")?'classic':'date'; -print ''; @@ -499,6 +499,8 @@ print ''; print '
'.$langs->trans('Ref').''; -print $form->showrefnav($object, 'id', $linkback, 1, 'id_sondage', 'id_sondage'); -print '
'.$langs->trans("Type").''; +print '
'.$langs->trans("Type").''; print img_picto('',dol_buildpath('/opensurvey/img/'.($type == 'classic'?'chart-32.png':'calendar-32.png'),1),'width="16"',1); print ' '.$langs->trans($type=='classic'?"TypeClassic":"TypeDate").'
'; +print '
'; + dol_fiche_end(); print '
'."\n"; @@ -1045,7 +1047,7 @@ print ''."\n"; print ''."\n"; -$toutsujet = explode(",", $object->sujet); +$toutsujet = explode(",", $object->sujet); // With old versions, this field was not set $compteursujet = 0; $meilleursujet = ''; @@ -1056,7 +1058,7 @@ for ($i = 0; $i < $nbcolonnes; $i++) { if ($object->format == "D") { $meilleursujetexport = $toutsujet[$i]; - if (strpos($toutsujet[$i], '@') !== false) { + if (strpos($toutsujet[$i], '@') !== false) { $toutsujetdate = explode("@", $toutsujet[$i]); $meilleursujet .= dol_print_date($toutsujetdate[0],'daytext'). ' ('.dol_print_date($toutsujetdate[0],'%A').')' . ' - ' . $toutsujetdate[1]; } else { @@ -1072,8 +1074,7 @@ for ($i = 0; $i < $nbcolonnes; $i++) { $compteursujet++; } } - -$meilleursujet = substr("$meilleursujet", 1); +$meilleursujet = substr($meilleursujet, 1); $meilleursujet = str_replace("°", "'", $meilleursujet); // Show best choice @@ -1083,9 +1084,9 @@ if ($nbofcheckbox >= 2) print '

'."\n"; if (isset($meilleurecolonne) && $compteursujet == "1") { - print " " . $langs->trans('TheBestChoice') . ": ".$meilleursujet." " . $langs->trans("with") . " $meilleurecolonne " . $vote_str . ".\n"; + print " " . $langs->trans('TheBestChoice') . ": ".$meilleursujet." " . $langs->trans("with") . " ".$meilleurecolonne."" . $vote_str . ".\n"; } elseif (isset($meilleurecolonne)) { - print " " . $langs->trans('TheBestChoices') . ": ".$meilleursujet." " . $langs->trans("with") . " $meilleurecolonne " . $vote_str . ".\n"; + print " " . $langs->trans('TheBestChoices') . ": ".$meilleursujet." " . $langs->trans("with") . " ".$meilleurecolonne."" . $vote_str . ".\n"; } print '


'."\n"; } From 67b3e3da99cbcbcc974f08bb240b31dee3d7d2b0 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 23 May 2017 15:51:39 +0200 Subject: [PATCH 14/20] FIX #6784 --- htdocs/core/lib/ajax.lib.php | 6 +++--- htdocs/opensurvey/card.php | 4 ++-- htdocs/public/opensurvey/studs.php | 3 +++ 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/htdocs/core/lib/ajax.lib.php b/htdocs/core/lib/ajax.lib.php index 9ba57abf302..d278f29b897 100644 --- a/htdocs/core/lib/ajax.lib.php +++ b/htdocs/core/lib/ajax.lib.php @@ -354,9 +354,9 @@ function ajax_dialog($title,$message,$w=350,$h=150) * Make content of an input box selected when we click into input field. * * @param string $htmlname Id of html object - * @param int $addlink Add a link to after + * @param string $addlink Add a 'link to' after */ -function ajax_autoselect($htmlname, $addlink=0) +function ajax_autoselect($htmlname, $addlink='') { global $langs; $out = ''; - if ($addlink) $out.=' '.$langs->trans("Link").''; + if ($addlink) $out.=' '.$langs->trans("Link").''; return $out; } diff --git a/htdocs/opensurvey/card.php b/htdocs/opensurvey/card.php index 707af9f7115..18326321a4b 100644 --- a/htdocs/opensurvey/card.php +++ b/htdocs/opensurvey/card.php @@ -332,9 +332,9 @@ $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($ $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current -$url=$urlwithouturlroot.dol_buildpath('/public/opensurvey/studs.php',1).'?sondage='.$object->id_sondage; +$url=$urlwithroot.'/public/opensurvey/studs.php?sondage='.$object->id_sondage; print ''; -if ($action != 'edit') print ajax_autoselect("opensurveyurl", 1); +if ($action != 'edit') print ajax_autoselect("opensurveyurl", $url); print ''; diff --git a/htdocs/public/opensurvey/studs.php b/htdocs/public/opensurvey/studs.php index 98d267fdd72..8e769452ec1 100644 --- a/htdocs/public/opensurvey/studs.php +++ b/htdocs/public/opensurvey/studs.php @@ -47,6 +47,9 @@ $nblignes=$object->fetch_lines(); //If the survey has not yet finished, then it can be modified $canbemodified = ((empty($object->date_fin) || $object->date_fin > dol_now()) && $object->status != Opensurveysondage::STATUS_CLOSED); +// Security check +if (empty($conf->opensurvey->enabled)) accessforbidden('',0,0,1); + /* * Actions From c98f0ba45713c6f66750c4328b3e76323ef6bfe6 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 23 May 2017 15:57:18 +0200 Subject: [PATCH 15/20] Fix typo --- htdocs/langs/en_US/stocks.lang | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/langs/en_US/stocks.lang b/htdocs/langs/en_US/stocks.lang index 0d2f10a2165..97ddedc3231 100644 --- a/htdocs/langs/en_US/stocks.lang +++ b/htdocs/langs/en_US/stocks.lang @@ -119,7 +119,7 @@ NbOfProductBeforePeriod=Quantity of product %s in stock before selected period ( NbOfProductAfterPeriod=Quantity of product %s in stock after selected period (> %s) MassMovement=Mass movement SelectProductInAndOutWareHouse=Select a product, a quantity, a source warehouse and a target warehouse, then click "%s". Once this is done for all required movements, click onto "%s". -RecordMovement=Record transfert +RecordMovement=Record transfer ReceivingForSameOrder=Receipts for this order StockMovementRecorded=Stock movements recorded RuleForStockAvailability=Rules on stock requirements From 6d4c5e4b4afe56d1247f7a02bb35db26b746b5f0 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 24 May 2017 11:20:56 +0200 Subject: [PATCH 16/20] Code comment --- htdocs/core/lib/functions.lib.php | 1 + htdocs/main.inc.php | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 30e1579c33e..e8ead0ed829 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -280,6 +280,7 @@ function GETPOST($paramname, $check='', $method=0, $filter=NULL, $options=NULL) $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring); $relativepathstring = preg_replace('/^\//', '', $relativepathstring); + // Code for search criteria persistence. // Retrieve values if restore_lastsearch_values is set and there is saved values if (! empty($_GET['restore_lastsearch_values']) && ! empty($_SESSION['lastsearch_values_'.$relativepathstring])) // Keep $_GET here { diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php index e674aea6d5c..da9e65f47ce 100644 --- a/htdocs/main.inc.php +++ b/htdocs/main.inc.php @@ -1935,7 +1935,6 @@ if (! function_exists("llxFooter")) if ($comment) print ''."\n"; printCommonFooter($zone); - //var_dump($langs); // Uncommment to see the property _tab_loaded to see which language file were loaded if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print ' '."\n"; // End div container From f011197e0017cb7e49f51dfbbf6897dc7514c207 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 24 May 2017 15:12:45 +0200 Subject: [PATCH 17/20] Update swagger to 2.0.24 --- COPYRIGHT | 137 +----- .../Luracast/Restler/explorer/css/screen.css | 43 +- .../Restler/explorer/images/logo_small.png | Bin 1620 -> 770 bytes .../Restler/explorer/images/pet_store_api.png | Bin 0 -> 824 bytes .../Restler/explorer/images/wordnik_api.png | Bin 0 -> 980 bytes .../Luracast/Restler/explorer/index.html | 34 +- .../Restler/explorer/lib/swagger-oauth.js | 103 ++--- .../Luracast/Restler/explorer/lib/swagger.js | 425 +++++++++++------- .../Luracast/Restler/explorer/swagger-ui.js | 331 ++++++++------ .../Restler/explorer/swagger-ui.min.js | 2 +- 10 files changed, 552 insertions(+), 523 deletions(-) create mode 100644 htdocs/includes/restler/framework/Luracast/Restler/explorer/images/pet_store_api.png create mode 100644 htdocs/includes/restler/framework/Luracast/Restler/explorer/images/wordnik_api.png diff --git a/COPYRIGHT b/COPYRIGHT index 61a0f2de6bd..04f0358a655 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -21,13 +21,13 @@ GeoIP 1.4 LGPL-2.1+ Yes Mobiledetect 2.8.17 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+ b Yes Library to build/edit ODT files +odtPHP 1.0.1 GPL-2+ Yes Library to build/edit ODT files ParseDown 1.6 MIT License Yes Markdown parser PHPExcel 1.8.1 LGPL-2.1+ Yes Read/Write XLS files, read ODS files php-iban 1.4.7 LGPL-3+ Yes Parse and validate IBAN (and IIBAN) bank account information in PHP PHPoAuthLib 0.8.2 MIT License Yes Library to provide oauth1 and oauth2 to different service PHPPrintIPP 1.3 GPL-2+ Yes Library to send print IPP requests -Restler 3.0.0RC6 LGPL-3+ Yes Library to develop REST Web services +Restler 3.0.0RC6 LGPL-3+ Yes Library to develop REST Web services (+ swagger-ui js lib into dir explorer) TCPDF 6.2.12 LGPL-3+ Yes PDF generation TCPDI 1.0.0 LGPL-3+ / Apache 2.0 Yes FPDI replacement Swift Mailer 5.4.2-DEV MIT license Yes Comprehensive mailing tools for PHP @@ -52,138 +52,13 @@ jQuery Timepicker 1.1.0 GPL and MIT License Yes jQuery Tiptip 1.3 GPL and MIT License Yes JS library for tooltips jsGanttImproved 1.7.5.2 BSD License Yes JS library (to build Gantt reports) JsTimezoneDetect 1.0.6 MIT License Yes JS library to detect user timezone +SwaggerUI 2.0.24 GPL-2+ Yes JS library to offer the REST API explorer For licenses compatibility informations: http://www.gnu.org/licenses/licenses.en.html -Copyright ---------- - -Copyright (C) 2016 - -Copyright (C) 2015 -- Laurent Destailleur -- Marcos García -- Alexandre Spangaro -- Frederic France -- Regis Houssin - -Copyright (C) 2014 -- Laurent Destailleur -- Raphaël Doursenaud -- Jean-François Ferry -- Marcos García -- Philippe Grand -- Florian Henry -- Regis Houssin -- Maxime Kohlhaas -- Juanjo Menent -- Alexandre Spangaro -- Frederic France - -Copyright (C) 2013 -- Christophe Battarel -- Laurent Destailleur -- Jean-François Ferry -- Marcos García -- Philippe Grand -- Florian Henry -- Regis Houssin -- Maxime Kohlhaas -- Juanjo Menent -- Adolfo Segura -- Alexandre Spangaro - -Copyright (C) 2012 -- Christophe Battarel -- Laurent Destailleur -- Jean-François Ferry -- Marcos García -- Philippe Grand -- Jean Heimburger -- Florian Henry -- Regis Houssin -- Maxime Kohlhaas -- Juanjo Menent -- Nicolas Péré -- Alexandre Spangaro - -Copyright (C) 2011 -- Laurent Destailleur -- Regis Houssin -- Juanjo Menent -- Philippe Grand -- Jean Heimburger - -Copyright (C) 2010 -- Laurent Destailleur -- Regis Houssin -- Juanjo Menent -- r2gnl -- meos - -Copyright (C) 2009 -- Laurent Destailleur -- Regis Houssin -- Juanjo Menent - -Copyright (C) 2008 -- Laurent Destailleur -- Regis Houssin -- Rodolphe Quiedeville -- Jeremie Ollivier - -Copyright (C) 2007 -- Rodolphe Quiedeville -- Laurent Destailleur -- Regis Houssin -- Auguria SARL -- Jean Heimburger -- Jeremie Ollivier - -Copyright (C) 2006 -- Auguria SARL -- Marc Barilley/Ocebo -- Laurent Destailleur -- Rodolphe Quiedeville -- Regis Houssin -- Andre Cianfarani -- Yannick Warnier -- Jean Heimburger - -Copyright (C) 2005 -- Brice Davoleau -- Laurent Destailleur -- Benoit Mortier -- Rodolphe Quiedeville -- Eric Seigne -- Matthieu Valleton -- Regis Houssin - -Copyright (C) 2004 -- Laurent Destailleur -- Rodolphe Quiedeville -- Eric Seigne -- Benoit Mortier -- Christophe Combelles -- Sebastien Di Cintio - -Copyright (C) 2003 -- Jean-Louis Bergamo -- Xavier Dutoit -- Rodolphe Quiedeville -- Emmanuel Raviart -- Eric Seigne - -Copyright (C) 2002 -- Jean-Louis Bergamo -- Rodolphe Quiedeville - -Copyright (C) 2001 -- Rodolphe Quiedeville - - - - +Copyright / Authors +------------------- +See page https://github.com/Dolibarr/dolibarr/graphs/contributors diff --git a/htdocs/includes/restler/framework/Luracast/Restler/explorer/css/screen.css b/htdocs/includes/restler/framework/Luracast/Restler/explorer/css/screen.css index 2ac5625af06..478b99837d7 100644 --- a/htdocs/includes/restler/framework/Luracast/Restler/explorer/css/screen.css +++ b/htdocs/includes/restler/framework/Luracast/Restler/explorer/css/screen.css @@ -350,7 +350,7 @@ font-size: .85em; line-height: 1.2em; overflow: auto; - max-height: 400px; + max-height: 200px; cursor: pointer; } .swagger-section .swagger-ui-wrap .model-signature ul.signature-nav { @@ -743,17 +743,20 @@ display: inline-block; font-size: 0.9em; } -.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header img { - display: block; - clear: none; - float: right; -} .swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header input.submit { display: block; clear: none; float: left; padding: 6px 8px; } +.swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content div.sandbox_header span.response_throbber { + background-image: url('../images/throbber.gif'); + width: 128px; + height: 16px; + display: block; + clear: none; + float: right; +} .swagger-section .swagger-ui-wrap ul#resources li.resource ul.endpoints li.endpoint ul.operations li.operation div.content form input[type='text'].error { outline: 2px solid black; outline-color: #cc0000; @@ -1158,7 +1161,7 @@ cursor: pointer; } .swagger-section #header { - background-color: #646257; + background-color: #89bf04; padding: 14px; } .swagger-section #header a#logo { @@ -1193,7 +1196,7 @@ padding: 6px 8px; font-size: 0.9em; color: white; - background-color: #000000; + background-color: #547f00; -moz-border-radius: 4px; -webkit-border-radius: 4px; -o-border-radius: 4px; @@ -1202,35 +1205,13 @@ border-radius: 4px; } .swagger-section #header form#api_selector .input a#explore:hover { - background-color: #a41e22; + background-color: #547f00; } .swagger-section #header form#api_selector .input input { font-size: 0.9em; padding: 3px; margin: 0; } -.swagger-section #footer-nav { - margin-top: 50px; - color: #bbb; - float: left; - list-style: none; - font-size: 0.8em; -} -.swagger-section #footer-nav li { - display: block; - float: left; -} -.swagger-section #footer-nav a { - margin-right: 4px; - text-decoration: none; - font-weight: none; - padding: 4px 2px; - font-size: 0.9em; - color: #999; -} -.swagger-section #footer-nav a:hover { - color: #555; -} .swagger-section #content_message { margin: 10px 15px; font-style: italic; diff --git a/htdocs/includes/restler/framework/Luracast/Restler/explorer/images/logo_small.png b/htdocs/includes/restler/framework/Luracast/Restler/explorer/images/logo_small.png index 2ed3cf64be72132f93719f8014a6f440b06d818a..5496a65579ae903d4008f9d268fac422ef9d3679 100644 GIT binary patch delta 757 zcmVeSaefwW^{L9a%BKPWN%_+AW3auXJt}l zVPtu6$z?nM00N{*L_t(|+Qe5qY|}s#esPzIE@o)O=n+8&R{|*#L(PIfT{3hiQ=F}c zp~=FUc0*!FJHWzFGqE6%NL1<;XChLEdTG@Sk5yS*2~bDg=YQT+mVIX@wF56YoppY> z@BMu5<%Q@!N$oaYTJMs{o1Hj{zU)vi6JQ2&cx&>)ZfVp2{)tzg4GBvD3&5@boJKre zJ30eu1)x3N+9gsM@#-+RHxaPN;V_lQG6K)HlLvDutp^T$uMiaC@ST^ZBO1#CLla(m z1{Ks3e94Adynh&~zGdCBX<^=^@I0X3SCR7OMbn}sUKdeFKO-flaJa%@kJ27@Rod?J z9=+Qx5|=PtG8n>y~9rIu}+48M}FW5Bbqw3 zt#po?c?kmG!FX32W(dOjzTb+U@64MzHItoeB!M0JcYm^KBq0?}5!|tR}5&*k=hqU1Np`{I?Gbb7b+;Y=z!O$nm8}UUSzrCVok2dMe##j1t zbxF~$^O(JOe=y#o&iZF&|1KS!4Pqm~YUtPaa}xR)WTS{s(z8WTpAfl&Oi~ADARd;i zc|2dJ>wo#Wf#fv~himh7V?Smz%4rfoBw(of_O7l9t{Vt<5?^=8(OEx}+adud!kbfi zfsy(V&q!X~mXJ{r*stQof-;iQPXh1hwBR*L1G&ztYv`a7B=K~d#e8-HEJhShIm0li z01l!p6##<^07Z%Eh62^kB5plKKb=vl4A{YyOl}|0VpD{ nD)OJ^fG<28}?}J(t ztryNcu>M1Y8rg+jhiC`b|TlKDJ7A5P}ONxTFekIUo1iHR@_b6}X8z-4neaq(;x zi?xi&WX3QVOeUSdpfMQH0DAP2=x7>kN#s&mB#jmY{Hatjl}cGej_~+~FC>MBg@u4M z0d3%>RmwaX5>H-%K)?s75kAbHVKzGqCvdr3jwf$CNX=%mLH4*fR$MF-IIvhTK*Qs} zc&`B*fC&(oHSuTw6Ut%=DBEo1B7g~r6y_lW6xmbe1>gsOQm@i#bTX-0z>}vWNxAVL zBUl<3X_89~QW2V*l+K3{4m(dFH7le!GO-B}7)AW76n>_Fmn{)xBZ4BCxG)vTmk0|a zh#3*&A%a{{a=J+L!dz{q}EO5*5<5lFX ztT~aF-W=wwXlAasy!KA#{!_vCc8`r){wOYAfK|}Zg9PJbxS`Drk;)p~zY|Tt-88>* zwriWWb1zVDZtTG?paYc|7T*|z0vmc|>Drcq6j5NpMz|2?cHb`i@?uwOi^ zq83NCbnz;42Pc0dj34#(XLPH(clD@>^Tx(273Y3H^+xZ#{TS}&gSD83m-~j}1AOfv zMVs~g)RU1HH|1RUcD`si?r4G*GZO0OveK+}{)fDYSTMi+hjRZR>cge1S zR@On$u^Zq1me^ji^p@q(E2tfBTvg3>Jq*E-5aaR-qd1lcM;WU z`vf>j9jA6B>rS5l-}&OHq0;I0;+3!cMzi&fqek1LqNjZyefrl8q?U<>9#!evrstg< z9UZRNU`5UKvUD!GPtvYGoKo%T9HASStIj)gc|l1glldggnPy|@c4zEtP{iK5USC1K ziz=MEGQLy=x@c#Hg$F8HUC&hyzUtY|{)^#UHYzzVSzcQ3^7e(a`*rm1RIaV^#o0IS z_w{vkWbY|374IK1=xA3vqFX{vwfG#EEU9>G9xCaaa>Z+G%+t}diAF+FEzVq};smoa zbi)HvbN`b!s}nDrr&Ia{2953Bcl~x&Cvp!-BYU1?)gSHc36Gp-R=&RcbjO;eQEGE& ta!w9m(NDOMo}d5m!&kLnqYQAv9LOHZ7#!&yyal!|q>!SLGf3{ne*t=UPFDZ` diff --git a/htdocs/includes/restler/framework/Luracast/Restler/explorer/images/pet_store_api.png b/htdocs/includes/restler/framework/Luracast/Restler/explorer/images/pet_store_api.png new file mode 100644 index 0000000000000000000000000000000000000000..f9f9cd4aeb35a108c4b2f1dddb59977d56c595d8 GIT binary patch literal 824 zcmV-81IPS{P)n=Rd;8mVwQNY4k4xJQ%YT}s;WA7;r!W@XgqjG_4og} z8w>{OB9REiMa8-B85td+y}bji^~2KA`Md4j-u{zw=H%Da@83%_8qEnl9k1WK;pWX- zb-lg)pQYAreK@>)*5Clqni{IZVYGG+NY67Bp-^bn;L{Nbh44I6CIK+n7p8#U?;fCA zYMFcy%UEjup4fgnli%NyzSe*@419QuU9lJ|T$?f9w?HIQ$RwEJGK7^!y7LhxIgVJp z9c!kB{0aydM1epU1NJ=h(}2X?Y{qn70yEN$dwm~favs=VbQ+T?!AvSl{P~PE zS&zsJbTQttne>kdM4$jBhLMFy@I1)3u-4cAzrY*l!o9eK^w%+jqY!oi(Ri8sMauvK zwnCP#%3hEH#FtNqq{iT(?=_JA_8XC>5Y8Y@!wmxKb|A87ZbpHA`+%v~0pt{5Nko1L zLKR^25YExt1lH7L1{t{|P z@n)yHyZf~3>LZ@#&CNw1rA#OlY^|)UJQKUrlKKO&x%wPhH}6&e0000dvj&>@zN_HP5m0E=+A=efDBI*IG*Gy%%< zz@yc%2XvGm)QQv5k^ZC6!9MwX8BCmQ{3eAX|GTwn#>(PS6PoB=$Pwn*?wz?%Tx2gwJ4apoy`A15D=>?%}hj`fV*p=6XW=YR(sp))`dxTnqHE&{&; zPdeO}SVkf*6_$c45W3Z}u|Z&a8{r!6ZNY62S>5{jAd)Hkjg@h%@c)c#BvZK2lmGw| z`Vh+%ECkF{t=)XpF3Z1bj=Pe9LpHbnQwjeTU#=4hB76#52DU2P2Ouj~^lRWwRd%eN zBw_z%FL0CUlk!`s2!`>QG&H__i_)I9=AuA=jn40z>;@hRsg)>J(58cx;l;h_zE*-R7Wbz6Ff#1Mss*)zTImU4`2@?a7y;v4 zH=lJ_PM5Rkw*AU`Cmq6aa>chASJ&Z3Ebj`y;w$MM!fa6`13VU7Kc|T5Xl#7ecj?mp zREV-nBJ6C)`?&}QDe_(KM>BrlN|iF{7-90j+J>N0^vY=LK;8!^9Y_m*aRPX{!S6ag zgRw(13pJvt`;{^S-vgUk?8pV_Vh4a4P7~}uHT)ENFMqd71QIOl8Q6+24TM_+158z) z54U-*C{M)S&!2Bfu&`?Ti6;WojY;%6+I;uCof+*T2iUMz!7Eg<{}#DJSx)C$5f zP(oSf>_s1t06cJ-U3?<9poS4O{Go>H>hro^ks;r3mm1Ehfq?m(_YE8UiVUgG%W9ZY z!@O^}KR%JW*0e=66rUYj5BP~=x%$^x92-m_ Api Explorer - + @@ -27,10 +26,11 @@ $(function () { window.swaggerUi = new SwaggerUi({ url: "resources.json", + validatorUrl: null, dom_id: "swagger-ui-container", - supportedSubmitMethods: ['get', 'post', 'put', 'patch', 'delete'], + supportedSubmitMethods: ['get', 'post', 'put', 'delete'], onComplete: function(swaggerApi, swaggerUi){ - log("Loaded Api Explorer"); + log("Loaded API Explorer"); if(typeof initOAuth == "function") { /* @@ -45,15 +45,19 @@ hljs.highlightBlock(e) }); }, + defaultModelRendering: 'model', onFailure: function(data) { - log("Unable to Load Api Explorer"); + log("Unable to Load API Explorer"); }, - docExpansion: "none" + docExpansion: "none", + /*showRequestHeaders: true, + jsonEditor: true */ + /*, sorter : "alpha"*/ }); $('#input_apiKey').change(function() { var key = $('#input_apiKey')[0].value; - + log("key: " + key); if(key && key.trim() != "") { /* DOL_CHANGE LDR We set DOLAPIKEY into header */ log("added key " + key); @@ -67,11 +71,15 @@ console.log("header DOLAPIKEY added with value "+key); } }) - window.swaggerUi.load(); }); - + + @@ -79,6 +87,14 @@
+
diff --git a/htdocs/includes/restler/framework/Luracast/Restler/explorer/lib/swagger-oauth.js b/htdocs/includes/restler/framework/Luracast/Restler/explorer/lib/swagger-oauth.js index 19777eb90f0..8bb17fb076a 100644 --- a/htdocs/includes/restler/framework/Luracast/Restler/explorer/lib/swagger-oauth.js +++ b/htdocs/includes/restler/framework/Luracast/Restler/explorer/lib/swagger-oauth.js @@ -48,72 +48,65 @@ function handleLogin() { str += ''; popup.append(str); } - + } - var $win = $(window), - dw = $win.width(), - dh = $win.height(), - st = $win.scrollTop(), - dlgWd = popupDialog.outerWidth(), - dlgHt = popupDialog.outerHeight(), - top = (dh -dlgHt)/2 + st, - left = (dw - dlgWd)/2; + var $win = $(window), + dw = $win.width(), + dh = $win.height(), + st = $win.scrollTop(), + dlgWd = popupDialog.outerWidth(), + dlgHt = popupDialog.outerHeight(), + top = (dh -dlgHt)/2 + st, + left = (dw - dlgWd)/2; - popupDialog.css({ - top: (top < 0? 0 : top) + 'px', - left: (left < 0? 0 : left) + 'px' - }); + popupDialog.css({ + top: (top < 0? 0 : top) + 'px', + left: (left < 0? 0 : left) + 'px' + }); - popupDialog.find('button.api-popup-cancel').click(function() { - popupMask.hide(); - popupDialog.hide(); - }); - popupDialog.find('button.api-popup-authbtn').click(function() { - popupMask.hide(); - popupDialog.hide(); + popupDialog.find('button.api-popup-cancel').click(function() { + popupMask.hide(); + popupDialog.hide(); + }); + popupDialog.find('button.api-popup-authbtn').click(function() { + popupMask.hide(); + popupDialog.hide(); - var authSchemes = window.swaggerUi.api.authSchemes; - var location = window.location; - var locationUrl = location.protocol + '//' + location.host + location.pathname; - var redirectUrl = locationUrl.replace("index.html","").concat("/o2c.html").replace("//o2c.html","/o2c.html"); - var url = null; + var authSchemes = window.swaggerUi.api.authSchemes; + var host = window.location; + var pathname = location.pathname.substring(0, location.pathname.lastIndexOf("/")); + var redirectUrl = host.protocol + '//' + host.host + pathname + "/o2c.html"; + var url = null; - var p = window.swaggerUi.api.authSchemes; - for (var key in p) { - if (p.hasOwnProperty(key)) { - var o = p[key].grantTypes; - for(var t in o) { - if(o.hasOwnProperty(t) && t === 'implicit') { - var dets = o[t]; - url = dets.loginEndpoint.url + "?response_type=token"; - window.swaggerUi.tokenName = dets.tokenName; - } + for (var key in authSchemes) { + if (authSchemes.hasOwnProperty(key)) { + var o = authSchemes[key].grantTypes; + for(var t in o) { + if(o.hasOwnProperty(t) && t === 'implicit') { + var dets = o[t]; + url = dets.loginEndpoint.url + "?response_type=token"; + window.swaggerUi.tokenName = dets.tokenName; } } } - var scopes = []; - var scopeForUrl=''; - var o = $('.api-popup-scopes').find('input:checked'); + } + var scopes = [] + var o = $('.api-popup-scopes').find('input:checked'); - for(var k =0; k < o.length; k++) { - scopes.push($(o[k]).attr("scope")); - if(k > 0){ - scopeForUrl+=' '; - } - scopeForUrl+=$(o[k]).attr("scope"); - } + for(k =0; k < o.length; k++) { + scopes.push($(o[k]).attr("scope")); + } - window.enabledScopes=scopes; - + window.enabledScopes=scopes; - url += '&redirect_uri=' + encodeURIComponent(redirectUrl); - url += '&realm=' + encodeURIComponent(realm); - url += '&client_id=' + encodeURIComponent(clientId); - url += '&scope=' + encodeURIComponent(scopeForUrl); + url += '&redirect_uri=' + encodeURIComponent(redirectUrl); + url += '&realm=' + encodeURIComponent(realm); + url += '&client_id=' + encodeURIComponent(clientId); + url += '&scope=' + encodeURIComponent(scopes); + + window.open(url); + }); - window.open(url); - }); - } popupMask.show(); popupDialog.show(); return; @@ -211,7 +204,7 @@ function onOAuthComplete(token) { } }); - window.authorizations.add("key", new ApiKeyAuthorization("Authorization", "Bearer " + b, "header")); + window.authorizations.add("oauth2", new ApiKeyAuthorization("Authorization", "Bearer " + b, "header")); } } } diff --git a/htdocs/includes/restler/framework/Luracast/Restler/explorer/lib/swagger.js b/htdocs/includes/restler/framework/Luracast/Restler/explorer/lib/swagger.js index 2100bb81e83..9e73a9b33e2 100644 --- a/htdocs/includes/restler/framework/Luracast/Restler/explorer/lib/swagger.js +++ b/htdocs/includes/restler/framework/Luracast/Restler/explorer/lib/swagger.js @@ -1,5 +1,5 @@ // swagger.js -// version 2.0.30 +// version 2.0.39 var __bind = function(fn, me){ return function(){ @@ -11,10 +11,20 @@ log = function(){ log.history = log.history || []; log.history.push(arguments); if(this.console){ - console.log( Array.prototype.slice.call(arguments) ); + console.log( Array.prototype.slice.call(arguments)[0] ); } }; +// if you want to apply conditional formatting of parameter values +parameterMacro = function(value) { + return value; +} + +// if you want to apply conditional formatting of model property values +modelPropertyMacro = function(value) { + return value; +} + if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(obj, start) { for (var i = (start || 0), j = this.length; i < j; i++) { @@ -45,48 +55,50 @@ if (!('map' in Array.prototype)) { } Object.keys = Object.keys || (function () { - var hasOwnProperty = Object.prototype.hasOwnProperty, - hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"), - DontEnums = [ - 'toString', - 'toLocaleString', - 'valueOf', - 'hasOwnProperty', - 'isPrototypeOf', - 'propertyIsEnumerable', - 'constructor' - ], - DontEnumsLength = DontEnums.length; - - return function (o) { - if (typeof o != "object" && typeof o != "function" || o === null) - throw new TypeError("Object.keys called on a non-object"); - - var result = []; - for (var name in o) { - if (hasOwnProperty.call(o, name)) - result.push(name); - } - - if (hasDontEnumBug) { - for (var i = 0; i < DontEnumsLength; i++) { - if (hasOwnProperty.call(o, DontEnums[i])) - result.push(DontEnums[i]); - } - } - - return result; - }; + var hasOwnProperty = Object.prototype.hasOwnProperty, + hasDontEnumBug = !{toString:null}.propertyIsEnumerable("toString"), + DontEnums = [ + 'toString', + 'toLocaleString', + 'valueOf', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor' + ], + DontEnumsLength = DontEnums.length; + + return function (o) { + if (typeof o != "object" && typeof o != "function" || o === null) + throw new TypeError("Object.keys called on a non-object"); + + var result = []; + for (var name in o) { + if (hasOwnProperty.call(o, name)) + result.push(name); + } + + if (hasDontEnumBug) { + for (var i = 0; i < DontEnumsLength; i++) { + if (hasOwnProperty.call(o, DontEnums[i])) + result.push(DontEnums[i]); + } + } + + return result; + }; })(); - var SwaggerApi = function(url, options) { + this.isBuilt = false; this.url = null; this.debug = false; this.basePath = null; this.authorizations = null; this.authorizationScheme = null; this.info = null; + this.useJQuery = false; + this.modelsArray = []; options = (options||{}); if (url) @@ -103,13 +115,20 @@ var SwaggerApi = function(url, options) { if (options.success != null) this.success = options.success; + if (typeof options.useJQuery === 'boolean') + this.useJQuery = options.useJQuery; + this.failure = options.failure != null ? options.failure : function() {}; this.progress = options.progress != null ? options.progress : function() {}; - if (options.success != null) + if (options.success != null) { this.build(); + this.isBuilt = true; + } } SwaggerApi.prototype.build = function() { + if(this.isBuilt) + return this; var _this = this; this.progress('fetching resource list: ' + this.url); var obj = { @@ -117,7 +136,7 @@ SwaggerApi.prototype.build = function() { url: this.url, method: "get", headers: { - accept: "application/json" + accept: "application/json,application/json;charset=\"utf-8\",*/*" }, on: { error: function(response) { @@ -154,6 +173,7 @@ SwaggerApi.prototype.buildFromSpec = function(response) { } this.apis = {}; this.apisArray = []; + this.consumes = response.consumes; this.produces = response.produces; this.authSchemes = response.authorizations; if (response.info != null) { @@ -171,13 +191,13 @@ SwaggerApi.prototype.buildFromSpec = function(response) { } } } - if (response.basePath) { + if (response.basePath) this.basePath = response.basePath; - } else if (this.url.indexOf('?') > 0) { + else if (this.url.indexOf('?') > 0) this.basePath = this.url.substring(0, this.url.lastIndexOf('?')); - } else { + else this.basePath = this.url; - } + if (isApi) { var newName = response.resourcePath.replace(/\//g, ''); this.resourcePath = response.resourcePath; @@ -272,7 +292,6 @@ SwaggerApi.prototype.fail = function(message) { SwaggerApi.prototype.setConsolidatedModels = function() { var model, modelName, resource, resource_name, _i, _len, _ref, _ref1, _results; - this.modelsArray = []; this.models = {}; _ref = this.apis; for (resource_name in _ref) { @@ -317,8 +336,8 @@ var SwaggerResource = function(resourceObj, api) { var _this = this; this.api = api; this.api = this.api; - produces = []; - consumes = []; + consumes = (this.consumes | []); + produces = (this.produces | []); this.path = this.api.resourcePath != null ? this.api.resourcePath : resourceObj.path; this.description = resourceObj.description; @@ -349,7 +368,7 @@ var SwaggerResource = function(resourceObj, api) { method: "get", useJQuery: this.useJQuery, headers: { - accept: "application/json" + accept: "application/json,application/json;charset=\"utf-8\",*/*" }, on: { response: function(resp) { @@ -368,22 +387,28 @@ var SwaggerResource = function(resourceObj, api) { } } -SwaggerResource.prototype.getAbsoluteBasePath = function(relativeBasePath) { - var parts, pos, url; +SwaggerResource.prototype.getAbsoluteBasePath = function (relativeBasePath) { + var pos, url; url = this.api.basePath; pos = url.lastIndexOf(relativeBasePath); - if (pos === -1) { - parts = url.split("/"); - url = parts[0] + "//" + parts[2]; - if (relativeBasePath.indexOf("/") === 0) { - return url + relativeBasePath; - } else { - return url + "/" + relativeBasePath; - } - } else if (relativeBasePath === "/") { - return url.substring(0, pos); - } else { - return url.substring(0, pos) + relativeBasePath; + var parts = url.split("/"); + var rootUrl = parts[0] + "//" + parts[2]; + + if(relativeBasePath.indexOf("http") === 0) + return relativeBasePath; + if(relativeBasePath === "/") + return rootUrl; + if(relativeBasePath.substring(0, 1) == "/") { + // use root + relative + return rootUrl + relativeBasePath; + } + else { + var pos = this.basePath.lastIndexOf("/"); + var base = this.basePath.substring(0, pos); + if(base.substring(base.length - 1) == "/") + return base + relativeBasePath; + else + return base + "/" + relativeBasePath; } }; @@ -478,8 +503,7 @@ SwaggerResource.prototype.addOperations = function(resource_path, ops, consumes, SwaggerResource.prototype.sanitize = function(nickname) { var op; - op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|./?,\\'""-]/g, '_'); - //' + op = nickname.replace(/[\s!@#$%^&*()_+=\[{\]};:<>|.\/?,\\'""-]/g, '_'); op = op.replace(/((_){2,})/g, '_'); op = op.replace(/^(_)*/g, ''); op = op.replace(/([_])*$/g, ''); @@ -584,6 +608,7 @@ var SwaggerModelProperty = function(name, obj) { this.isCollection = this.dataType && (this.dataType.toLowerCase() === 'array' || this.dataType.toLowerCase() === 'list' || this.dataType.toLowerCase() === 'set'); this.descr = obj.description; this.required = obj.required; + this.defaultValue = modelPropertyMacro(obj.defaultValue); if (obj.items != null) { if (obj.items.type != null) { this.refDataType = obj.items.type; @@ -629,7 +654,9 @@ SwaggerModelProperty.prototype.getSampleValue = function(modelsToIgnore) { SwaggerModelProperty.prototype.toSampleValue = function(value) { var result; - if (value === "integer") { + if ((typeof this.defaultValue !== 'undefined') && this.defaultValue !== null) { + result = this.defaultValue; + } else if (value === "integer") { result = 0; } else if (value === "boolean") { result = false; @@ -759,6 +786,7 @@ var SwaggerOperation = function(nickname, path, method, parameters, summary, not } } } + param.defaultValue = parameterMacro(param.defaultValue); } this.resource[this.nickname] = function(args, callback, error) { return _this["do"](args, callback, error); @@ -812,7 +840,7 @@ SwaggerOperation.prototype.getSampleJSON = function(type, models) { else return JSON.stringify(val, null, 2); } - else + else return val; } }; @@ -1073,7 +1101,7 @@ SwaggerOperation.prototype.formatXml = function(xml) { var SwaggerRequest = function(type, url, params, opts, successCallback, errorCallback, operation, execution) { var _this = this; var errors = []; - this.useJQuery = (typeof operation.useJQuery !== 'undefined' ? operation.useJQuery : null); + this.useJQuery = (typeof operation.resource.useJQuery !== 'undefined' ? operation.resource.useJQuery : null); this.type = (type||errors.push("SwaggerRequest type is required (get/post/put/delete/patch/options).")); this.url = (url||errors.push("SwaggerRequest url is required.")); this.params = params; @@ -1090,96 +1118,59 @@ var SwaggerRequest = function(type, url, params, opts, successCallback, errorCal this.type = this.type.toUpperCase(); - var myHeaders = {}; + // set request, response content type headers + var headers = this.setHeaders(params, this.operation); var body = params.body; - var parent = params["parent"]; - var requestContentType = "application/json"; - var formParams = []; - var fileParams = []; - var params = this.operation.parameters; - - - for(var i = 0; i < params.length; i++) { - var param = params[i]; - if(param.paramType === "form") - formParams.push(param); - else if(param.paramType === "file") - fileParams.push(param); - } - - - if (body && (this.type === "POST" || this.type === "PUT" || this.type === "PATCH")) { - if (this.opts.requestContentType) { - requestContentType = this.opts.requestContentType; - } - } else { - // if any form params, content type must be set - if(formParams.length > 0) { - if(fileParams.length > 0) - requestContentType = "multipart/form-data"; - else - requestContentType = "application/x-www-form-urlencoded"; - } - else if (this.type != "DELETE") - requestContentType = null; - } - - if (requestContentType && this.operation.consumes) { - if (this.operation.consumes[requestContentType] === 'undefined') { - log("server doesn't consume " + requestContentType + ", try " + JSON.stringify(this.operation.consumes)); - if (this.requestContentType === null) { - requestContentType = this.operation.consumes[0]; - } - } - } - - var responseContentType = null; - if (this.opts.responseContentType) { - responseContentType = this.opts.responseContentType; - } else { - responseContentType = "application/json"; - } - if (responseContentType && this.operation.produces) { - if (this.operation.produces[responseContentType] === 'undefined') { - log("server can't produce " + responseContentType); - } - } - if (requestContentType && requestContentType.indexOf("application/x-www-form-urlencoded") === 0) { - var fields = {}; - var possibleParams = {}; + // encode the body for form submits + if (headers["Content-Type"]) { var values = {}; - var key; - for(key in formParams){ - var param = formParams[key]; - values[param.name] = param; + var i; + var operationParams = this.operation.parameters; + for(i = 0; i < operationParams.length; i++) { + var param = operationParams[i]; + if(param.paramType === "form") + values[param.name] = param; } - var encoded = ""; - var key; - for(key in values) { - value = this.params[key]; - if(typeof value !== 'undefined'){ - if(encoded !== "") - encoded += "&"; - encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value); + if(headers["Content-Type"].indexOf("application/x-www-form-urlencoded") === 0) { + var encoded = ""; + var key; + for(key in values) { + value = this.params[key]; + if(typeof value !== 'undefined'){ + if(encoded !== "") + encoded += "&"; + encoded += encodeURIComponent(key) + '=' + encodeURIComponent(value); + } } + body = encoded; + } + else if (headers["Content-Type"].indexOf("multipart/form-data") === 0) { + // encode the body for form submits + var data = ""; + var boundary = "----SwaggerFormBoundary" + Date.now(); + var key; + for(key in values) { + value = this.params[key]; + if(typeof value !== 'undefined') { + data += '--' + boundary + '\n'; + data += 'Content-Disposition: form-data; name="' + key + '"'; + data += '\n\n'; + data += value + "\n"; + } + } + data += "--" + boundary + "--\n"; + headers["Content-Type"] = "multipart/form-data; boundary=" + boundary; + body = data; } - body = encoded; } - var name; - for (name in this.headers) - myHeaders[name] = this.headers[name]; - if ((requestContentType && body !== "") || (requestContentType === "application/x-www-form-urlencoded")) - myHeaders["Content-Type"] = requestContentType; - if (responseContentType) - myHeaders["Accept"] = responseContentType; if (!((this.headers != null) && (this.headers.mock != null))) { obj = { url: this.url, method: this.type, - headers: myHeaders, + headers: headers, body: body, useJQuery: this.useJQuery, on: { @@ -1216,6 +1207,77 @@ var SwaggerRequest = function(type, url, params, opts, successCallback, errorCal } }; +SwaggerRequest.prototype.setHeaders = function(params, operation) { + // default type + var accepts = "application/json"; + var consumes = "application/json"; + + var allDefinedParams = this.operation.parameters; + var definedFormParams = []; + var definedFileParams = []; + var body = params.body; + var headers = {}; + + // get params from the operation and set them in definedFileParams, definedFormParams, headers + var i; + for(i = 0; i < allDefinedParams.length; i++) { + var param = allDefinedParams[i]; + if(param.paramType === "form") + definedFormParams.push(param); + else if(param.paramType === "file") + definedFileParams.push(param); + else if(param.paramType === "header" && this.params.headers) { + var key = param.name; + var headerValue = this.params.headers[param.name]; + if(typeof this.params.headers[param.name] !== 'undefined') + headers[key] = headerValue; + } + } + + // if there's a body, need to set the accepts header via requestContentType + if (body && (this.type === "POST" || this.type === "PUT" || this.type === "PATCH" || this.type === "DELETE")) { + if (this.opts.requestContentType) + consumes = this.opts.requestContentType; + } else { + // if any form params, content type must be set + if(definedFormParams.length > 0) { + if(definedFileParams.length > 0) + consumes = "multipart/form-data"; + else + consumes = "application/x-www-form-urlencoded"; + } + else if (this.type === "DELETE") + body = "{}"; + else if (this.type != "DELETE") + accepts = null; + } + + if (consumes && this.operation.consumes) { + if (this.operation.consumes.indexOf(consumes) === -1) { + log("server doesn't consume " + consumes + ", try " + JSON.stringify(this.operation.consumes)); + consumes = this.operation.consumes[0]; + } + } + + if (this.opts.responseContentType) { + accepts = this.opts.responseContentType; + } else { + accepts = "application/json"; + } + if (accepts && this.operation.produces) { + if (this.operation.produces.indexOf(accepts) === -1) { + log("server can't produce " + accepts); + accepts = this.operation.produces[0]; + } + } + + if ((consumes && body !== "") || (consumes === "application/x-www-form-urlencoded")) + headers["Content-Type"] = consumes; + if (accepts) + headers["Accept"] = accepts; + return headers; +} + SwaggerRequest.prototype.asCurl = function() { var results = []; if(this.headers) { @@ -1259,9 +1321,16 @@ SwaggerHttp.prototype.isIE8 = function() { }; /* - * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic + * JQueryHttpClient lets a browser take advantage of JQuery's cross-browser magic. + * NOTE: when jQuery is available it will export both '$' and 'jQuery' to the global space. + * Since we are using closures here we need to alias it for internal use. */ -var JQueryHttpClient = function(options) {} +var JQueryHttpClient = function(options) { + "use strict"; + if(!jQuery){ + var jQuery = window.jQuery; + } +} JQueryHttpClient.prototype.execute = function(obj) { var cb = obj.on; @@ -1335,8 +1404,8 @@ JQueryHttpClient.prototype.execute = function(obj) { return cb.response(out); }; - $.support.cors = true; - return $.ajax(obj); + jQuery.support.cors = true; + return jQuery.ajax(obj); } /* @@ -1411,11 +1480,36 @@ ShredHttpClient.prototype.execute = function(obj) { return out; }; + // Transform an error into a usable response-like object + var transformError = function(error) { + var out = { + // Default to a status of 0 - The client will treat this as a generic permissions sort of error + status: 0, + data: error.message || error + }; + + if(error.code) { + out.obj = error; + + if(error.code === 'ENOTFOUND' || error.code === 'ECONNREFUSED' ) { + // We can tell the client that this should be treated as a missing resource and not as a permissions thing + out.status = 404; + } + } + + return out; + }; + res = { error: function(response) { if (obj) return cb.error(transform(response)); }, + // Catch the Shred error raised when the request errors as it is made (i.e. No Response is coming) + request_error: function(err) { + if(obj) + return cb.error(transformError(err)); + }, redirect: function(response) { if (obj) return cb.redirect(transform(response)); @@ -1452,26 +1546,42 @@ SwaggerAuthorizations.prototype.remove = function(name) { }; SwaggerAuthorizations.prototype.apply = function(obj, authorizations) { - status = null; + var status = null; var key; - for (key in this.authz) { - value = this.authz[key]; - result = value.apply(obj, authorizations); - if (result === false) - status = false; - if (result === true) - status = true; + + // if the "authorizations" key is undefined, or has an empty array, add all keys + if(typeof authorizations === 'undefined' || Object.keys(authorizations).length == 0) { + for (key in this.authz) { + value = this.authz[key]; + result = value.apply(obj, authorizations); + if (result === true) + status = true; + } } + else { + for(name in authorizations) { + for (key in this.authz) { + if(key == name) { + value = this.authz[key]; + result = value.apply(obj, authorizations); + if (result === true) + status = true; + } + } + } + } + return status; }; /** * ApiKeyAuthorization allows a query param or header to be injected */ -var ApiKeyAuthorization = function(name, value, type) { +var ApiKeyAuthorization = function(name, value, type, delimiter) { this.name = name; this.value = value; this.type = type; + this.delimiter = delimiter; }; ApiKeyAuthorization.prototype.apply = function(obj, authorizations) { @@ -1482,7 +1592,12 @@ ApiKeyAuthorization.prototype.apply = function(obj, authorizations) { obj.url = obj.url + "?" + this.name + "=" + this.value; return true; } else if (this.type === "header") { - obj.headers[this.name] = this.value; + if(typeof obj.headers[this.name] !== 'undefined') { + if(typeof this.delimiter !== 'undefined') + obj.headers[this.name] = obj.headers[this.name] + this.delimiter + this.value; + } + else + obj.headers[this.name] = this.value; return true; } }; diff --git a/htdocs/includes/restler/framework/Luracast/Restler/explorer/swagger-ui.js b/htdocs/includes/restler/framework/Luracast/Restler/explorer/swagger-ui.js index 5c6aad20be6..c28bf145ab6 100644 --- a/htdocs/includes/restler/framework/Luracast/Restler/explorer/swagger-ui.js +++ b/htdocs/includes/restler/framework/Luracast/Restler/explorer/swagger-ui.js @@ -1,5 +1,5 @@ // swagger-ui.js -// version 2.0.17 +// version 2.0.23 $(function() { // Helper function for vertically aligning DOM elements @@ -68,7 +68,7 @@ log = function(){ log.history = log.history || []; log.history.push(arguments); if(this.console){ - console.log( Array.prototype.slice.call(arguments) ); + console.log( Array.prototype.slice.call(arguments)[0] ); } }; @@ -240,67 +240,74 @@ helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; function program1(depth0,data) { var buffer = "", stack1, stack2; - buffer += "\n "; + buffer += "\n
" + + escapeExpression(((stack1 = ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.title)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + + "
\n
"; + stack2 = ((stack1 = ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.description)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1); + if(stack2 || stack2 === 0) { buffer += stack2; } + buffer += "
\n "; stack2 = helpers['if'].call(depth0, ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.termsOfServiceUrl), {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data}); if(stack2 || stack2 === 0) { buffer += stack2; } - buffer += "\n "; + buffer += "\n "; stack2 = helpers['if'].call(depth0, ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.contact), {hash:{},inverse:self.noop,fn:self.program(4, program4, data),data:data}); if(stack2 || stack2 === 0) { buffer += stack2; } - buffer += "\n "; + buffer += "\n "; stack2 = helpers['if'].call(depth0, ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.license), {hash:{},inverse:self.noop,fn:self.program(6, program6, data),data:data}); if(stack2 || stack2 === 0) { buffer += stack2; } - buffer += "\n "; + buffer += "\n "; return buffer; } function program2(depth0,data) { var buffer = "", stack1; - buffer += "
  • Terms
  • "; + + "\">Terms of service
    "; return buffer; } function program4(depth0,data) { var buffer = "", stack1; - buffer += "
  • Contact
  • "; + + "\">Contact the developer"; return buffer; } function program6(depth0,data) { var buffer = "", stack1; - buffer += "
  • " + escapeExpression(((stack1 = ((stack1 = depth0.info),stack1 == null || stack1 === false ? stack1 : stack1.license)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) - + "\"> License
  • "; + + ""; return buffer; } function program8(depth0,data) { var buffer = "", stack1; - buffer += " v"; + buffer += "\n , api version: "; if (stack1 = helpers.apiVersion) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.apiVersion; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } - buffer += escapeExpression(stack1); + buffer += escapeExpression(stack1) + + "\n "; return buffer; } - buffer += "
    \n
    \n
    \n
      \n
    \n\n
    \n
      \n "; + buffer += "
      \n "; stack1 = helpers['if'].call(depth0, depth0.info, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } - buffer += "\n
    • \n "; + buffer += "\n
    • \n
      \n
        \n
      \n\n
      \n
      \n
      \n

      [ base url: "; if (stack1 = helpers.basePath) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.basePath; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } - buffer += escapeExpression(stack1); + buffer += escapeExpression(stack1) + + "\n "; stack1 = helpers['if'].call(depth0, depth0.apiVersion, {hash:{},inverse:self.noop,fn:self.program(8, program8, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } - buffer += " Powered by Restler & Swagger\n \n

    \n
    \n
    \n"; + buffer += "]\n \n\n"; return buffer; }); })(); @@ -389,7 +396,7 @@ function program18(depth0,data) { function program20(depth0,data) { - return "\n
    \n \n \n \n
    \n "; + return "\n
    \n \n \n \n
    \n "; } buffer += "\n
      \n
    • \n "; + + "'/>\n "; return buffer; } -function program12(depth0,data) { +function program13(depth0,data) { var buffer = "", stack1; - buffer += "\n \n "; + + "' placeholder='' type='text' value=''/>\n "; return buffer; } @@ -1057,23 +1073,19 @@ helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; function program1(depth0,data) { - var buffer = "", stack1; - buffer += " : "; - if (stack1 = helpers.description) { stack1 = stack1.call(depth0, {hash:{},data:data}); } - else { stack1 = depth0.description; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } - if(stack1 || stack1 === 0) { buffer += stack1; } - return buffer; + + return " : "; } buffer += "
      \n

      \n "; + + "\">"; if (stack1 = helpers.name) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) @@ -1083,6 +1095,9 @@ function program1(depth0,data) { else { stack1 = depth0.description; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } if (!helpers.description) { stack1 = blockHelperMissing.call(depth0, stack1, options); } if(stack1 || stack1 === 0) { buffer += stack1; } + if (stack1 = helpers.description) { stack1 = stack1.call(depth0, {hash:{},data:data}); } + else { stack1 = depth0.description; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } + if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n

      \n
        \n
      • \n Show/Hide\n
      • \n
      • \n Show/Hide\n
      • \n
      • \n \n List Operations\n \n
      • \n
      • \n \n List Operations\n \n
      • \n
      • \n \n Expand Operations\n \n
      • \n
      • \n 0) { map[o.name] = o.value; } @@ -1708,16 +1750,16 @@ helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; isFileUpload = true; } } - _ref1 = form.find("textarea"); - for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { - o = _ref1[_j]; + _ref6 = form.find("textarea"); + for (_j = 0, _len1 = _ref6.length; _j < _len1; _j++) { + o = _ref6[_j]; if ((o.value != null) && jQuery.trim(o.value).length > 0) { map["body"] = o.value; } } - _ref2 = form.find("select"); - for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { - o = _ref2[_k]; + _ref7 = form.find("select"); + for (_k = 0, _len2 = _ref7.length; _k < _len2; _k++) { + o = _ref7[_k]; val = this.getSelectedValue(o); if ((val != null) && jQuery.trim(val).length > 0) { map[o.name] = val; @@ -1739,46 +1781,46 @@ helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; }; OperationView.prototype.handleFileUpload = function(map, form) { - var bodyParam, el, headerParams, o, obj, param, params, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2, _ref3, + var bodyParam, el, headerParams, o, obj, param, params, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref5, _ref6, _ref7, _ref8, _this = this; - _ref = form.serializeArray(); - for (_i = 0, _len = _ref.length; _i < _len; _i++) { - o = _ref[_i]; + _ref5 = form.serializeArray(); + for (_i = 0, _len = _ref5.length; _i < _len; _i++) { + o = _ref5[_i]; if ((o.value != null) && jQuery.trim(o.value).length > 0) { map[o.name] = o.value; } } bodyParam = new FormData(); params = 0; - _ref1 = this.model.parameters; - for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { - param = _ref1[_j]; + _ref6 = this.model.parameters; + for (_j = 0, _len1 = _ref6.length; _j < _len1; _j++) { + param = _ref6[_j]; if (param.paramType === 'form') { - if (map[param.name] !== void 0) { + if (param.type.toLowerCase() !== 'file' && map[param.name] !== void 0) { bodyParam.append(param.name, map[param.name]); } } } headerParams = {}; - _ref2 = this.model.parameters; - for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { - param = _ref2[_k]; + _ref7 = this.model.parameters; + for (_k = 0, _len2 = _ref7.length; _k < _len2; _k++) { + param = _ref7[_k]; if (param.paramType === 'header') { headerParams[param.name] = map[param.name]; } } log(headerParams); - _ref3 = form.find('input[type~="file"]'); - for (_l = 0, _len3 = _ref3.length; _l < _len3; _l++) { - el = _ref3[_l]; + _ref8 = form.find('input[type~="file"]'); + for (_l = 0, _len3 = _ref8.length; _l < _len3; _l++) { + el = _ref8[_l]; if (typeof el.files[0] !== 'undefined') { bodyParam.append($(el).attr('name'), el.files[0]); params += 1; } } - log(bodyParam); this.invocationUrl = this.model.supportHeaderParams() ? (headerParams = this.model.getHeaderParams(map), this.model.urlify(map, false)) : this.model.urlify(map, true); - $(".request_url", $(this.el)).html("
        " + this.invocationUrl + "
        "); + $(".request_url", $(this.el)).html("
        ");
        +      $(".request_url pre", $(this.el)).text(this.invocationUrl);
               obj = {
                 type: this.model.method,
                 url: this.invocationUrl,
        @@ -1829,14 +1871,14 @@ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
             };
         
             OperationView.prototype.getSelectedValue = function(select) {
        -      var opt, options, _i, _len, _ref;
        +      var opt, options, _i, _len, _ref5;
               if (!select.multiple) {
                 return select.value;
               } else {
                 options = [];
        -        _ref = select.options;
        -        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        -          opt = _ref[_i];
        +        _ref5 = select.options;
        +        for (_i = 0, _len = _ref5.length; _i < _len; _i++) {
        +          opt = _ref5[_i];
                   if (opt.selected) {
                     options.push(opt.value);
                   }
        @@ -1924,9 +1966,9 @@ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
                 padding = '';
                 indent += transitions[fromTo];
                 padding = ((function() {
        -          var _j, _ref, _results;
        +          var _j, _ref5, _results;
                   _results = [];
        -          for (j = _j = 0, _ref = indent; 0 <= _ref ? _j < _ref : _j > _ref; j = 0 <= _ref ? ++_j : --_j) {
        +          for (j = _j = 0, _ref5 = indent; 0 <= _ref5 ? _j < _ref5 : _j > _ref5; j = 0 <= _ref5 ? ++_j : --_j) {
                     _results.push('  ');
                   }
                   return _results;
        @@ -1945,7 +1987,7 @@ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
             };
         
             OperationView.prototype.showStatus = function(response) {
        -      var code, content, contentType, headers, pre, response_body, url;
        +      var code, content, contentType, headers, opts, pre, response_body, response_body_el, url;
               if (response.content === void 0) {
                 content = response.data;
                 url = response.url;
        @@ -1974,14 +2016,21 @@ helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
                 pre = $('
        ').append(code);
               }
               response_body = pre;
        -      $(".request_url", $(this.el)).html("
        " + url + "
        "); + $(".request_url", $(this.el)).html("
        ");
        +      $(".request_url pre", $(this.el)).text(url);
               $(".response_code", $(this.el)).html("
        " + response.status + "
        "); $(".response_body", $(this.el)).html(response_body); - $(".response_headers", $(this.el)).html("
        " + JSON.stringify(response.headers, null, "  ").replace(/\n/g, "
        ") + "
        "); + $(".response_headers", $(this.el)).html("
        " + _.escape(JSON.stringify(response.headers, null, "  ")).replace(/\n/g, "
        ") + "
        "); $(".response", $(this.el)).slideDown(); $(".response_hider", $(this.el)).show(); $(".response_throbber", $(this.el)).hide(); - return hljs.highlightBlock($('.response_body', $(this.el))[0]); + response_body_el = $('.response_body', $(this.el))[0]; + opts = this.options.swaggerOptions; + if (opts.highlightSizeThreshold && response.data.length > opts.highlightSizeThreshold) { + return response_body_el; + } else { + return hljs.highlightBlock(response_body_el); + } }; OperationView.prototype.toggleOperationContent = function() { @@ -1999,11 +2048,11 @@ helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; })(Backbone.View); StatusCodeView = (function(_super) { - __extends(StatusCodeView, _super); function StatusCodeView() { - StatusCodeView.__super__.constructor.apply(this, arguments); + _ref5 = StatusCodeView.__super__.constructor.apply(this, arguments); + return _ref5; } StatusCodeView.prototype.initialize = function() {}; @@ -2038,11 +2087,11 @@ helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; })(Backbone.View); ParameterView = (function(_super) { - __extends(ParameterView, _super); function ParameterView() { - ParameterView.__super__.constructor.apply(this, arguments); + _ref6 = ParameterView.__super__.constructor.apply(this, arguments); + return _ref6; } ParameterView.prototype.initialize = function() { @@ -2127,11 +2176,11 @@ helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; })(Backbone.View); SignatureView = (function(_super) { - __extends(SignatureView, _super); function SignatureView() { - SignatureView.__super__.constructor.apply(this, arguments); + _ref7 = SignatureView.__super__.constructor.apply(this, arguments); + return _ref7; } SignatureView.prototype.events = { @@ -2146,7 +2195,7 @@ helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var template; template = this.template(); $(this.el).html(template(this.model)); - this.switchToDescription(); + this.switchToSnippet(); this.isParam = this.model.isParam; if (this.isParam) { $('.notice', $(this.el)).text('Click to set as parameter value'); @@ -2196,11 +2245,11 @@ helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; })(Backbone.View); ContentTypeView = (function(_super) { - __extends(ContentTypeView, _super); function ContentTypeView() { - ContentTypeView.__super__.constructor.apply(this, arguments); + _ref8 = ContentTypeView.__super__.constructor.apply(this, arguments); + return _ref8; } ContentTypeView.prototype.initialize = function() {}; @@ -2222,11 +2271,11 @@ helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; })(Backbone.View); ResponseContentTypeView = (function(_super) { - __extends(ResponseContentTypeView, _super); function ResponseContentTypeView() { - ResponseContentTypeView.__super__.constructor.apply(this, arguments); + _ref9 = ResponseContentTypeView.__super__.constructor.apply(this, arguments); + return _ref9; } ResponseContentTypeView.prototype.initialize = function() {}; @@ -2248,11 +2297,11 @@ helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; })(Backbone.View); ParameterContentTypeView = (function(_super) { - __extends(ParameterContentTypeView, _super); function ParameterContentTypeView() { - ParameterContentTypeView.__super__.constructor.apply(this, arguments); + _ref10 = ParameterContentTypeView.__super__.constructor.apply(this, arguments); + return _ref10; } ParameterContentTypeView.prototype.initialize = function() {}; diff --git a/htdocs/includes/restler/framework/Luracast/Restler/explorer/swagger-ui.min.js b/htdocs/includes/restler/framework/Luracast/Restler/explorer/swagger-ui.min.js index a1e827a1029..2956b613b0f 100644 --- a/htdocs/includes/restler/framework/Luracast/Restler/explorer/swagger-ui.min.js +++ b/htdocs/includes/restler/framework/Luracast/Restler/explorer/swagger-ui.min.js @@ -1 +1 @@ -$(function(){$.fn.vAlign=function(){return this.each(function(c){var a=$(this).height();var d=$(this).parent().height();var b=(d-a)/2;$(this).css("margin-top",b)})};$.fn.stretchFormtasticInputWidthToParent=function(){return this.each(function(b){var d=$(this).closest("form").innerWidth();var c=parseInt($(this).closest("form").css("padding-left"),10)+parseInt($(this).closest("form").css("padding-right"),10);var a=parseInt($(this).css("padding-left"),10)+parseInt($(this).css("padding-right"),10);$(this).css("width",d-c-a)})};$("form.formtastic li.string input, form.formtastic textarea").stretchFormtasticInputWidthToParent();$("ul.downplayed li div.content p").vAlign();$("form.sandbox").submit(function(){var a=true;$(this).find("input.required").each(function(){$(this).removeClass("error");if($(this).val()==""){$(this).addClass("error");$(this).wiggle();a=false}});return a})});function clippyCopiedCallback(b){$("#api_key_copied").fadeIn().delay(1000).fadeOut()}log=function(){log.history=log.history||[];log.history.push(arguments);if(this.console){console.log(Array.prototype.slice.call(arguments))}};if(Function.prototype.bind&&console&&typeof console.log=="object"){["log","info","warn","error","assert","dir","clear","profile","profileEnd"].forEach(function(a){console[a]=this.bind(console[a],console)},Function.prototype.call)}var Docs={shebang:function(){var b=$.param.fragment().split("/");b.shift();switch(b.length){case 1:log("shebang resource:"+b[0]);var d="resource_"+b[0];Docs.expandEndpointListForResource(b[0]);$("#"+d).slideto({highlight:false});break;case 2:log("shebang endpoint: "+b.join("_"));Docs.expandEndpointListForResource(b[0]);$("#"+d).slideto({highlight:false});var c=b.join("_");var a=c+"_content";log("li_dom_id "+c);log("li_content_dom_id "+a);Docs.expandOperation($("#"+a));$("#"+c).slideto({highlight:false});break}},toggleEndpointListForResource:function(b){var a=$("li#resource_"+Docs.escapeResourceName(b)+" ul.endpoints");if(a.is(":visible")){Docs.collapseEndpointListForResource(b)}else{Docs.expandEndpointListForResource(b)}},expandEndpointListForResource:function(b){var b=Docs.escapeResourceName(b);if(b==""){$(".resource ul.endpoints").slideDown();return}$("li#resource_"+b).addClass("active");var a=$("li#resource_"+b+" ul.endpoints");a.slideDown()},collapseEndpointListForResource:function(b){var b=Docs.escapeResourceName(b);$("li#resource_"+b).removeClass("active");var a=$("li#resource_"+b+" ul.endpoints");a.slideUp()},expandOperationsForResource:function(a){Docs.expandEndpointListForResource(a);if(a==""){$(".resource ul.endpoints li.operation div.content").slideDown();return}$("li#resource_"+Docs.escapeResourceName(a)+" li.operation div.content").each(function(){Docs.expandOperation($(this))})},collapseOperationsForResource:function(a){Docs.expandEndpointListForResource(a);$("li#resource_"+Docs.escapeResourceName(a)+" li.operation div.content").each(function(){Docs.collapseOperation($(this))})},escapeResourceName:function(a){return a.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g,"\\$&")},expandOperation:function(a){a.slideDown()},collapseOperation:function(a){a.slideUp()}};(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.content_type=b(function(g,l,f,k,j){this.compilerInfo=[4,">= 1.0.0"];f=this.merge(f,g.helpers);j=j||{};var i="",c,h="function",m=this;function e(r,q){var o="",p;o+="\n ";p=f.each.call(r,r.produces,{hash:{},inverse:m.noop,fn:m.program(2,d,q),data:q});if(p||p===0){o+=p}o+="\n";return o}function d(r,q){var o="",p;o+='\n \n ";return o}function n(p,o){return'\n \n'}i+='\n\n";return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.main=b(function(g,m,f,l,k){this.compilerInfo=[4,">= 1.0.0"];f=this.merge(f,g.helpers);k=k||{};var i="",c,h="function",j=this.escapeExpression,p=this;function e(v,u){var r="",t,s;r+="\n ";s=f["if"].call(v,((t=v.info),t==null||t===false?t:t.termsOfServiceUrl),{hash:{},inverse:p.noop,fn:p.program(2,d,u),data:u});if(s||s===0){r+=s}r+="\n ";s=f["if"].call(v,((t=v.info),t==null||t===false?t:t.contact),{hash:{},inverse:p.noop,fn:p.program(4,q,u),data:u});if(s||s===0){r+=s}r+="\n ";s=f["if"].call(v,((t=v.info),t==null||t===false?t:t.license),{hash:{},inverse:p.noop,fn:p.program(6,o,u),data:u});if(s||s===0){r+=s}r+="\n ";return r}function d(u,t){var r="",s;r+='
      • Terms
      • ';return r}function q(u,t){var r="",s;r+='
      • Contact
      • ';return r}function o(u,t){var r="",s;r+='
      • License
      • ';return r}function n(u,t){var r="",s;r+=" v";if(s=f.apiVersion){s=s.call(u,{hash:{},data:t})}else{s=u.apiVersion;s=typeof s===h?s.apply(u):s}r+=j(s);return r}i+="
        \n
        \n
        \n
          \n
        \n\n
        \n
          \n ";c=f["if"].call(m,m.info,{hash:{},inverse:p.noop,fn:p.program(1,e,k),data:k});if(c||c===0){i+=c}i+="\n
        • \n ";if(c=f.basePath){c=c.call(m,{hash:{},data:k})}else{c=m.basePath;c=typeof c===h?c.apply(m):c}i+=j(c);c=f["if"].call(m,m.apiVersion,{hash:{},inverse:p.noop,fn:p.program(8,n,k),data:k});if(c||c===0){i+=c}i+=" Powered by Restler & Swagger\n
        • \n
        \n
        \n
        \n";return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.operation=b(function(g,s,q,m,y){this.compilerInfo=[4,">= 1.0.0"];q=this.merge(q,g.helpers);y=y||{};var r="",i,f,e="function",d=this.escapeExpression,p=this,c=q.blockHelperMissing;function o(C,B){var z="",A;z+="\n

        Implementation Notes

        \n

        ";if(A=q.notes){A=A.call(C,{hash:{},data:B})}else{A=C.notes;A=typeof A===e?A.apply(C):A}if(A||A===0){z+=A}z+="

        \n ";return z}function n(A,z){return'\n
        \n '}function l(C,B){var z="",A;z+='\n \n ";return z}function k(D,C){var z="",B,A;z+="\n
        "+d(((B=D.scope),typeof B===e?B.apply(D):B))+"
        \n ";return z}function h(A,z){return"
        "}function x(A,z){return'\n
        \n \n
        \n '}function w(A,z){return'\n

        Response Class

        \n

        \n
        \n
        \n '}function v(A,z){return'\n

        Parameters

        \n \n \n \n \n \n \n \n \n \n \n \n\n \n
        ParameterValueDescriptionParameter TypeData Type
        \n '}function u(A,z){return"\n
        \n

        Response Messages

        \n \n \n \n \n \n \n \n \n \n \n \n
        HTTP Status CodeReasonResponse Model
        \n "}function t(A,z){return"\n "}function j(A,z){return"\n
        \n \n \n \n
        \n "}r+="\n
          \n
        • \n \n \n
        • \n
        \n";return r})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.param=b(function(f,q,o,j,s){this.compilerInfo=[4,">= 1.0.0"];o=this.merge(o,f.helpers);s=s||{};var p="",g,d="function",c=this.escapeExpression,n=this;function m(x,w){var u="",v;u+="\n ";v=o["if"].call(x,x.isFile,{hash:{},inverse:n.program(4,k,w),fn:n.program(2,l,w),data:w});if(v||v===0){u+=v}u+="\n ";return u}function l(x,w){var u="",v;u+='\n \n
        \n ';return u}function k(x,w){var u="",v;u+="\n ";v=o["if"].call(x,x.defaultValue,{hash:{},inverse:n.program(7,h,w),fn:n.program(5,i,w),data:w});if(v||v===0){u+=v}u+="\n ";return u}function i(x,w){var u="",v;u+="\n \n ";return u}function h(x,w){var u="",v;u+="\n \n
        \n
        \n ';return u}function e(x,w){var u="",v;u+="\n ";v=o["if"].call(x,x.defaultValue,{hash:{},inverse:n.program(12,r,w),fn:n.program(10,t,w),data:w});if(v||v===0){u+=v}u+="\n ";return u}function t(x,w){var u="",v;u+="\n \n ";return u}function r(x,w){var u="",v;u+="\n \n ";return u}p+="";if(g=o.name){g=g.call(q,{hash:{},data:s})}else{g=q.name;g=typeof g===d?g.apply(q):g}p+=c(g)+"\n\n\n ";g=o["if"].call(q,q.isBody,{hash:{},inverse:n.program(9,e,s),fn:n.program(1,m,s),data:s});if(g||g===0){p+=g}p+="\n\n\n";if(g=o.description){g=g.call(q,{hash:{},data:s})}else{g=q.description;g=typeof g===d?g.apply(q):g}if(g||g===0){p+=g}p+="\n";if(g=o.paramType){g=g.call(q,{hash:{},data:s})}else{g=q.paramType;g=typeof g===d?g.apply(q):g}if(g||g===0){p+=g}p+='\n\n \n\n';return p})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.param_list=b(function(h,t,r,m,y){this.compilerInfo=[4,">= 1.0.0"];r=this.merge(r,h.helpers);y=y||{};var s="",j,g,e,p=this,q=r.helperMissing,d="function",c=this.escapeExpression;function o(A,z){return" multiple='multiple'"}function n(A,z){return"\n "}function l(C,B){var z="",A;z+="\n ";A=r["if"].call(C,C.defaultValue,{hash:{},inverse:p.program(8,i,B),fn:p.program(6,k,B),data:B});if(A||A===0){z+=A}z+="\n ";return z}function k(A,z){return"\n "}function i(E,D){var z="",C,B,A;z+="\n ";A={hash:{},inverse:p.program(11,x,D),fn:p.program(9,f,D),data:D};B=((C=r.isArray||E.isArray),C?C.call(E,E,A):q.call(E,"isArray",E,A));if(B||B===0){z+=B}z+="\n ";return z}function f(A,z){return"\n "}function x(A,z){return"\n \n "}function w(C,B){var z="",A;z+="\n ";A=r["if"].call(C,C.isDefault,{hash:{},inverse:p.program(16,u,B),fn:p.program(14,v,B),data:B});if(A||A===0){z+=A}z+="\n ";return z}function v(C,B){var z="",A;z+='\n \n ";return z}function u(C,B){var z="",A;z+="\n \n ";return z}s+="";if(j=r.name){j=j.call(t,{hash:{},data:y})}else{j=t.name;j=typeof j===d?j.apply(t):j}s+=c(j)+"\n\n \n\n";if(g=r.description){g=g.call(t,{hash:{},data:y})}else{g=t.description;g=typeof g===d?g.apply(t):g}if(g||g===0){s+=g}s+="\n";if(g=r.paramType){g=g.call(t,{hash:{},data:y})}else{g=t.paramType;g=typeof g===d?g.apply(t):g}if(g||g===0){s+=g}s+='\n';return s})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.param_readonly=b(function(g,m,f,l,k){this.compilerInfo=[4,">= 1.0.0"];f=this.merge(f,g.helpers);k=k||{};var i="",d,h="function",j=this.escapeExpression,o=this;function e(t,s){var q="",r;q+="\n \n ";return q}function c(t,s){var q="",r;q+="\n ";r=f["if"].call(t,t.defaultValue,{hash:{},inverse:o.program(6,n,s),fn:o.program(4,p,s),data:s});if(r||r===0){q+=r}q+="\n ";return q}function p(t,s){var q="",r;q+="\n ";if(r=f.defaultValue){r=r.call(t,{hash:{},data:s})}else{r=t.defaultValue;r=typeof r===h?r.apply(t):r}q+=j(r)+"\n ";return q}function n(r,q){return"\n (empty)\n "}i+="";if(d=f.name){d=d.call(m,{hash:{},data:k})}else{d=m.name;d=typeof d===h?d.apply(m):d}i+=j(d)+"\n\n ";d=f["if"].call(m,m.isBody,{hash:{},inverse:o.program(3,c,k),fn:o.program(1,e,k),data:k});if(d||d===0){i+=d}i+="\n\n";if(d=f.description){d=d.call(m,{hash:{},data:k})}else{d=m.description;d=typeof d===h?d.apply(m):d}if(d||d===0){i+=d}i+="\n";if(d=f.paramType){d=d.call(m,{hash:{},data:k})}else{d=m.paramType;d=typeof d===h?d.apply(m):d}if(d||d===0){i+=d}i+='\n\n';return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.param_readonly_required=b(function(g,m,f,l,k){this.compilerInfo=[4,">= 1.0.0"];f=this.merge(f,g.helpers);k=k||{};var i="",d,h="function",j=this.escapeExpression,o=this;function e(t,s){var q="",r;q+="\n \n ";return q}function c(t,s){var q="",r;q+="\n ";r=f["if"].call(t,t.defaultValue,{hash:{},inverse:o.program(6,n,s),fn:o.program(4,p,s),data:s});if(r||r===0){q+=r}q+="\n ";return q}function p(t,s){var q="",r;q+="\n ";if(r=f.defaultValue){r=r.call(t,{hash:{},data:s})}else{r=t.defaultValue;r=typeof r===h?r.apply(t):r}q+=j(r)+"\n ";return q}function n(r,q){return"\n (empty)\n "}i+="";if(d=f.name){d=d.call(m,{hash:{},data:k})}else{d=m.name;d=typeof d===h?d.apply(m):d}i+=j(d)+"\n\n ";d=f["if"].call(m,m.isBody,{hash:{},inverse:o.program(3,c,k),fn:o.program(1,e,k),data:k});if(d||d===0){i+=d}i+="\n\n";if(d=f.description){d=d.call(m,{hash:{},data:k})}else{d=m.description;d=typeof d===h?d.apply(m):d}if(d||d===0){i+=d}i+="\n";if(d=f.paramType){d=d.call(m,{hash:{},data:k})}else{d=m.paramType;d=typeof d===h?d.apply(m):d}if(d||d===0){i+=d}i+='\n\n';return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.param_required=b(function(f,q,o,j,u){this.compilerInfo=[4,">= 1.0.0"];o=this.merge(o,f.helpers);u=u||{};var p="",g,d="function",c=this.escapeExpression,n=this;function m(z,y){var w="",x;w+="\n ";x=o["if"].call(z,z.isFile,{hash:{},inverse:n.program(4,k,y),fn:n.program(2,l,y),data:y});if(x||x===0){w+=x}w+="\n ";return w}function l(z,y){var w="",x;w+='\n \n ";return w}function k(z,y){var w="",x;w+="\n ";x=o["if"].call(z,z.defaultValue,{hash:{},inverse:n.program(7,h,y),fn:n.program(5,i,y),data:y});if(x||x===0){w+=x}w+="\n ";return w}function i(z,y){var w="",x;w+="\n \n ";return w}function h(z,y){var w="",x;w+="\n \n
        \n
        \n ';return w}function e(z,y){var w="",x;w+="\n ";x=o["if"].call(z,z.isFile,{hash:{},inverse:n.program(12,t,y),fn:n.program(10,v,y),data:y});if(x||x===0){w+=x}w+="\n ";return w}function v(z,y){var w="",x;w+="\n \n ";return w}function t(z,y){var w="",x;w+="\n ";x=o["if"].call(z,z.defaultValue,{hash:{},inverse:n.program(15,r,y),fn:n.program(13,s,y),data:y});if(x||x===0){w+=x}w+="\n ";return w}function s(z,y){var w="",x;w+="\n \n ";return w}function r(z,y){var w="",x;w+="\n \n ";return w}p+="";if(g=o.name){g=g.call(q,{hash:{},data:u})}else{g=q.name;g=typeof g===d?g.apply(q):g}p+=c(g)+"\n\n ";g=o["if"].call(q,q.isBody,{hash:{},inverse:n.program(9,e,u),fn:n.program(1,m,u),data:u});if(g||g===0){p+=g}p+="\n\n\n ";if(g=o.description){g=g.call(q,{hash:{},data:u})}else{g=q.description;g=typeof g===d?g.apply(q):g}if(g||g===0){p+=g}p+="\n\n";if(g=o.paramType){g=g.call(q,{hash:{},data:u})}else{g=q.paramType;g=typeof g===d?g.apply(q):g}if(g||g===0){p+=g}p+='\n\n';return p})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.parameter_content_type=b(function(g,l,f,k,j){this.compilerInfo=[4,">= 1.0.0"];f=this.merge(f,g.helpers);j=j||{};var i="",c,h="function",m=this;function e(r,q){var o="",p;o+="\n ";p=f.each.call(r,r.consumes,{hash:{},inverse:m.noop,fn:m.program(2,d,q),data:q});if(p||p===0){o+=p}o+="\n";return o}function d(r,q){var o="",p;o+='\n \n ";return o}function n(p,o){return'\n \n'}i+='\n\n";return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.resource=b(function(f,l,e,k,j){this.compilerInfo=[4,">= 1.0.0"];e=this.merge(e,f.helpers);j=j||{};var h="",c,o,g="function",i=this.escapeExpression,n=this,m=e.blockHelperMissing;function d(s,r){var p="",q;p+=" : ";if(q=e.description){q=q.call(s,{hash:{},data:r})}else{q=s.description;q=typeof q===g?q.apply(s):q}if(q||q===0){p+=q}return p}h+="
        \n

        \n ";if(c=e.name){c=c.call(l,{hash:{},data:j})}else{c=l.name;c=typeof c===g?c.apply(l):c}h+=i(c)+" ";o={hash:{},inverse:n.noop,fn:n.program(1,d,j),data:j};if(c=e.description){c=c.call(l,o)}else{c=l.description;c=typeof c===g?c.apply(l):c}if(!e.description){c=m.call(l,c,o)}if(c||c===0){h+=c}h+="\n

        \n \n
        \n\n";return h})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.response_content_type=b(function(g,l,f,k,j){this.compilerInfo=[4,">= 1.0.0"];f=this.merge(f,g.helpers);j=j||{};var i="",c,h="function",m=this;function e(r,q){var o="",p;o+="\n ";p=f.each.call(r,r.produces,{hash:{},inverse:m.noop,fn:m.program(2,d,q),data:q});if(p||p===0){o+=p}o+="\n";return o}function d(r,q){var o="",p;o+='\n \n ";return o}function n(p,o){return'\n \n'}i+='\n\n";return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.signature=b(function(e,k,d,j,i){this.compilerInfo=[4,">= 1.0.0"];d=this.merge(d,e.helpers);i=i||{};var g="",c,f="function",h=this.escapeExpression;g+='
        \n\n
        \n\n
        \n
        \n ';if(c=d.signature){c=c.call(k,{hash:{},data:i})}else{c=k.signature;c=typeof c===f?c.apply(k):c}if(c||c===0){g+=c}g+='\n
        \n\n
        \n
        ';if(c=d.sampleJSON){c=c.call(k,{hash:{},data:i})}else{c=k.sampleJSON;c=typeof c===f?c.apply(k):c}g+=h(c)+'
        \n \n
        \n
        \n\n';return g})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.status_code=b(function(e,k,d,j,i){this.compilerInfo=[4,">= 1.0.0"];d=this.merge(d,e.helpers);i=i||{};var g="",c,f="function",h=this.escapeExpression;g+="";if(c=d.code){c=c.call(k,{hash:{},data:i})}else{c=k.code;c=typeof c===f?c.apply(k):c}g+=h(c)+"\n";if(c=d.message){c=c.call(k,{hash:{},data:i})}else{c=k.message;c=typeof c===f?c.apply(k):c}if(c||c===0){g+=c}g+="\n";return g})})();(function(){var g,c,i,d,m,f,k,a,l,j,b,h={}.hasOwnProperty,e=function(q,o){for(var n in o){if(h.call(o,n)){q[n]=o[n]}}function p(){this.constructor=q}p.prototype=o.prototype;q.prototype=new p();q.__super__=o.prototype;return q};b=(function(o){e(n,o);function n(){n.__super__.constructor.apply(this,arguments)}n.prototype.dom_id="swagger_ui";n.prototype.options=null;n.prototype.api=null;n.prototype.headerView=null;n.prototype.mainView=null;n.prototype.initialize=function(p){var q=this;if(p==null){p={}}if(p.dom_id!=null){this.dom_id=p.dom_id;delete p.dom_id}if($("#"+this.dom_id)==null){$("body").append('
        ')}this.options=p;this.options.success=function(){return q.render()};this.options.progress=function(r){return q.showMessage(r)};this.options.failure=function(r){return q.onLoadFailure(r)};this.headerView=new c({el:$("#header")});return this.headerView.on("update-swagger-ui",function(r){return q.updateSwaggerUi(r)})};n.prototype.updateSwaggerUi=function(p){this.options.url=p.url;return this.load()};n.prototype.load=function(){var p,q;if((q=this.mainView)!=null){q.clear()}p=this.options.url;if(p.indexOf("http")!==0){p=this.buildUrl(window.location.href.toString(),p)}this.options.url=p;this.headerView.update(p);this.api=new SwaggerApi(this.options);this.api.build();return this.api};n.prototype.render=function(){var p=this;this.showMessage("Finished Loading Resource Information. Rendering Swagger UI...");this.headerView.updateInfo(this.api.info);this.mainView=new i({model:this.api,el:$("#"+this.dom_id)}).render();this.showMessage();switch(this.options.docExpansion){case"full":Docs.expandOperationsForResource("");break;case"list":Docs.collapseOperationsForResource("")}if(this.options.onComplete){this.options.onComplete(this.api,this)}return setTimeout(function(){return Docs.shebang()},400)};n.prototype.buildUrl=function(r,p){var q,s;log("base is "+r);if(p.indexOf("/")===0){s=r.split("/");r=s[0]+"//"+s[2];return r+p}else{q=r.length;if(r.indexOf("?")>-1){q=Math.min(q,r.indexOf("?"))}if(r.indexOf("#")>-1){q=Math.min(q,r.indexOf("#"))}r=r.substring(0,q);if(r.indexOf("/",r.length-1)!==-1){return r+p}return r+"/"+p}};n.prototype.showMessage=function(p){if(p==null){p=""}$("#message-bar").removeClass("message-fail");$("#message-bar").addClass("message-success");return $("#message-bar").html(p)};n.prototype.onLoadFailure=function(p){var q;if(p==null){p=""}$("#message-bar").removeClass("message-success");$("#message-bar").addClass("message-fail");q=$("#message-bar").html(p);if(this.options.onFailure!=null){this.options.onFailure(p)}return q};return n})(Backbone.Router);window.SwaggerUi=b;c=(function(o){e(n,o);function n(){n.__super__.constructor.apply(this,arguments)}n.prototype.events={"click #show-pet-store-icon":"showPetStore","click #show-wordnik-dev-icon":"showWordnikDev","click #explore":"showCustom","keyup #input_baseUrl":"showCustomOnKeyup","keyup #input_apiKey":"showCustomOnKeyup"};n.prototype.initialize=function(){};n.prototype.showPetStore=function(p){return this.trigger("update-swagger-ui",{url:"http://petstore.swagger.wordnik.com/api/api-docs"})};n.prototype.showWordnikDev=function(p){return this.trigger("update-swagger-ui",{url:"http://api.wordnik.com/v4/resources.json"})};n.prototype.showCustomOnKeyup=function(p){if(p.keyCode===13){return this.showCustom()}};n.prototype.showCustom=function(p){if(p!=null){p.preventDefault()}return this.trigger("update-swagger-ui",{url:$("#input_baseUrl").val(),apiKey:$("#input_apiKey").val()})};n.prototype.update=function(q,r,p){if(p==null){p=false}$("#input_baseUrl").val(q);if(p){return this.trigger("update-swagger-ui",{url:q})}};n.prototype.updateInfo=function(p){if(p.title!=null){$("#logo").text(p.title)}if(p.description!=null){$("#logo").attr("title",p.description)}if(p.termsOfServiceUrl!=null){return $("#logo").attr("href",p.termsOfServiceUrl)}};return n})(Backbone.View);i=(function(n){e(o,n);function o(){o.__super__.constructor.apply(this,arguments)}o.prototype.initialize=function(){};o.prototype.render=function(){var q,v,t,u,s,p,r;$(this.el).html(Handlebars.templates.main(this.model));u={};q=0;r=this.model.apisArray;for(s=0,p=r.length;sq){B=q-r}if(Bp){w=p-t}if(w0){r[u.name]=u.value}if(u.type==="file"){C=true}}y=t.find("textarea");for(z=0,s=y.length;z0){r.body=u.value}}w=t.find("select");for(x=0,q=w.length;x0){r[u.name]=v}}p.responseContentType=$("div select[name=responseContentType]",$(this.el)).val();p.requestContentType=$("div select[name=parameterContentType]",$(this.el)).val();$(".response_throbber",$(this.el)).show();if(C){return this.handleFileUpload(r,t)}else{return this.model["do"](r,p,this.showCompleteStatus,this.showErrorStatus,this)}}};n.prototype.success=function(p,q){return q.showCompleteStatus(p)};n.prototype.handleFileUpload=function(H,u){var C,t,p,D,B,z,F,w,s,r,q,G,K,J,I,A,y,x,v,E=this;A=u.serializeArray();for(w=0,G=A.length;w0){H[D.name]=D.value}}C=new FormData();F=0;y=this.model.parameters;for(s=0,K=y.length;s"+this.invocationUrl+"
        ");B={type:this.model.method,url:this.invocationUrl,headers:p,data:C,dataType:"json",contentType:false,processData:false,error:function(M,N,L){return E.showErrorStatus(E.wrap(M),E)},success:function(L){return E.showResponse(L,E)},complete:function(L){return E.showCompleteStatus(E.wrap(L),E)}};if(window.authorizations){window.authorizations.apply(B)}if(F===0){B.data.append("fake","true")}jQuery.ajax(B);return false};n.prototype.wrap=function(t){var r,u,w,q,v,s,p;w={};u=t.getAllResponseHeaders().split("\r");for(s=0,p=u.length;s0){return r.join(",")}else{return null}}};n.prototype.hideResponse=function(p){if(p!=null){p.preventDefault()}$(".response",$(this.el)).slideUp();return $(".response_hider",$(this.el)).fadeOut()};n.prototype.showResponse=function(p){var q;q=JSON.stringify(p,null,"\t").replace(/\n/g,"
        ");return $(".response_body",$(this.el)).html(escape(q))};n.prototype.showErrorStatus=function(q,p){return p.showStatus(q)};n.prototype.showCompleteStatus=function(q,p){return p.showStatus(q)};n.prototype.formatXml=function(w){var s,v,q,x,C,y,r,p,A,B,u,t,z;p=/(>)(<)(\/*)/g;B=/[ ]*(.*)[ ]+\n/g;s=/(<.+>)(.+\n)/g;w=w.replace(p,"$1\n$2$3").replace(B,"$1\n").replace(s,"$1\n$2");r=0;v="";C=w.split("\n");q=0;x="other";A={"single->single":0,"single->closing":-1,"single->opening":0,"single->other":0,"closing->single":0,"closing->closing":-1,"closing->opening":0,"closing->other":0,"opening->single":1,"opening->closing":0,"opening->opening":1,"opening->other":1,"other->single":0,"other->closing":-1,"other->opening":0,"other->other":0};u=function(I){var E,D,G,K,H,F,J;F={single:Boolean(I.match(/<.+\/>/)),closing:Boolean(I.match(/<\/.+>/)),opening:Boolean(I.match(/<[^!?].*>/))};H=((function(){var L;L=[];for(G in F){J=F[G];if(J){L.push(G)}}return L})())[0];H=H===void 0?"other":H;E=x+"->"+H;x=H;K="";q+=A[E];K=((function(){var M,N,L;L=[];for(D=M=0,N=q;0<=N?MN;D=0<=N?++M:--M){L.push(" ")}return L})()).join("");if(E==="opening->closing"){return v=v.substr(0,v.length-1)+I+"\n"}else{return v+=K+I+"\n"}};for(t=0,z=C.length;t").text("no content");u=$('
        ').append(t)}else{if(w==="application/json"||/\+json$/.test(w)){t=$("").text(JSON.stringify(JSON.parse(s),null,"  "));u=$('
        ').append(t)}else{if(w==="application/xml"||/\+xml$/.test(w)){t=$("").text(this.formatXml(s));u=$('
        ').append(t)}else{if(w==="text/html"){t=$("").html(s);u=$('
        ').append(t)}else{if(/^image\//.test(w)){u=$("").attr("src",q)}else{t=$("").text(s);u=$('
        ').append(t)}}}}}r=u;$(".request_url",$(this.el)).html("
        "+q+"
        ");$(".response_code",$(this.el)).html("
        "+p.status+"
        ");$(".response_body",$(this.el)).html(r);$(".response_headers",$(this.el)).html("
        "+JSON.stringify(p.headers,null,"  ").replace(/\n/g,"
        ")+"
        ");$(".response",$(this.el)).slideDown();$(".response_hider",$(this.el)).show();$(".response_throbber",$(this.el)).hide();return hljs.highlightBlock($(".response_body",$(this.el))[0])};n.prototype.toggleOperationContent=function(){var p;p=$("#"+Docs.escapeResourceName(this.model.parentId)+"_"+this.model.nickname+"_content");if(p.is(":visible")){return Docs.collapseOperation(p)}else{return Docs.expandOperation(p)}};return n})(Backbone.View);j=(function(o){e(n,o);function n(){n.__super__.constructor.apply(this,arguments)}n.prototype.initialize=function(){};n.prototype.render=function(){var q,p,r;r=this.template();$(this.el).html(r(this.model));if(swaggerUi.api.models.hasOwnProperty(this.model.responseModel)){q={sampleJSON:JSON.stringify(swaggerUi.api.models[this.model.responseModel].createJSONSample(),null,2),isParam:false,signature:swaggerUi.api.models[this.model.responseModel].getMockSignature()};p=new l({model:q,tagName:"div"});$(".model-signature",this.$el).append(p.render().el)}else{$(".model-signature",this.$el).html("")}return this};n.prototype.template=function(){return Handlebars.templates.status_code};return n})(Backbone.View);f=(function(o){e(n,o);function n(){n.__super__.constructor.apply(this,arguments)}n.prototype.initialize=function(){return Handlebars.registerHelper("isArray",function(q,p){if(q.type.toLowerCase()==="array"||q.allowMultiple){return p.fn(this)}else{return p.inverse(this)}})};n.prototype.render=function(){var v,p,r,u,q,w,t,s;s=this.model.type||this.model.dataType;if(this.model.paramType==="body"){this.model.isBody=true}if(s.toLowerCase()==="file"){this.model.isFile=true}t=this.template();$(this.el).html(t(this.model));q={sampleJSON:this.model.sampleJSON,isParam:true,signature:this.model.signature};if(this.model.sampleJSON){w=new l({model:q,tagName:"div"});$(".model-signature",$(this.el)).append(w.render().el)}else{$(".model-signature",$(this.el)).html(this.model.signature)}p=false;if(this.model.isBody){p=true}v={isParam:p};v.consumes=this.model.consumes;if(p){r=new m({model:v});$(".parameter-content-type",$(this.el)).append(r.render().el)}else{u=new a({model:v});$(".response-content-type",$(this.el)).append(u.render().el)}return this};n.prototype.template=function(){if(this.model.isList){return Handlebars.templates.param_list}else{if(this.options.readOnly){if(this.model.required){return Handlebars.templates.param_readonly_required}else{return Handlebars.templates.param_readonly}}else{if(this.model.required){return Handlebars.templates.param_required}else{return Handlebars.templates.param}}}};return n})(Backbone.View);l=(function(o){e(n,o);function n(){n.__super__.constructor.apply(this,arguments)}n.prototype.events={"click a.description-link":"switchToDescription","click a.snippet-link":"switchToSnippet","mousedown .snippet":"snippetToTextArea"};n.prototype.initialize=function(){};n.prototype.render=function(){var p;p=this.template();$(this.el).html(p(this.model));this.switchToDescription();this.isParam=this.model.isParam;if(this.isParam){$(".notice",$(this.el)).text("Click to set as parameter value")}return this};n.prototype.template=function(){return Handlebars.templates.signature};n.prototype.switchToDescription=function(p){if(p!=null){p.preventDefault()}$(".snippet",$(this.el)).hide();$(".description",$(this.el)).show();$(".description-link",$(this.el)).addClass("selected");return $(".snippet-link",$(this.el)).removeClass("selected")};n.prototype.switchToSnippet=function(p){if(p!=null){p.preventDefault()}$(".description",$(this.el)).hide();$(".snippet",$(this.el)).show();$(".snippet-link",$(this.el)).addClass("selected");return $(".description-link",$(this.el)).removeClass("selected")};n.prototype.snippetToTextArea=function(p){var q;if(this.isParam){if(p!=null){p.preventDefault()}q=$("textarea",$(this.el.parentNode.parentNode.parentNode));if($.trim(q.val())===""){return q.val(this.model.sampleJSON)}}};return n})(Backbone.View);g=(function(n){e(o,n);function o(){o.__super__.constructor.apply(this,arguments)}o.prototype.initialize=function(){};o.prototype.render=function(){var p;p=this.template();$(this.el).html(p(this.model));$("label[for=contentType]",$(this.el)).text("Response Content Type");return this};o.prototype.template=function(){return Handlebars.templates.content_type};return o})(Backbone.View);a=(function(n){e(o,n);function o(){o.__super__.constructor.apply(this,arguments)}o.prototype.initialize=function(){};o.prototype.render=function(){var p;p=this.template();$(this.el).html(p(this.model));$("label[for=responseContentType]",$(this.el)).text("Response Content Type");return this};o.prototype.template=function(){return Handlebars.templates.response_content_type};return o})(Backbone.View);m=(function(o){e(n,o);function n(){n.__super__.constructor.apply(this,arguments)}n.prototype.initialize=function(){};n.prototype.render=function(){var p;p=this.template();$(this.el).html(p(this.model));$("label[for=parameterContentType]",$(this.el)).text("Parameter content type:");return this};n.prototype.template=function(){return Handlebars.templates.parameter_content_type};return n})(Backbone.View)}).call(this); \ No newline at end of file +$(function(){$.fn.vAlign=function(){return this.each(function(c){var a=$(this).height();var d=$(this).parent().height();var b=(d-a)/2;$(this).css("margin-top",b)})};$.fn.stretchFormtasticInputWidthToParent=function(){return this.each(function(b){var d=$(this).closest("form").innerWidth();var c=parseInt($(this).closest("form").css("padding-left"),10)+parseInt($(this).closest("form").css("padding-right"),10);var a=parseInt($(this).css("padding-left"),10)+parseInt($(this).css("padding-right"),10);$(this).css("width",d-c-a)})};$("form.formtastic li.string input, form.formtastic textarea").stretchFormtasticInputWidthToParent();$("ul.downplayed li div.content p").vAlign();$("form.sandbox").submit(function(){var a=true;$(this).find("input.required").each(function(){$(this).removeClass("error");if($(this).val()==""){$(this).addClass("error");$(this).wiggle();a=false}});return a})});function clippyCopiedCallback(b){$("#api_key_copied").fadeIn().delay(1000).fadeOut()}log=function(){log.history=log.history||[];log.history.push(arguments);if(this.console){console.log(Array.prototype.slice.call(arguments)[0])}};if(Function.prototype.bind&&console&&typeof console.log=="object"){["log","info","warn","error","assert","dir","clear","profile","profileEnd"].forEach(function(a){console[a]=this.bind(console[a],console)},Function.prototype.call)}var Docs={shebang:function(){var b=$.param.fragment().split("/");b.shift();switch(b.length){case 1:log("shebang resource:"+b[0]);var d="resource_"+b[0];Docs.expandEndpointListForResource(b[0]);$("#"+d).slideto({highlight:false});break;case 2:log("shebang endpoint: "+b.join("_"));Docs.expandEndpointListForResource(b[0]);$("#"+d).slideto({highlight:false});var c=b.join("_");var a=c+"_content";log("li_dom_id "+c);log("li_content_dom_id "+a);Docs.expandOperation($("#"+a));$("#"+c).slideto({highlight:false});break}},toggleEndpointListForResource:function(b){var a=$("li#resource_"+Docs.escapeResourceName(b)+" ul.endpoints");if(a.is(":visible")){Docs.collapseEndpointListForResource(b)}else{Docs.expandEndpointListForResource(b)}},expandEndpointListForResource:function(b){var b=Docs.escapeResourceName(b);if(b==""){$(".resource ul.endpoints").slideDown();return}$("li#resource_"+b).addClass("active");var a=$("li#resource_"+b+" ul.endpoints");a.slideDown()},collapseEndpointListForResource:function(b){var b=Docs.escapeResourceName(b);$("li#resource_"+b).removeClass("active");var a=$("li#resource_"+b+" ul.endpoints");a.slideUp()},expandOperationsForResource:function(a){Docs.expandEndpointListForResource(a);if(a==""){$(".resource ul.endpoints li.operation div.content").slideDown();return}$("li#resource_"+Docs.escapeResourceName(a)+" li.operation div.content").each(function(){Docs.expandOperation($(this))})},collapseOperationsForResource:function(a){Docs.expandEndpointListForResource(a);$("li#resource_"+Docs.escapeResourceName(a)+" li.operation div.content").each(function(){Docs.collapseOperation($(this))})},escapeResourceName:function(a){return a.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]\^`{|}~]/g,"\\$&")},expandOperation:function(a){a.slideDown()},collapseOperation:function(a){a.slideUp()}};(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.content_type=b(function(g,l,f,k,j){this.compilerInfo=[4,">= 1.0.0"];f=this.merge(f,g.helpers);j=j||{};var i="",c,h="function",m=this;function e(r,q){var o="",p;o+="\n ";p=f.each.call(r,r.produces,{hash:{},inverse:m.noop,fn:m.program(2,d,q),data:q});if(p||p===0){o+=p}o+="\n";return o}function d(r,q){var o="",p;o+='\n \n ";return o}function n(p,o){return'\n \n'}i+='\n\n";return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.main=b(function(g,m,f,l,k){this.compilerInfo=[4,">= 1.0.0"];f=this.merge(f,g.helpers);k=k||{};var i="",c,h="function",j=this.escapeExpression,p=this;function e(v,u){var r="",t,s;r+='\n
        '+j(((t=((t=v.info),t==null||t===false?t:t.title)),typeof t===h?t.apply(v):t))+'
        \n
        ';s=((t=((t=v.info),t==null||t===false?t:t.description)),typeof t===h?t.apply(v):t);if(s||s===0){r+=s}r+="
        \n ";s=f["if"].call(v,((t=v.info),t==null||t===false?t:t.termsOfServiceUrl),{hash:{},inverse:p.noop,fn:p.program(2,d,u),data:u});if(s||s===0){r+=s}r+="\n ";s=f["if"].call(v,((t=v.info),t==null||t===false?t:t.contact),{hash:{},inverse:p.noop,fn:p.program(4,q,u),data:u});if(s||s===0){r+=s}r+="\n ";s=f["if"].call(v,((t=v.info),t==null||t===false?t:t.license),{hash:{},inverse:p.noop,fn:p.program(6,o,u),data:u});if(s||s===0){r+=s}r+="\n ";return r}function d(u,t){var r="",s;r+='';return r}function q(u,t){var r="",s;r+="';return r}function o(u,t){var r="",s;r+="";return r}function n(u,t){var r="",s;r+='\n , api version: ';if(s=f.apiVersion){s=s.call(u,{hash:{},data:t})}else{s=u.apiVersion;s=typeof s===h?s.apply(u):s}r+=j(s)+"\n ";return r}i+="
        \n ";c=f["if"].call(m,m.info,{hash:{},inverse:p.noop,fn:p.program(1,e,k),data:k});if(c||c===0){i+=c}i+="\n
        \n
        \n
          \n
        \n\n
        \n
        \n
        \n

        [ base url: ";if(c=f.basePath){c=c.call(m,{hash:{},data:k})}else{c=m.basePath;c=typeof c===h?c.apply(m):c}i+=j(c)+"\n ";c=f["if"].call(m,m.apiVersion,{hash:{},inverse:p.noop,fn:p.program(8,n,k),data:k});if(c||c===0){i+=c}i+="]

        \n
        \n
        \n";return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.operation=b(function(g,s,q,m,y){this.compilerInfo=[4,">= 1.0.0"];q=this.merge(q,g.helpers);y=y||{};var r="",i,f,e="function",d=this.escapeExpression,p=this,c=q.blockHelperMissing;function o(C,B){var z="",A;z+="\n

        Implementation Notes

        \n

        ";if(A=q.notes){A=A.call(C,{hash:{},data:B})}else{A=C.notes;A=typeof A===e?A.apply(C):A}if(A||A===0){z+=A}z+="

        \n ";return z}function n(A,z){return'\n
        \n '}function l(C,B){var z="",A;z+='\n \n ";return z}function k(D,C){var z="",B,A;z+="\n
        "+d(((B=D.scope),typeof B===e?B.apply(D):B))+"
        \n ";return z}function h(A,z){return"
        "}function x(A,z){return'\n
        \n \n
        \n '}function w(A,z){return'\n

        Response Class

        \n

        \n
        \n
        \n '}function v(A,z){return'\n

        Parameters

        \n \n \n \n \n \n \n \n \n \n \n \n\n \n
        ParameterValueDescriptionParameter TypeData Type
        \n '}function u(A,z){return"\n
        \n

        Response Messages

        \n \n \n \n \n \n \n \n \n \n \n \n
        HTTP Status CodeReasonResponse Model
        \n "}function t(A,z){return"\n "}function j(A,z){return"\n
        \n \n \n \n
        \n "}r+="\n
          \n
        • \n \n \n
        • \n
        \n";return r})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.param=b(function(f,q,o,j,t){this.compilerInfo=[4,">= 1.0.0"];o=this.merge(o,f.helpers);t=t||{};var p="",g,d="function",c=this.escapeExpression,n=this;function m(y,x){var v="",w;v+="\n ";w=o["if"].call(y,y.isFile,{hash:{},inverse:n.program(4,k,x),fn:n.program(2,l,x),data:x});if(w||w===0){v+=w}v+="\n ";return v}function l(y,x){var v="",w;v+='\n \n
        \n ';return v}function k(y,x){var v="",w;v+="\n ";w=o["if"].call(y,y.defaultValue,{hash:{},inverse:n.program(7,h,x),fn:n.program(5,i,x),data:x});if(w||w===0){v+=w}v+="\n ";return v}function i(y,x){var v="",w;v+="\n \n ";return v}function h(y,x){var v="",w;v+="\n \n
        \n
        \n ';return v}function e(y,x){var v="",w;v+="\n ";w=o["if"].call(y,y.isFile,{hash:{},inverse:n.program(10,u,x),fn:n.program(2,l,x),data:x});if(w||w===0){v+=w}v+="\n ";return v}function u(y,x){var v="",w;v+="\n ";w=o["if"].call(y,y.defaultValue,{hash:{},inverse:n.program(13,r,x),fn:n.program(11,s,x),data:x});if(w||w===0){v+=w}v+="\n ";return v}function s(y,x){var v="",w;v+="\n \n ";return v}function r(y,x){var v="",w;v+="\n \n ";return v}p+="";if(g=o.name){g=g.call(q,{hash:{},data:t})}else{g=q.name;g=typeof g===d?g.apply(q):g}p+=c(g)+"\n\n\n ";g=o["if"].call(q,q.isBody,{hash:{},inverse:n.program(9,e,t),fn:n.program(1,m,t),data:t});if(g||g===0){p+=g}p+="\n\n\n";if(g=o.description){g=g.call(q,{hash:{},data:t})}else{g=q.description;g=typeof g===d?g.apply(q):g}if(g||g===0){p+=g}p+="\n";if(g=o.paramType){g=g.call(q,{hash:{},data:t})}else{g=q.paramType;g=typeof g===d?g.apply(q):g}if(g||g===0){p+=g}p+='\n\n \n\n';return p})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.param_list=b(function(h,t,r,m,y){this.compilerInfo=[4,">= 1.0.0"];r=this.merge(r,h.helpers);y=y||{};var s="",j,g,e,p=this,q=r.helperMissing,d="function",c=this.escapeExpression;function o(A,z){return" multiple='multiple'"}function n(A,z){return"\n "}function l(C,B){var z="",A;z+="\n ";A=r["if"].call(C,C.defaultValue,{hash:{},inverse:p.program(8,i,B),fn:p.program(6,k,B),data:B});if(A||A===0){z+=A}z+="\n ";return z}function k(A,z){return"\n "}function i(E,D){var z="",C,B,A;z+="\n ";A={hash:{},inverse:p.program(11,x,D),fn:p.program(9,f,D),data:D};B=((C=r.isArray||E.isArray),C?C.call(E,E,A):q.call(E,"isArray",E,A));if(B||B===0){z+=B}z+="\n ";return z}function f(A,z){return"\n "}function x(A,z){return"\n \n "}function w(C,B){var z="",A;z+="\n ";A=r["if"].call(C,C.isDefault,{hash:{},inverse:p.program(16,u,B),fn:p.program(14,v,B),data:B});if(A||A===0){z+=A}z+="\n ";return z}function v(C,B){var z="",A;z+='\n \n ";return z}function u(C,B){var z="",A;z+="\n \n ";return z}s+="";if(j=r.name){j=j.call(t,{hash:{},data:y})}else{j=t.name;j=typeof j===d?j.apply(t):j}s+=c(j)+"\n\n \n\n";if(g=r.description){g=g.call(t,{hash:{},data:y})}else{g=t.description;g=typeof g===d?g.apply(t):g}if(g||g===0){s+=g}s+="\n";if(g=r.paramType){g=g.call(t,{hash:{},data:y})}else{g=t.paramType;g=typeof g===d?g.apply(t):g}if(g||g===0){s+=g}s+='\n';return s})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.param_readonly=b(function(g,m,f,l,k){this.compilerInfo=[4,">= 1.0.0"];f=this.merge(f,g.helpers);k=k||{};var i="",d,h="function",j=this.escapeExpression,o=this;function e(t,s){var q="",r;q+="\n \n ";return q}function c(t,s){var q="",r;q+="\n ";r=f["if"].call(t,t.defaultValue,{hash:{},inverse:o.program(6,n,s),fn:o.program(4,p,s),data:s});if(r||r===0){q+=r}q+="\n ";return q}function p(t,s){var q="",r;q+="\n ";if(r=f.defaultValue){r=r.call(t,{hash:{},data:s})}else{r=t.defaultValue;r=typeof r===h?r.apply(t):r}q+=j(r)+"\n ";return q}function n(r,q){return"\n (empty)\n "}i+="";if(d=f.name){d=d.call(m,{hash:{},data:k})}else{d=m.name;d=typeof d===h?d.apply(m):d}i+=j(d)+"\n\n ";d=f["if"].call(m,m.isBody,{hash:{},inverse:o.program(3,c,k),fn:o.program(1,e,k),data:k});if(d||d===0){i+=d}i+="\n\n";if(d=f.description){d=d.call(m,{hash:{},data:k})}else{d=m.description;d=typeof d===h?d.apply(m):d}if(d||d===0){i+=d}i+="\n";if(d=f.paramType){d=d.call(m,{hash:{},data:k})}else{d=m.paramType;d=typeof d===h?d.apply(m):d}if(d||d===0){i+=d}i+='\n\n';return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.param_readonly_required=b(function(g,m,f,l,k){this.compilerInfo=[4,">= 1.0.0"];f=this.merge(f,g.helpers);k=k||{};var i="",d,h="function",j=this.escapeExpression,o=this;function e(t,s){var q="",r;q+="\n \n ";return q}function c(t,s){var q="",r;q+="\n ";r=f["if"].call(t,t.defaultValue,{hash:{},inverse:o.program(6,n,s),fn:o.program(4,p,s),data:s});if(r||r===0){q+=r}q+="\n ";return q}function p(t,s){var q="",r;q+="\n ";if(r=f.defaultValue){r=r.call(t,{hash:{},data:s})}else{r=t.defaultValue;r=typeof r===h?r.apply(t):r}q+=j(r)+"\n ";return q}function n(r,q){return"\n (empty)\n "}i+="";if(d=f.name){d=d.call(m,{hash:{},data:k})}else{d=m.name;d=typeof d===h?d.apply(m):d}i+=j(d)+"\n\n ";d=f["if"].call(m,m.isBody,{hash:{},inverse:o.program(3,c,k),fn:o.program(1,e,k),data:k});if(d||d===0){i+=d}i+="\n\n";if(d=f.description){d=d.call(m,{hash:{},data:k})}else{d=m.description;d=typeof d===h?d.apply(m):d}if(d||d===0){i+=d}i+="\n";if(d=f.paramType){d=d.call(m,{hash:{},data:k})}else{d=m.paramType;d=typeof d===h?d.apply(m):d}if(d||d===0){i+=d}i+='\n\n';return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.param_required=b(function(f,q,o,j,u){this.compilerInfo=[4,">= 1.0.0"];o=this.merge(o,f.helpers);u=u||{};var p="",g,d="function",c=this.escapeExpression,n=this;function m(z,y){var w="",x;w+="\n ";x=o["if"].call(z,z.isFile,{hash:{},inverse:n.program(4,k,y),fn:n.program(2,l,y),data:y});if(x||x===0){w+=x}w+="\n ";return w}function l(z,y){var w="",x;w+='\n \n ";return w}function k(z,y){var w="",x;w+="\n ";x=o["if"].call(z,z.defaultValue,{hash:{},inverse:n.program(7,h,y),fn:n.program(5,i,y),data:y});if(x||x===0){w+=x}w+="\n ";return w}function i(z,y){var w="",x;w+="\n \n ";return w}function h(z,y){var w="",x;w+="\n \n
        \n
        \n ';return w}function e(z,y){var w="",x;w+="\n ";x=o["if"].call(z,z.isFile,{hash:{},inverse:n.program(12,t,y),fn:n.program(10,v,y),data:y});if(x||x===0){w+=x}w+="\n ";return w}function v(z,y){var w="",x;w+="\n \n ";return w}function t(z,y){var w="",x;w+="\n ";x=o["if"].call(z,z.defaultValue,{hash:{},inverse:n.program(15,r,y),fn:n.program(13,s,y),data:y});if(x||x===0){w+=x}w+="\n ";return w}function s(z,y){var w="",x;w+="\n \n ";return w}function r(z,y){var w="",x;w+="\n \n ";return w}p+="";if(g=o.name){g=g.call(q,{hash:{},data:u})}else{g=q.name;g=typeof g===d?g.apply(q):g}p+=c(g)+"\n\n ";g=o["if"].call(q,q.isBody,{hash:{},inverse:n.program(9,e,u),fn:n.program(1,m,u),data:u});if(g||g===0){p+=g}p+="\n\n\n ";if(g=o.description){g=g.call(q,{hash:{},data:u})}else{g=q.description;g=typeof g===d?g.apply(q):g}if(g||g===0){p+=g}p+="\n\n";if(g=o.paramType){g=g.call(q,{hash:{},data:u})}else{g=q.paramType;g=typeof g===d?g.apply(q):g}if(g||g===0){p+=g}p+='\n\n';return p})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.parameter_content_type=b(function(g,l,f,k,j){this.compilerInfo=[4,">= 1.0.0"];f=this.merge(f,g.helpers);j=j||{};var i="",c,h="function",m=this;function e(r,q){var o="",p;o+="\n ";p=f.each.call(r,r.consumes,{hash:{},inverse:m.noop,fn:m.program(2,d,q),data:q});if(p||p===0){o+=p}o+="\n";return o}function d(r,q){var o="",p;o+='\n \n ";return o}function n(p,o){return'\n \n'}i+='\n\n";return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.resource=b(function(f,l,e,k,j){this.compilerInfo=[4,">= 1.0.0"];e=this.merge(e,f.helpers);j=j||{};var h="",c,o,g="function",i=this.escapeExpression,n=this,m=e.blockHelperMissing;function d(q,p){return" : "}h+="
        \n

        \n ';if(c=e.name){c=c.call(l,{hash:{},data:j})}else{c=l.name;c=typeof c===g?c.apply(l):c}h+=i(c)+" ";o={hash:{},inverse:n.noop,fn:n.program(1,d,j),data:j};if(c=e.description){c=c.call(l,o)}else{c=l.description;c=typeof c===g?c.apply(l):c}if(!e.description){c=m.call(l,c,o)}if(c||c===0){h+=c}if(c=e.description){c=c.call(l,{hash:{},data:j})}else{c=l.description;c=typeof c===g?c.apply(l):c}if(c||c===0){h+=c}h+="\n

        \n \n
        \n\n";return h})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.response_content_type=b(function(g,l,f,k,j){this.compilerInfo=[4,">= 1.0.0"];f=this.merge(f,g.helpers);j=j||{};var i="",c,h="function",m=this;function e(r,q){var o="",p;o+="\n ";p=f.each.call(r,r.produces,{hash:{},inverse:m.noop,fn:m.program(2,d,q),data:q});if(p||p===0){o+=p}o+="\n";return o}function d(r,q){var o="",p;o+='\n \n ";return o}function n(p,o){return'\n \n'}i+='\n\n";return i})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.signature=b(function(e,k,d,j,i){this.compilerInfo=[4,">= 1.0.0"];d=this.merge(d,e.helpers);i=i||{};var g="",c,f="function",h=this.escapeExpression;g+='
        \n\n
        \n\n
        \n
        \n ';if(c=d.signature){c=c.call(k,{hash:{},data:i})}else{c=k.signature;c=typeof c===f?c.apply(k):c}if(c||c===0){g+=c}g+='\n
        \n\n
        \n
        ';if(c=d.sampleJSON){c=c.call(k,{hash:{},data:i})}else{c=k.sampleJSON;c=typeof c===f?c.apply(k):c}g+=h(c)+'
        \n \n
        \n
        \n\n';return g})})();(function(){var b=Handlebars.template,a=Handlebars.templates=Handlebars.templates||{};a.status_code=b(function(e,k,d,j,i){this.compilerInfo=[4,">= 1.0.0"];d=this.merge(d,e.helpers);i=i||{};var g="",c,f="function",h=this.escapeExpression;g+="";if(c=d.code){c=c.call(k,{hash:{},data:i})}else{c=k.code;c=typeof c===f?c.apply(k):c}g+=h(c)+"\n";if(c=d.message){c=c.call(k,{hash:{},data:i})}else{c=k.message;c=typeof c===f?c.apply(k):c}if(c||c===0){g+=c}g+="\n";return g})})();(function(){var j,r,u,o,l,k,n,m,i,p,s,q,h,c,g,f,e,d,b,a,x,w,t={}.hasOwnProperty,v=function(B,z){for(var y in z){if(t.call(z,y)){B[y]=z[y]}}function A(){this.constructor=B}A.prototype=z.prototype;B.prototype=new A();B.__super__=z.prototype;return B};s=(function(z){v(y,z);function y(){q=y.__super__.constructor.apply(this,arguments);return q}y.prototype.dom_id="swagger_ui";y.prototype.options=null;y.prototype.api=null;y.prototype.headerView=null;y.prototype.mainView=null;y.prototype.initialize=function(A){var B=this;if(A==null){A={}}if(A.dom_id!=null){this.dom_id=A.dom_id;delete A.dom_id}if($("#"+this.dom_id)==null){$("body").append('
        ')}this.options=A;this.options.success=function(){return B.render()};this.options.progress=function(C){return B.showMessage(C)};this.options.failure=function(C){return B.onLoadFailure(C)};this.headerView=new r({el:$("#header")});return this.headerView.on("update-swagger-ui",function(C){return B.updateSwaggerUi(C)})};y.prototype.updateSwaggerUi=function(A){this.options.url=A.url;return this.load()};y.prototype.load=function(){var B,A;if((A=this.mainView)!=null){A.clear()}B=this.options.url;if(B.indexOf("http")!==0){B=this.buildUrl(window.location.href.toString(),B)}this.options.url=B;this.headerView.update(B);this.api=new SwaggerApi(this.options);this.api.build();return this.api};y.prototype.render=function(){var A=this;this.showMessage("Finished Loading Resource Information. Rendering Swagger UI...");this.mainView=new u({model:this.api,el:$("#"+this.dom_id),swaggerOptions:this.options}).render();this.showMessage();switch(this.options.docExpansion){case"full":Docs.expandOperationsForResource("");break;case"list":Docs.collapseOperationsForResource("")}if(this.options.onComplete){this.options.onComplete(this.api,this)}return setTimeout(function(){return Docs.shebang()},400)};y.prototype.buildUrl=function(C,A){var B,D;log("base is "+C);if(A.indexOf("/")===0){D=C.split("/");C=D[0]+"//"+D[2];return C+A}else{B=C.length;if(C.indexOf("?")>-1){B=Math.min(B,C.indexOf("?"))}if(C.indexOf("#")>-1){B=Math.min(B,C.indexOf("#"))}C=C.substring(0,B);if(C.indexOf("/",C.length-1)!==-1){return C+A}return C+"/"+A}};y.prototype.showMessage=function(A){if(A==null){A=""}$("#message-bar").removeClass("message-fail");$("#message-bar").addClass("message-success");return $("#message-bar").html(A)};y.prototype.onLoadFailure=function(A){var B;if(A==null){A=""}$("#message-bar").removeClass("message-success");$("#message-bar").addClass("message-fail");B=$("#message-bar").html(A);if(this.options.onFailure!=null){this.options.onFailure(A)}return B};return y})(Backbone.Router);window.SwaggerUi=s;r=(function(z){v(y,z);function y(){h=y.__super__.constructor.apply(this,arguments);return h}y.prototype.events={"click #show-pet-store-icon":"showPetStore","click #show-wordnik-dev-icon":"showWordnikDev","click #explore":"showCustom","keyup #input_baseUrl":"showCustomOnKeyup","keyup #input_apiKey":"showCustomOnKeyup"};y.prototype.initialize=function(){};y.prototype.showPetStore=function(A){return this.trigger("update-swagger-ui",{url:"http://petstore.swagger.wordnik.com/api/api-docs"})};y.prototype.showWordnikDev=function(A){return this.trigger("update-swagger-ui",{url:"http://api.wordnik.com/v4/resources.json"})};y.prototype.showCustomOnKeyup=function(A){if(A.keyCode===13){return this.showCustom()}};y.prototype.showCustom=function(A){if(A!=null){A.preventDefault()}return this.trigger("update-swagger-ui",{url:$("#input_baseUrl").val(),apiKey:$("#input_apiKey").val()})};y.prototype.update=function(B,C,A){if(A==null){A=false}$("#input_baseUrl").val(B);if(A){return this.trigger("update-swagger-ui",{url:B})}};return y})(Backbone.View);u=(function(y){var z;v(A,y);function A(){g=A.__super__.constructor.apply(this,arguments);return g}z={alpha:function(C,B){return C.path.localeCompare(B.path)},method:function(C,B){return C.method.localeCompare(B.method)}};A.prototype.initialize=function(D){var C,H,F,E,B,G;if(D==null){D={}}if(D.swaggerOptions.sorter){F=D.swaggerOptions.sorter;H=z[F];G=this.model.apisArray;for(E=0,B=G.length;EB){K=B-C}if(KA){H=A-E}if(H0){D[I.name]=I.value}if(I.type==="file"){N=true}}E=G.find("textarea");for(L=0,F=E.length;L0){D.body=I.value}}B=G.find("select");for(K=0,C=B.length;K0){D[I.name]=J}}A.responseContentType=$("div select[name=responseContentType]",$(this.el)).val();A.requestContentType=$("div select[name=parameterContentType]",$(this.el)).val();$(".response_throbber",$(this.el)).show();if(N){return this.handleFileUpload(D,G)}else{return this.model["do"](D,A,this.showCompleteStatus,this.showErrorStatus,this)}}};y.prototype.success=function(A,B){return B.showCompleteStatus(A)};y.prototype.handleFileUpload=function(R,I){var M,H,C,N,L,K,P,J,G,F,D,Q,U,T,S,E,B,A,V,O=this;E=I.serializeArray();for(J=0,Q=E.length;J0){R[N.name]=N.value}}M=new FormData();P=0;B=this.model.parameters;for(G=0,U=B.length;G
        ");$(".request_url pre",$(this.el)).text(this.invocationUrl);L={type:this.model.method,url:this.invocationUrl,headers:C,data:M,dataType:"json",contentType:false,processData:false,error:function(X,Y,W){return O.showErrorStatus(O.wrap(X),O)},success:function(W){return O.showResponse(W,O)},complete:function(W){return O.showCompleteStatus(O.wrap(W),O)}};if(window.authorizations){window.authorizations.apply(L)}if(P===0){L.data.append("fake","true")}jQuery.ajax(L);return false};y.prototype.wrap=function(E){var C,F,H,B,G,D,A;H={};F=E.getAllResponseHeaders().split("\r");for(D=0,A=F.length;D0){return C.join(",")}else{return null}}};y.prototype.hideResponse=function(A){if(A!=null){A.preventDefault()}$(".response",$(this.el)).slideUp();return $(".response_hider",$(this.el)).fadeOut()};y.prototype.showResponse=function(A){var B;B=JSON.stringify(A,null,"\t").replace(/\n/g,"
        ");return $(".response_body",$(this.el)).html(escape(B))};y.prototype.showErrorStatus=function(B,A){return A.showStatus(B)};y.prototype.showCompleteStatus=function(B,A){return A.showStatus(B)};y.prototype.formatXml=function(H){var D,G,B,I,N,J,C,A,L,M,F,E,K;A=/(>)(<)(\/*)/g;M=/[ ]*(.*)[ ]+\n/g;D=/(<.+>)(.+\n)/g;H=H.replace(A,"$1\n$2$3").replace(M,"$1\n").replace(D,"$1\n$2");C=0;G="";N=H.split("\n");B=0;I="other";L={"single->single":0,"single->closing":-1,"single->opening":0,"single->other":0,"closing->single":0,"closing->closing":-1,"closing->opening":0,"closing->other":0,"opening->single":1,"opening->closing":0,"opening->opening":1,"opening->other":1,"other->single":0,"other->closing":-1,"other->opening":0,"other->other":0};F=function(T){var P,O,R,V,S,Q,U;Q={single:Boolean(T.match(/<.+\/>/)),closing:Boolean(T.match(/<\/.+>/)),opening:Boolean(T.match(/<[^!?].*>/))};S=((function(){var W;W=[];for(R in Q){U=Q[R];if(U){W.push(R)}}return W})())[0];S=S===void 0?"other":S;P=I+"->"+S;I=S;V="";B+=L[P];V=((function(){var X,Y,W;W=[];for(O=X=0,Y=B;0<=Y?XY;O=0<=Y?++X:--X){W.push(" ")}return W})()).join("");if(P==="opening->closing"){return G=G.substr(0,G.length-1)+T+"\n"}else{return G+=V+T+"\n"}};for(E=0,K=N.length;E").text("no content");E=$('
        ').append(C)}else{if(J==="application/json"||/\+json$/.test(J)){C=$("").text(JSON.stringify(JSON.parse(H),null,"  "));E=$('
        ').append(C)}else{if(J==="application/xml"||/\+xml$/.test(J)){C=$("").text(this.formatXml(H));E=$('
        ').append(C)}else{if(J==="text/html"){C=$("").html(H);E=$('
        ').append(C)}else{if(/^image\//.test(J)){E=$("").attr("src",B)}else{C=$("").text(H);E=$('
        ').append(C)}}}}}I=E;$(".request_url",$(this.el)).html("
        ");$(".request_url pre",$(this.el)).text(B);$(".response_code",$(this.el)).html("
        "+F.status+"
        ");$(".response_body",$(this.el)).html(I);$(".response_headers",$(this.el)).html("
        "+_.escape(JSON.stringify(F.headers,null,"  ")).replace(/\n/g,"
        ")+"
        ");$(".response",$(this.el)).slideDown();$(".response_hider",$(this.el)).show();$(".response_throbber",$(this.el)).hide();G=$(".response_body",$(this.el))[0];A=this.options.swaggerOptions;if(A.highlightSizeThreshold&&F.data.length>A.highlightSizeThreshold){return G}else{return hljs.highlightBlock(G)}};y.prototype.toggleOperationContent=function(){var A;A=$("#"+Docs.escapeResourceName(this.model.parentId)+"_"+this.model.nickname+"_content");if(A.is(":visible")){return Docs.collapseOperation(A)}else{return Docs.expandOperation(A)}};return y})(Backbone.View);p=(function(z){v(y,z);function y(){d=y.__super__.constructor.apply(this,arguments);return d}y.prototype.initialize=function(){};y.prototype.render=function(){var B,A,C;C=this.template();$(this.el).html(C(this.model));if(swaggerUi.api.models.hasOwnProperty(this.model.responseModel)){B={sampleJSON:JSON.stringify(swaggerUi.api.models[this.model.responseModel].createJSONSample(),null,2),isParam:false,signature:swaggerUi.api.models[this.model.responseModel].getMockSignature()};A=new i({model:B,tagName:"div"});$(".model-signature",this.$el).append(A.render().el)}else{$(".model-signature",this.$el).html("")}return this};y.prototype.template=function(){return Handlebars.templates.status_code};return y})(Backbone.View);k=(function(z){v(y,z);function y(){b=y.__super__.constructor.apply(this,arguments);return b}y.prototype.initialize=function(){return Handlebars.registerHelper("isArray",function(B,A){if(B.type.toLowerCase()==="array"||B.allowMultiple){return A.fn(this)}else{return A.inverse(this)}})};y.prototype.render=function(){var G,A,C,F,B,H,E,D;D=this.model.type||this.model.dataType;if(this.model.paramType==="body"){this.model.isBody=true}if(D.toLowerCase()==="file"){this.model.isFile=true}E=this.template();$(this.el).html(E(this.model));B={sampleJSON:this.model.sampleJSON,isParam:true,signature:this.model.signature};if(this.model.sampleJSON){H=new i({model:B,tagName:"div"});$(".model-signature",$(this.el)).append(H.render().el)}else{$(".model-signature",$(this.el)).html(this.model.signature)}A=false;if(this.model.isBody){A=true}G={isParam:A};G.consumes=this.model.consumes;if(A){C=new l({model:G});$(".parameter-content-type",$(this.el)).append(C.render().el)}else{F=new m({model:G});$(".response-content-type",$(this.el)).append(F.render().el)}return this};y.prototype.template=function(){if(this.model.isList){return Handlebars.templates.param_list}else{if(this.options.readOnly){if(this.model.required){return Handlebars.templates.param_readonly_required}else{return Handlebars.templates.param_readonly}}else{if(this.model.required){return Handlebars.templates.param_required}else{return Handlebars.templates.param}}}};return y})(Backbone.View);i=(function(z){v(y,z);function y(){a=y.__super__.constructor.apply(this,arguments);return a}y.prototype.events={"click a.description-link":"switchToDescription","click a.snippet-link":"switchToSnippet","mousedown .snippet":"snippetToTextArea"};y.prototype.initialize=function(){};y.prototype.render=function(){var A;A=this.template();$(this.el).html(A(this.model));this.switchToSnippet();this.isParam=this.model.isParam;if(this.isParam){$(".notice",$(this.el)).text("Click to set as parameter value")}return this};y.prototype.template=function(){return Handlebars.templates.signature};y.prototype.switchToDescription=function(A){if(A!=null){A.preventDefault()}$(".snippet",$(this.el)).hide();$(".description",$(this.el)).show();$(".description-link",$(this.el)).addClass("selected");return $(".snippet-link",$(this.el)).removeClass("selected")};y.prototype.switchToSnippet=function(A){if(A!=null){A.preventDefault()}$(".description",$(this.el)).hide();$(".snippet",$(this.el)).show();$(".snippet-link",$(this.el)).addClass("selected");return $(".description-link",$(this.el)).removeClass("selected")};y.prototype.snippetToTextArea=function(A){var B;if(this.isParam){if(A!=null){A.preventDefault()}B=$("textarea",$(this.el.parentNode.parentNode.parentNode));if($.trim(B.val())===""){return B.val(this.model.sampleJSON)}}};return y})(Backbone.View);j=(function(y){v(z,y);function z(){x=z.__super__.constructor.apply(this,arguments);return x}z.prototype.initialize=function(){};z.prototype.render=function(){var A;A=this.template();$(this.el).html(A(this.model));$("label[for=contentType]",$(this.el)).text("Response Content Type");return this};z.prototype.template=function(){return Handlebars.templates.content_type};return z})(Backbone.View);m=(function(y){v(z,y);function z(){w=z.__super__.constructor.apply(this,arguments);return w}z.prototype.initialize=function(){};z.prototype.render=function(){var A;A=this.template();$(this.el).html(A(this.model));$("label[for=responseContentType]",$(this.el)).text("Response Content Type");return this};z.prototype.template=function(){return Handlebars.templates.response_content_type};return z})(Backbone.View);l=(function(z){v(y,z);function y(){c=y.__super__.constructor.apply(this,arguments);return c}y.prototype.initialize=function(){};y.prototype.render=function(){var A;A=this.template();$(this.el).html(A(this.model));$("label[for=parameterContentType]",$(this.el)).text("Parameter content type:");return this};y.prototype.template=function(){return Handlebars.templates.parameter_content_type};return y})(Backbone.View)}).call(this); \ No newline at end of file From 160eb194ea28e33f12953aa2b5bf5d64b1033537 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 24 May 2017 15:24:35 +0200 Subject: [PATCH 18/20] Clean REST response for user and third parties --- .../societe/class/api_thirdparties.class.php | 21 ++++++++++++++++++- htdocs/user/class/api_users.class.php | 20 ++++++++++++++---- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/htdocs/societe/class/api_thirdparties.class.php b/htdocs/societe/class/api_thirdparties.class.php index df7965d6d8c..507fd62ec48 100644 --- a/htdocs/societe/class/api_thirdparties.class.php +++ b/htdocs/societe/class/api_thirdparties.class.php @@ -311,7 +311,26 @@ class Thirdparties extends DolibarrApi return $this->company; } - /** + /** + * Clean sensible object datas + * + * @param object $object Object to clean + * @return array Array of cleaned object properties + */ + function _cleanObjectDatas($object) { + + $object = parent::_cleanObjectDatas($object); + + unset($object->total_ht); + unset($object->total_tva); + unset($object->total_localtax1); + unset($object->total_localtax2); + unset($object->total_ttc); + + return $object; + } + + /** * Validate fields before create or update object * * @param array $data Datas to validate diff --git a/htdocs/user/class/api_users.class.php b/htdocs/user/class/api_users.class.php index aa2569fb3ca..af1b8441293 100644 --- a/htdocs/user/class/api_users.class.php +++ b/htdocs/user/class/api_users.class.php @@ -225,9 +225,9 @@ class Users extends DolibarrApi /** * add user to group * - * @param int $id User ID - * @param int $group Group ID - * @return int + * @param int $id User ID + * @param int $group Group ID + * @return int 1 if success * * @url GET {id}/setGroup/{group} */ @@ -246,7 +246,13 @@ class Users extends DolibarrApi throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login); } - return $this->useraccount->SetInGroup($group,1); + $result = $this->useraccount->SetInGroup($group,1); + if (! ($result > 0)) + { + throw new RestException(500, $this->useraccount->error); + } + + return 1; } /** @@ -287,6 +293,12 @@ class Users extends DolibarrApi unset($object->lastsearch_values); unset($object->lastsearch_values_tmp); + unset($object->total_ht); + unset($object->total_tva); + unset($object->total_localtax1); + unset($object->total_localtax2); + unset($object->total_ttc); + return $object; } From 3782bc445888981404e16b246dd8729e182ed637 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 24 May 2017 18:00:26 +0200 Subject: [PATCH 19/20] Look and feel v6 --- htdocs/projet/admin/project.php | 2 +- htdocs/projet/admin/project_extrafields.php | 2 +- htdocs/projet/admin/project_task_extrafields.php | 2 +- htdocs/projet/tasks/time.php | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/htdocs/projet/admin/project.php b/htdocs/projet/admin/project.php index 42cacc19272..fbcecf032cf 100644 --- a/htdocs/projet/admin/project.php +++ b/htdocs/projet/admin/project.php @@ -318,7 +318,7 @@ print load_fiche_titre($langs->trans("ProjectsSetup"),$linkback,'title_setup'); $head=project_admin_prepare_head(); -dol_fiche_head($head, 'project', $langs->trans("Projects"), 0, 'project'); +dol_fiche_head($head, 'project', $langs->trans("Projects"), -1, 'project'); diff --git a/htdocs/projet/admin/project_extrafields.php b/htdocs/projet/admin/project_extrafields.php index e3e070a3473..26a6286f034 100644 --- a/htdocs/projet/admin/project_extrafields.php +++ b/htdocs/projet/admin/project_extrafields.php @@ -70,7 +70,7 @@ print load_fiche_titre($langs->trans("ProjectsSetup"),$linkback,'title_setup'); $head = project_admin_prepare_head(); -dol_fiche_head($head, 'attributes', $langs->trans("Projects"), 0, 'project'); +dol_fiche_head($head, 'attributes', $langs->trans("Projects"), -1, 'project'); require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php'; diff --git a/htdocs/projet/admin/project_task_extrafields.php b/htdocs/projet/admin/project_task_extrafields.php index 3d6e1d78fe8..58f91e863fc 100644 --- a/htdocs/projet/admin/project_task_extrafields.php +++ b/htdocs/projet/admin/project_task_extrafields.php @@ -69,7 +69,7 @@ print load_fiche_titre($langs->trans("ProjectsSetup"),$linkback,'title_setup'); $head = project_admin_prepare_head(); -dol_fiche_head($head, 'attributes_task', $langs->trans("Projects"), 0, 'project'); +dol_fiche_head($head, 'attributes_task', $langs->trans("Projects"), -1, 'project'); require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_view.tpl.php'; diff --git a/htdocs/projet/tasks/time.php b/htdocs/projet/tasks/time.php index cbdfece9d45..b35cc4d707d 100644 --- a/htdocs/projet/tasks/time.php +++ b/htdocs/projet/tasks/time.php @@ -96,7 +96,7 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria -if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") ||GETPOST("button_removefilter")) // All test are required to be compatible with all browsers +if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") ||GETPOST("button_removefilter")) // All tests are required to be compatible with all browsers { $search_date=''; $search_datehour=''; @@ -305,7 +305,7 @@ if (($id > 0 || ! empty($ref)) || $projectidforalltimes > 0) // Tabs for project $tab='tasks'; $head=project_prepare_head($projectstatic); - dol_fiche_head($head, $tab, $langs->trans("Project"), 0, ($projectstatic->public?'projectpub':'project')); + dol_fiche_head($head, $tab, $langs->trans("Project"), -1, ($projectstatic->public?'projectpub':'project')); $param=($mode=='mine'?'&mode=mine':''); From e5fe629a0e761063f74b6787ea61735d71880981 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 24 May 2017 22:48:44 +0200 Subject: [PATCH 20/20] NEW Extrafields support formulas to be computed using PHP expressions --- htdocs/contact/list.php | 6 +- htdocs/core/actions_extrafields.inc.php | 108 ++++++++++-------- htdocs/core/class/extrafields.class.php | 97 +++++++++++----- htdocs/core/lib/functions.lib.php | 24 +++- htdocs/core/tpl/admin_extrafields_add.tpl.php | 67 ++++++++--- .../core/tpl/admin_extrafields_edit.tpl.php | 59 ++++++++-- .../core/tpl/admin_extrafields_view.tpl.php | 6 +- .../install/mysql/migration/5.0.0-6.0.0.sql | 5 +- .../install/mysql/tables/llx_extrafields.sql | 6 +- htdocs/langs/en_US/admin.lang | 12 +- htdocs/langs/en_US/main.lang | 1 + .../modulebuilder/skeletons/skeleton_list.php | 20 ++-- htdocs/projet/list.php | 50 ++++---- htdocs/projet/tasks/list.php | 37 +++--- htdocs/societe/class/societe.class.php | 2 - htdocs/societe/list.php | 6 +- 16 files changed, 335 insertions(+), 171 deletions(-) diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index 39557a6e455..9bcfee7ccae 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -597,7 +597,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab $align=$extrafields->getAlignFlag($key); $typeofextrafield=$extrafields->attribute_type[$key]; print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) { $crit=$val; $tmpkey=preg_replace('/search_options_/','',$key); @@ -664,7 +664,9 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab if (! empty($arrayfields["ef.".$key]['checked'])) { $align=$extrafields->getAlignFlag($key); - print_liste_field_titre($langs->trans($extralabels[$key]),$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($langs->trans($extralabels[$key]),$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); } } } diff --git a/htdocs/core/actions_extrafields.inc.php b/htdocs/core/actions_extrafields.inc.php index afcf929589b..b34cbe886ab 100644 --- a/htdocs/core/actions_extrafields.inc.php +++ b/htdocs/core/actions_extrafields.inc.php @@ -14,6 +14,8 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . * or see http://www.gnu.org/ + * + * $elementype must be defined. */ /** @@ -24,11 +26,14 @@ $maxsizestring=255; $maxsizeint=10; -$extrasize=GETPOST('size'); -if (GETPOST('type')=='double' && strpos($extrasize,',')===false) $extrasize='24,8'; -if (GETPOST('type')=='date') $extrasize=''; -if (GETPOST('type')=='datetime') $extrasize=''; -if (GETPOST('type')=='select') $extrasize=''; +$extrasize=GETPOST('size','int'); +$type=GETPOST('type','alpha'); +$param=GETPOST('param','alpha');; + +if ($type=='double' && strpos($extrasize,',')===false) $extrasize='24,8'; +if ($type=='date') $extrasize=''; +if ($type=='datetime') $extrasize=''; +if ($type=='select') $extrasize=''; // Add attribute @@ -37,73 +42,73 @@ if ($action == 'add') if ($_POST["button"] != $langs->trans("Cancel")) { // Check values - if (! GETPOST('type')) + if (! $type) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Type")); $action = 'create'; } - if (GETPOST('type')=='varchar' && $extrasize <= 0) + if ($type=='varchar' && $extrasize <= 0) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Size")); $action = 'edit'; } - if (GETPOST('type')=='varchar' && $extrasize > $maxsizestring) + if ($type=='varchar' && $extrasize > $maxsizestring) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorSizeTooLongForVarcharType",$maxsizestring); $action = 'create'; } - if (GETPOST('type')=='int' && $extrasize > $maxsizeint) + if ($type=='int' && $extrasize > $maxsizeint) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorSizeTooLongForIntType",$maxsizeint); $action = 'create'; } - if (GETPOST('type')=='select' && !GETPOST('param')) + if ($type=='select' && !$param) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorNoValueForSelectType"); $action = 'create'; } - if (GETPOST('type')=='sellist' && !GETPOST('param')) + if ($type=='sellist' && !$param) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorNoValueForSelectListType"); $action = 'create'; } - if (GETPOST('type')=='checkbox' && !GETPOST('param')) + if ($type=='checkbox' && !$param) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorNoValueForCheckBoxType"); $action = 'create'; } - if (GETPOST('type')=='link' && !GETPOST('param')) + if ($type=='link' && !$param) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorNoValueForLinkType"); $action = 'create'; } - if (GETPOST('type')=='radio' && !GETPOST('param')) + if ($type=='radio' && !$param) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorNoValueForRadioType"); $action = 'create'; } - if (((GETPOST('type')=='radio') || (GETPOST('type')=='checkbox')) && GETPOST('param')) + if ((($type=='radio') || ($type=='checkbox')) && $param) { // Construct array for parameter (value of select list) - $parameters = GETPOST('param'); + $parameters = $param; $parameters_array = explode("\r\n",$parameters); foreach($parameters_array as $param_ligne) { @@ -134,11 +139,11 @@ if ($action == 'add') if (isset($_POST["attrname"]) && preg_match("/^[a-z0-9-_]+$/",$_POST['attrname']) && !is_numeric($_POST["attrname"])) { // Construct array for parameter (value of select list) - $default_value = GETPOST('default_value'); - $parameters = GETPOST('param'); + $default_value = GETPOST('default_value','alpha'); + $parameters = $param; $parameters_array = explode("\r\n",$parameters); //In sellist we have only one line and it can have come to do SQL expression - if (GETPOST('type')=='sellist') { + if ($type=='sellist') { foreach($parameters_array as $param_ligne) { $params['options'] = array($parameters=>null); @@ -155,20 +160,21 @@ if ($action == 'add') } $result=$extrafields->addExtraField( - GETPOST('attrname'), - GETPOST('label'), - GETPOST('type'), - GETPOST('pos'), + GETPOST('attrname', 'alpha'), + GETPOST('label', 'alpha'), + $type, + GETPOST('pos', 'alpha'), $extrasize, $elementtype, - (GETPOST('unique')?1:0), - (GETPOST('required')?1:0), + (GETPOST('unique', 'alpha')?1:0), + (GETPOST('required', 'alpha')?1:0), $default_value, $params, - (GETPOST('alwayseditable')?1:0), - (GETPOST('perms')?GETPOST('perms'):''), - (GETPOST('list')?1:0), - (GETPOST('ishidden')?1:0) + (GETPOST('alwayseditable', 'alpha')?1:0), + (GETPOST('perms', 'alpha')?GETPOST('perms', 'alpha'):''), + (GETPOST('list', 'alpha')?1:0), + (GETPOST('ishidden', 'alpha')?1:0), + GETPOST('computed_value','alpha') ); if ($result > 0) { @@ -205,66 +211,66 @@ if ($action == 'update') if ($_POST["button"] != $langs->trans("Cancel")) { // Check values - if (! GETPOST('type')) + if (! $type) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Type")); $action = 'edit'; } - if (GETPOST('type')=='varchar' && $extrasize <= 0) + if ($type=='varchar' && $extrasize <= 0) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorFieldRequired",$langs->transnoentitiesnoconv("Size")); $action = 'edit'; } - if (GETPOST('type')=='varchar' && $extrasize > $maxsizestring) + if ($type=='varchar' && $extrasize > $maxsizestring) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorSizeTooLongForVarcharType",$maxsizestring); $action = 'edit'; } - if (GETPOST('type')=='int' && $extrasize > $maxsizeint) + if ($type=='int' && $extrasize > $maxsizeint) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorSizeTooLongForIntType",$maxsizeint); $action = 'edit'; } - if (GETPOST('type')=='select' && !GETPOST('param')) + if ($type=='select' && !$param) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorNoValueForSelectType"); $action = 'edit'; } - if (GETPOST('type')=='sellist' && !GETPOST('param')) + if ($type=='sellist' && !$param) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorNoValueForSelectListType"); $action = 'edit'; } - if (GETPOST('type')=='checkbox' && !GETPOST('param')) + if ($type=='checkbox' && !$param) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorNoValueForCheckBoxType"); $action = 'edit'; } - if (GETPOST('type')=='radio' && !GETPOST('param')) + if ($type=='radio' && !$param) { $error++; $langs->load("errors"); $mesg[]=$langs->trans("ErrorNoValueForRadioType"); $action = 'edit'; } - if (((GETPOST('type')=='radio') || (GETPOST('type')=='checkbox')) && GETPOST('param')) + if ((($type=='radio') || ($type=='checkbox')) && $param) { // Construct array for parameter (value of select list) - $parameters = GETPOST('param'); + $parameters = $param; $parameters_array = explode("\r\n",$parameters); foreach($parameters_array as $param_ligne) { @@ -295,10 +301,10 @@ if ($action == 'update') { $pos = GETPOST('pos','int'); // Construct array for parameter (value of select list) - $parameters = GETPOST('param'); + $parameters = $param; $parameters_array = explode("\r\n",$parameters); //In sellist we have only one line and it can have come to do SQL expression - if (GETPOST('type')=='sellist') { + if ($type=='sellist') { foreach($parameters_array as $param_ligne) { $params['options'] = array($parameters=>null); @@ -315,19 +321,21 @@ if ($action == 'update') } $result=$extrafields->update( - GETPOST('attrname'), - GETPOST('label'), - GETPOST('type'), + GETPOST('attrname', 'alpha'), + GETPOST('label', 'alpha'), + $type, $extrasize, $elementtype, - (GETPOST('unique')?1:0), - (GETPOST('required')?1:0), + (GETPOST('unique', 'alpha')?1:0), + (GETPOST('required', 'alpha')?1:0), $pos, $params, - (GETPOST('alwayseditable')?1:0), - (GETPOST('perms')?GETPOST('perms'):''), - (GETPOST('list')?1:0), - (GETPOST('ishidden')?1:0) + (GETPOST('alwayseditable', 'alpha')?1:0), + (GETPOST('perms', 'alpha')?GETPOST('perms', 'alpha'):''), + (GETPOST('list', 'alpha')?1:0), + (GETPOST('ishidden', 'alpha')?1:0), + GETPOST('default_value','alpha'), + GETPOST('computed_value','alpha') ); if ($result > 0) { diff --git a/htdocs/core/class/extrafields.class.php b/htdocs/core/class/extrafields.class.php index f86f786e0fb..c89fc593745 100644 --- a/htdocs/core/class/extrafields.class.php +++ b/htdocs/core/class/extrafields.class.php @@ -36,14 +36,22 @@ class ExtraFields { var $db; - // Tableau contenant le nom des champs en clef et la definition de ces champs + + // type of element (for what object is the extrafield) + var $attribute_elementtype; + + // Array with type of the extra field var $attribute_type; - // Tableau contenant le nom des champs en clef et le label de ces champs en value + // Array with label of extra field var $attribute_label; - // Tableau contenant le nom des champs en clef et la taille/longueur max de ces champs en value + // Array with size of extra field var $attribute_size; - // Tableau contenant le nom des choix en clef et la valeur de ces choix en value + // array with list of possible values for some types of extra fields var $attribute_choice; + // Array to store compute formula for computed fields + var $attribute_computed; + // Array to store default value + var $attribute_default; // Array to store if attribute is unique or not var $attribute_unique; // Array to store if attribute is required or not @@ -77,16 +85,17 @@ class ExtraFields 'phone'=>'ExtrafieldPhone', 'mail'=>'ExtrafieldMail', 'url'=>'ExtrafieldUrl', + 'password' => 'ExtrafieldPassword', 'select' => 'ExtrafieldSelect', 'sellist' => 'ExtrafieldSelectList', 'radio' => 'ExtrafieldRadio', 'checkbox' => 'ExtrafieldCheckBox', 'chkbxlst' => 'ExtrafieldCheckBoxFromList', 'link' => 'ExtrafieldLink', - 'password' => 'ExtrafieldPassword', 'separate' => 'ExtrafieldSeparator', ); + /** * Constructor * @@ -96,10 +105,12 @@ class ExtraFields { $this->db = $db; $this->error = array(); + $this->attribute_elementtype = array(); $this->attribute_type = array(); $this->attribute_label = array(); $this->attribute_size = array(); - $this->attribute_elementtype = array(); + $this->attribute_computed = array(); + $this->attribute_default = array(); $this->attribute_unique = array(); $this->attribute_required = array(); $this->attribute_perms = array(); @@ -118,15 +129,16 @@ class ExtraFields * @param string $elementtype Element type ('member', 'product', 'thirdparty', ...) * @param int $unique Is field unique or not * @param int $required Is field required or not - * @param string $default_value Defaulted value (Example: '', '0', 'null', 'avalue') + * @param string $default_value Defaulted value (In database. use the default_value feature for default value on screen. Example: '', '0', 'null', 'avalue') * @param array $param Params for field * @param int $alwayseditable Is attribute always editable regardless of the document status * @param string $perms Permission to check * @param int $list Into list view by default * @param int $ishidden Is hidden extrafield (warning, do not rely on this. If your module need a hidden data, it must use its own table) + * @param string $computed Computed value * @return int <=0 if KO, >0 if OK */ - function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique=0, $required=0, $default_value='', $param=0, $alwayseditable=0, $perms='', $list=0, $ishidden=0) + function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique=0, $required=0, $default_value='', $param=0, $alwayseditable=0, $perms='', $list=0, $ishidden=0, $computed='') { if (empty($attrname)) return -1; if (empty($label)) return -1; @@ -137,13 +149,13 @@ class ExtraFields // Create field into database except for separator type which is not stored in database if ($type != 'separate') { - $result=$this->create($attrname, $type, $size, $elementtype, $unique, $required, $default_value, $param, $perms, $list); + $result=$this->create($attrname, $type, $size, $elementtype, $unique, $required, $default_value, $param, $perms, $list, $copmputed); } $err1=$this->errno; if ($result > 0 || $err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' || $type == 'separate') { // Add declaration of field into table - $result2=$this->create_label($attrname,$label,$type,$pos,$size,$elementtype, $unique, $required, $param, $alwayseditable, $perms, $list, $ishidden); + $result2=$this->create_label($attrname, $label, $type, $pos, $size, $elementtype, $unique, $required, $param, $alwayseditable, $perms, $list, $ishidden, $default, $computed); $err2=$this->errno; if ($result2 > 0 || ($err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' && $err2 == 'DB_ERROR_RECORD_ALREADY_EXISTS')) { @@ -169,13 +181,14 @@ class ExtraFields * @param string $elementtype Element type ('member', 'product', 'thirdparty', 'contact', ...) * @param int $unique Is field unique or not * @param int $required Is field required or not - * @param string $default_value Default value for field + * @param string $default_value Default value for field (in database) * @param array $param Params for field (ex for select list : array('options'=>array('value'=>'label of option')) * @param string $perms Permission * @param int $list Into list view by default + * @param string $computed Computed value * @return int <=0 if KO, >0 if OK */ - private function create($attrname, $type='varchar', $length=255, $elementtype='member', $unique=0, $required=0, $default_value='',$param='', $perms='', $list=0) + private function create($attrname, $type='varchar', $length=255, $elementtype='member', $unique=0, $required=0, $default_value='',$param='', $perms='', $list=0, $computed='') { if ($elementtype == 'thirdparty') $elementtype='societe'; if ($elementtype == 'contact') $elementtype='socpeople'; @@ -258,9 +271,11 @@ class ExtraFields * @param string $perms Permission to check * @param int $list Into list view by default * @param int $ishidden Is hidden extrafield (warning, do not rely on this. If your module need a hidden data, it must use its own table) + * @param string $default Default value (in database. use the default_value feature for default value on screen). + * @param string $computed Computed value * @return int <=0 if KO, >0 if OK */ - private function create_label($attrname, $label='', $type='', $pos=0, $size=0, $elementtype='member', $unique=0, $required=0, $param='', $alwayseditable=0, $perms='', $list=0, $ishidden=0) + private function create_label($attrname, $label='', $type='', $pos=0, $size=0, $elementtype='member', $unique=0, $required=0, $param='', $alwayseditable=0, $perms='', $list=0, $ishidden=0, $default='', $computed='') { global $conf; @@ -286,7 +301,7 @@ class ExtraFields $params=''; } - $sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields(name, label, type, pos, size, entity, elementtype, fieldunique, fieldrequired, param, alwayseditable, perms, list, ishidden)"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields(name, label, type, pos, size, entity, elementtype, fieldunique, fieldrequired, param, alwayseditable, perms, list, ishidden, fielddefault, fieldcomputed)"; $sql.= " VALUES('".$attrname."',"; $sql.= " '".$this->db->escape($label)."',"; $sql.= " '".$type."',"; @@ -299,8 +314,10 @@ class ExtraFields $sql.= " '".$params."',"; $sql.= " '".$alwayseditable."',"; $sql.= " ".($perms?"'".$this->db->escape($perms)."'":"null").","; - $sql.= " ".$list; - $sql.= ", ".$ishidden; + $sql.= " ".$list.","; + $sql.= " ".$ishidden.","; + $sql.= " ".($default?"'".$this->db->escape($default)."'":"null").","; + $sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null"); $sql.=')'; dol_syslog(get_class($this)."::create_label", LOG_DEBUG); @@ -430,9 +447,11 @@ class ExtraFields * @param string $perms Permission to check * @param int $list Into list view by default * @param int $ishidden Is hidden extrafield (warning, do not rely on this. If your module need a hidden data, it must use its own table) + * @param string $default Default value (in database. use the default_value feature for default value on screen). + * @param string $computed Computed value * @return int >0 if OK, <=0 if KO */ - function update($attrname,$label,$type,$length,$elementtype,$unique=0,$required=0,$pos=0,$param='',$alwayseditable=0, $perms='',$list='',$ishidden=0) + function update($attrname,$label,$type,$length,$elementtype,$unique=0,$required=0,$pos=0,$param='',$alwayseditable=0, $perms='',$list='',$ishidden=0,$default='',$computed='') { if ($elementtype == 'thirdparty') $elementtype='societe'; if ($elementtype == 'contact') $elementtype='socpeople'; @@ -479,7 +498,7 @@ class ExtraFields { if ($label) { - $result=$this->update_label($attrname,$label,$type,$length,$elementtype,$unique,$required,$pos,$param,$alwayseditable,$perms,$list,$ishidden); + $result=$this->update_label($attrname,$label,$type,$length,$elementtype,$unique,$required,$pos,$param,$alwayseditable,$perms,$list,$ishidden,$default,$computed); } if ($result > 0) { @@ -531,12 +550,14 @@ class ExtraFields * @param string $perms Permission to check * @param int $list Into list view by default * @param int $ishidden Is hidden extrafield (warning, do not rely on this. If your module need a hidden data, it must use its own table) + * @param string $default Default value (in database. use the default_value feature for default value on screen). + * @param string $computed Computed value * @return int <=0 if KO, >0 if OK */ - private function update_label($attrname,$label,$type,$size,$elementtype,$unique=0,$required=0,$pos=0,$param='',$alwayseditable=0,$perms='',$list=0,$ishidden=0) + private function update_label($attrname,$label,$type,$size,$elementtype,$unique=0,$required=0,$pos=0,$param='',$alwayseditable=0,$perms='',$list=0,$ishidden=0,$default='',$computed='') { global $conf; - dol_syslog(get_class($this)."::update_label ".$attrname.", ".$label.", ".$type.", ".$size.", ".$elementtype.", ".$unique.", ".$required.", ".$pos.", ".$alwayseditable.", ".$perms.", ".$list.", ".$ishidden); + dol_syslog(get_class($this)."::update_label ".$attrname.", ".$label.", ".$type.", ".$size.", ".$elementtype.", ".$unique.", ".$required.", ".$pos.", ".$alwayseditable.", ".$perms.", ".$list.", ".$ishidden.", ".$default.", ".$computed); // Clean parameters if ($elementtype == 'thirdparty') $elementtype='societe'; @@ -557,7 +578,7 @@ class ExtraFields $sql_del.= " WHERE name = '".$attrname."'"; $sql_del.= " AND entity = ".$conf->entity; $sql_del.= " AND elementtype = '".$elementtype."'"; - dol_syslog(get_class($this)."::update_label", LOG_DEBUG); + $resql1=$this->db->query($sql_del); $sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields("; @@ -573,8 +594,10 @@ class ExtraFields $sql.= " pos,"; $sql.= " alwayseditable,"; $sql.= " param,"; - $sql.= " list"; - $sql.= ", ishidden"; + $sql.= " list,"; + $sql.= " ishidden,"; + $sql.= " fielddefault,"; + $sql.= " fieldcomputed"; $sql.= ") VALUES ("; $sql.= "'".$attrname."',"; $sql.= " ".$conf->entity.","; @@ -588,10 +611,12 @@ class ExtraFields $sql.= " '".$pos."',"; $sql.= " '".$alwayseditable."',"; $sql.= " '".$param."',"; - $sql.= " ".$list; - $sql.= ", ".$ishidden; + $sql.= " ".$list.", "; + $sql.= " ".$ishidden.", "; + $sql.= " ".($default?"'".$this->db->escape($default)."'":"null").","; + $sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null"); $sql.= ")"; - dol_syslog(get_class($this)."::update_label", LOG_DEBUG); + $resql2=$this->db->query($sql); if ($resql1 && $resql2) @@ -635,7 +660,7 @@ class ExtraFields // For avoid conflicts with external modules if (!$forceload && !empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return $array_name_label; - $sql = "SELECT rowid,name,label,type,size,elementtype,fieldunique,fieldrequired,param,pos,alwayseditable,perms,list,ishidden"; + $sql = "SELECT rowid,name,label,type,size,elementtype,fieldunique,fieldrequired,param,pos,alwayseditable,perms,list,ishidden,fielddefault,fieldcomputed"; $sql.= " FROM ".MAIN_DB_PREFIX."extrafields"; $sql.= " WHERE entity IN (0,".$conf->entity.")"; if ($elementtype) $sql.= " AND elementtype = '".$elementtype."'"; @@ -658,6 +683,8 @@ class ExtraFields $this->attribute_label[$tab->name]=$tab->label; $this->attribute_size[$tab->name]=$tab->size; $this->attribute_elementtype[$tab->name]=$tab->elementtype; + $this->attribute_default[$tab->name]=$tab->fielddefault; + $this->attribute_computed[$tab->name]=$tab->fieldcomputed; $this->attribute_unique[$tab->name]=$tab->fieldunique; $this->attribute_required[$tab->name]=$tab->fieldrequired; $this->attribute_param[$tab->name]=($tab->param ? unserialize($tab->param) : ''); @@ -699,6 +726,8 @@ class ExtraFields $type =$this->attribute_type[$key]; $size =$this->attribute_size[$key]; $elementtype=$this->attribute_elementtype[$key]; + $default=$this->attribute_default[$key]; + $computed=$this->attribute_computed[$key]; $unique=$this->attribute_unique[$key]; $required=$this->attribute_required[$key]; $param=$this->attribute_param[$key]; @@ -706,6 +735,8 @@ class ExtraFields $list=$this->attribute_list[$key]; $hidden=$this->attribute_hidden[$key]; + if ($computed) return ''.$langs->trans("AutomaticallyCalculated").''; + if (empty($showsize)) { if ($type == 'date') @@ -1218,10 +1249,12 @@ class ExtraFields { global $conf,$langs; + $elementtype=$this->attribute_elementtype[$key]; $label=$this->attribute_label[$key]; $type=$this->attribute_type[$key]; $size=$this->attribute_size[$key]; - $elementtype=$this->attribute_elementtype[$key]; + $default=$this->attribute_default[$key]; + $computed=$this->attribute_computed[$key]; $unique=$this->attribute_unique[$key]; $required=$this->attribute_required[$key]; $params=$this->attribute_param[$key]; @@ -1229,6 +1262,14 @@ class ExtraFields $list=$this->attribute_list[$key]; $hidden=$this->attribute_hidden[$key]; // warning, do not rely on this. If your module need a hidden data, it must use its own table. + // If field is a computed field, value must become result of compute + if ($computed) + { + // Make the eval of compute string + //var_dump($computed); + $value = dol_eval($computed, 1, 0); + } + $showsize=0; if ($type == 'date') { diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index e8ead0ed829..9ecfdc037f3 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -5604,20 +5604,32 @@ function verifCond($strRights) * * @param string $s String to evaluate * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)). + * @param int $hideerrors 1=Hide errors * @return mixed Nothing or return of eval */ -function dol_eval($s,$returnvalue=0) +function dol_eval($s, $returnvalue=0, $hideerrors=1) { // Only global variables can be changed by eval function and returned to caller - global $langs, $user, $conf; - global $leftmenu; + global $db, $langs, $user, $conf; + global $mainmenu, $leftmenu; global $rights; global $object; - global $soc; + global $mysoc; + + global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object + global $soc; // For backward compatibility //print $s."
        \n"; - if ($returnvalue) return @eval('return '.$s.';'); - else @eval($s); + if ($returnvalue) + { + if ($hideerrors) return @eval('return '.$s.';'); + else return eval('return '.$s.';'); + } + else + { + if ($hideerrors) @eval($s); + else eval($s); + } } /** diff --git a/htdocs/core/tpl/admin_extrafields_add.tpl.php b/htdocs/core/tpl/admin_extrafields_add.tpl.php index 9e4fd464ee6..62821372e56 100644 --- a/htdocs/core/tpl/admin_extrafields_add.tpl.php +++ b/htdocs/core/tpl/admin_extrafields_add.tpl.php @@ -18,10 +18,12 @@ */ /** - * The following vars must be defined + * The following vars must be defined: * $type2label * $form * $conf, $lang, + * The following vars may also be defined: + * $elementtype */ ?> @@ -31,15 +33,16 @@ jQuery(document).ready(function() { function init_typeoffields(type) { - console.log("select new type "+type); + console.log("selected type is "+type); var size = jQuery("#size"); + var computed_value = jQuery("#computed_value"); + var default_value = jQuery("#default_value"); var unique = jQuery("#unique"); var required = jQuery("#required"); - var default_value = jQuery("#default_value"); var alwayseditable = jQuery("#alwayseditable"); var list = jQuery("#list"); + // Case of computed field + console.log(type); + if (type == '' || type == 'varchar' || type == 'int' || type == 'double' || type == 'price') { + jQuery("tr.extra_computed_value").show(); + } else { + computed_value.val(''); jQuery("tr.extra_computed_value").hide(); + } + if (computed_value.val()) + { + console.log("We enter a computed formula"); + jQuery("#default_value").val(''); + /* jQuery("#unique, #required, #alwayseditable, #ishidden, #list").removeAttr('checked'); */ + jQuery("#default_value, #unique, #required, #alwayseditable, #ishidden, #list").attr('disabled', true); + jQuery("tr.extra_default_value, tr.extra_unique, tr.extra_required, tr.extra_alwayseditable, tr.extra_ishidden, tr.extra_list").hide(); + } + else + { + console.log("No computed formula"); + jQuery("#default_value, #unique, #required, #alwayseditable, #ishidden, #list").attr('disabled', false); + jQuery("tr.extra_default_value, tr.extra_unique, tr.extra_required, tr.extra_alwayseditable, tr.extra_ishidden, tr.extra_list").show(); + } + if (type == 'date') { size.val('').prop('disabled', true); unique.removeAttr('disabled'); jQuery("#value_choice").hide();jQuery("#helpchkbxlst").hide(); } else if (type == 'datetime') { size.val('').prop('disabled', true); unique.removeAttr('disabled'); jQuery("#value_choice").hide(); jQuery("#helpchkbxlst").hide();} else if (type == 'double') { size.val('24,8').removeAttr('disabled'); unique.removeAttr('disabled'); jQuery("#value_choice").hide(); jQuery("#helpchkbxlst").hide();} @@ -65,7 +90,10 @@ else if (type == 'checkbox') { size.val('').prop('disabled', true); unique.removeAttr('checked').prop('disabled', true); jQuery("#value_choice").show();jQuery("#helpselect").show();jQuery("#helpsellist").hide();jQuery("#helpchkbxlst").hide();jQuery("#helplink").hide();} else if (type == 'chkbxlst') { size.val('').prop('disabled', true); unique.removeAttr('checked').prop('disabled', true); jQuery("#value_choice").show();jQuery("#helpselect").hide();jQuery("#helpsellist").hide();jQuery("#helpchkbxlst").show();jQuery("#helplink").hide();} else if (type == 'link') { size.val('').prop('disabled', true); unique.removeAttr('disabled'); jQuery("#value_choice").show();jQuery("#helpselect").hide();jQuery("#helpsellist").hide();jQuery("#helpchkbxlst").hide();jQuery("#helplink").show();} - else if (type == 'separate') { size.val('').prop('disabled', true); unique.removeAttr('checked').prop('disabled', true); required.val('').prop('disabled', true); default_value.val('').prop('disabled', true); jQuery("#value_choice").hide();jQuery("#helpselect").hide();jQuery("#helpsellist").hide();jQuery("#helpchkbxlst").hide();jQuery("#helplink").hide();} + else if (type == 'separate') { + size.val('').prop('disabled', true); unique.removeAttr('checked').prop('disabled', true); required.val('').prop('disabled', true); + jQuery("#value_choice").hide();jQuery("#helpselect").hide();jQuery("#helpsellist").hide();jQuery("#helpchkbxlst").hide();jQuery("#helplink").hide(); + } else { // type = string size.val('').prop('disabled', true); unique.removeAttr('disabled'); @@ -73,10 +101,12 @@ if (type == 'separate') { - unique.removeAttr('checked').prop('disabled', true); required.removeAttr('checked').prop('disabled', true); alwayseditable.removeAttr('checked').prop('disabled', true); list.val('').prop('disabled', true); + required.removeAttr('checked').prop('disabled', true); alwayseditable.removeAttr('checked').prop('disabled', true); list.val('').prop('disabled', true); + jQuery('#size, #default_value').val('').prop('disabled', true); } else { + default_value.removeAttr('disabled'); required.removeAttr('disabled'); alwayseditable.removeAttr('disabled'); list.val('').removeAttr('disabled'); } } @@ -84,6 +114,11 @@ jQuery("#type").change(function() { init_typeoffields($(this).val()); }); + + // If we enter a formula, we disable other fields + jQuery("#computed_value").keyup(function() { + init_typeoffields(jQuery('#type').val()); + }); }); @@ -103,9 +138,7 @@ selectarray('type',$type2label,GETPOST('type')); ?> -trans("Size"); ?> - -trans("Position"); ?> +trans("Size"); ?> @@ -124,17 +157,21 @@ - -trans("DefaultValue"); ?>"> + +trans("Position"); ?> + +textwithpicto($langs->trans("ComputedFormula"), $langs->trans("ComputedFormulaDesc"), 1, 'help', '', 0, 2, 'tooltipcompute'); ?>"> + +trans("DefaultValue").' ('.$langs->trans("Database").')'; ?>"> -trans("Unique"); ?>> +trans("Unique"); ?>> -trans("Required"); ?>> +trans("Required"); ?>> -trans("AlwaysEditable"); ?>> +trans("AlwaysEditable"); ?>> global->MAIN_CAN_HIDE_EXTRAFIELDS)) { ?> -trans("Hidden"); ?>> +trans("Hidden"); ?>> global->MAIN_FEATURES_LEVEL >= 2) { ?> diff --git a/htdocs/core/tpl/admin_extrafields_edit.tpl.php b/htdocs/core/tpl/admin_extrafields_edit.tpl.php index b6c43b10ce9..6f049c506a3 100644 --- a/htdocs/core/tpl/admin_extrafields_edit.tpl.php +++ b/htdocs/core/tpl/admin_extrafields_edit.tpl.php @@ -15,6 +15,16 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ + +/** + * The following vars must be defined: + * $type2label + * $form + * $conf, $lang, + * The following vars may also be defined: + * $elementtype + */ + ?> @@ -24,9 +34,10 @@ { console.log("select new type "+type); var size = jQuery("#size"); + var computed_value = jQuery("#computed_value"); + var default_value = jQuery("#default_value"); var unique = jQuery("#unique"); var required = jQuery("#required"); - var default_value = jQuery("#default_value"); var alwayseditable = jQuery("#alwayseditable"); var list = jQuery("#list"); + // Case of computed field + if (type == 'varchar' || type == 'int' || type == 'double' || type == 'price') { + jQuery("tr.extra_computed_value").show(); + } else { + computed_value.val(''); jQuery("tr.extra_computed_value").hide(); + } + if (computed_value.val()) + { + console.log("We enter a computed formula"); + jQuery("#default_value").val(''); + /* jQuery("#unique, #required, #alwayseditable, #ishidden, #list").removeAttr('checked'); */ + jQuery("#default_value, #unique, #required, #alwayseditable, #ishidden, #list").attr('disabled', true); + jQuery("tr.extra_default_value, tr.extra_unique, tr.extra_required, tr.extra_alwayseditable, tr.extra_ishidden, tr.extra_list").hide(); + } + else + { + console.log("No computed formula"); + jQuery("#default_value, #unique, #required, #alwayseditable, #ishidden, #list").attr('disabled', false); + jQuery("tr.extra_default_value, tr.extra_unique, tr.extra_required, tr.extra_alwayseditable, tr.extra_ishidden, tr.extra_list").show(); + } + if (type == 'date') { size.val('').prop('disabled', true); unique.removeAttr('disabled'); jQuery("#value_choice").hide();jQuery("#helpchkbxlst").hide(); } else if (type == 'datetime') { size.val('').prop('disabled', true); unique.removeAttr('disabled'); jQuery("#value_choice").hide(); jQuery("#helpchkbxlst").hide();} else if (type == 'double') { size.removeAttr('disabled'); unique.removeAttr('disabled'); jQuery("#value_choice").hide(); jQuery("#helpchkbxlst").hide();} @@ -65,9 +97,11 @@ if (type == 'separate') { required.removeAttr('checked').prop('disabled', true); alwayseditable.removeAttr('checked').prop('disabled', true); list.val('').prop('disabled', true); + jQuery('#size, #default_value').val('').prop('disabled', true); } else { + default_value.removeAttr('disabled'); required.removeAttr('disabled'); alwayseditable.removeAttr('disabled'); list.val('').removeAttr('disabled'); } } @@ -75,6 +109,11 @@ jQuery("#type").change(function() { init_typeoffields($(this).val()); }); + + // If we enter a formula, we disable other fields + jQuery("#computed_value").keyup(function() { + init_typeoffields(jQuery('#type').val()); + }); }); @@ -92,6 +131,8 @@ attribute_type[$attrname]; $size=$extrafields->attribute_size[$attrname]; +$computed=$extrafields->attribute_computed[$attrname]; +$default=$extrafields->attribute_default[$attrname]; $unique=$extrafields->attribute_unique[$attrname]; $required=$extrafields->attribute_required[$attrname]; $pos=$extrafields->attribute_pos[$attrname]; @@ -156,9 +197,7 @@ else ?> -trans("Size"); ?> - -trans("Position"); ?> +trans("Size"); ?> @@ -177,12 +216,18 @@ else + +trans("Position"); ?> + +textwithpicto($langs->trans("ComputedFormula"), $langs->trans("ComputedFormulaDesc"), 1, 'help', '', 0, 2, 'tooltipcompute'); ?> + + -trans("Unique"); ?>> +trans("Unique"); ?>> -trans("Required"); ?>> +trans("Required"); ?>> -trans("AlwaysEditable"); ?>> +trans("AlwaysEditable"); ?>> global->MAIN_CAN_HIDE_EXTRAFIELDS)) { ?> trans("Hidden"); ?>> diff --git a/htdocs/core/tpl/admin_extrafields_view.tpl.php b/htdocs/core/tpl/admin_extrafields_view.tpl.php index 3242a388a3d..a6d7e735735 100644 --- a/htdocs/core/tpl/admin_extrafields_view.tpl.php +++ b/htdocs/core/tpl/admin_extrafields_view.tpl.php @@ -37,12 +37,15 @@ print '
        '; print ''; print ''; -print ''; +print ''; print ''; print ''; print ''; print ''; print ''; +print ''; print ''; print ''; if (! empty($conf->global->MAIN_CAN_HIDE_EXTRAFIELDS)) print ''; @@ -61,6 +64,7 @@ if (count($extrafields->attribute_type)) print "\n"; print '\n"; print '\n"; + print '\n"; print '\n"; print '\n"; if (! empty($conf->global->MAIN_CAN_HIDE_EXTRAFIELDS)) print '\n"; // Add hidden option on not working feature. Why hide if user can't see it. diff --git a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql index 6c71f279867..f7ed5b7575b 100644 --- a/htdocs/install/mysql/migration/5.0.0-6.0.0.sql +++ b/htdocs/install/mysql/migration/5.0.0-6.0.0.sql @@ -34,6 +34,10 @@ -- VMYSQL4.3 ALTER TABLE llx_opensurvey_sondage MODIFY COLUMN date_fin DATETIME NULL DEFAULT NULL; -- VPGSQL8.2 ALTER TABLE llx_opensurvey_sondage ALTER COLUMN date_fin DROP NOT NULL; + +ALTER TABLE llx_extrafields ADD COLUMN fieldcomputed text; +ALTER TABLE llx_extrafields ADD COLUMN fielddefault varchar(255); + ALTER TABLE llx_opensurvey_sondage MODIFY COLUMN tms timestamp DEFAULT CURRENT_TIMESTAMP; ALTER TABLE llx_opensurvey_sondage ADD COLUMN fk_user_creat integer NOT NULL DEFAULT 0; @@ -251,7 +255,6 @@ ALTER TABLE llx_product_fournisseur_price_log ADD COLUMN multicurrency_tx d ALTER TABLE llx_product_fournisseur_price_log ADD COLUMN multicurrency_price double(24,8) DEFAULT NULL; ALTER TABLE llx_product_fournisseur_price_log ADD COLUMN multicurrency_price_ttc double(24,8) DEFAULT NULL; - create table llx_payment_various ( rowid integer AUTO_INCREMENT PRIMARY KEY, diff --git a/htdocs/install/mysql/tables/llx_extrafields.sql b/htdocs/install/mysql/tables/llx_extrafields.sql index 2cc144db092..aee51524e6f 100644 --- a/htdocs/install/mysql/tables/llx_extrafields.sql +++ b/htdocs/install/mysql/tables/llx_extrafields.sql @@ -21,12 +21,14 @@ create table llx_extrafields ( rowid integer AUTO_INCREMENT PRIMARY KEY, name varchar(64) NOT NULL, -- name of field into extrafields tables - entity integer DEFAULT 1 NOT NULL, -- multi company id - elementtype varchar(64) NOT NULL DEFAULT 'member', -- for which element this extra fields is for + entity integer DEFAULT 1 NOT NULL, -- multi company id + elementtype varchar(64) NOT NULL DEFAULT 'member', -- for which element this extra fields is for tms timestamp, -- date of last update label varchar(255) NOT NULL, -- label to show for attribute type varchar(8), size varchar(8) DEFAULT NULL, + fieldcomputed text, + fielddefault varchar(255), fieldunique integer DEFAULT 0, fieldrequired integer DEFAULT 0, perms varchar(255), -- not used yet diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang index d25a97c28e5..fe547931908 100644 --- a/htdocs/langs/en_US/admin.lang +++ b/htdocs/langs/en_US/admin.lang @@ -375,19 +375,21 @@ Int=Integer Float=Float DateAndTime=Date and hour Unique=Unique -Boolean=Boolean (Checkbox) +Boolean=Boolean (one checkbox) ExtrafieldPhone = Phone ExtrafieldPrice = Price ExtrafieldMail = Email ExtrafieldUrl = Url ExtrafieldSelect = Select list ExtrafieldSelectList = Select from table -ExtrafieldSeparator=Separator +ExtrafieldSeparator=Separator (not a field) ExtrafieldPassword=Password -ExtrafieldCheckBox=Checkbox -ExtrafieldRadio=Radio button -ExtrafieldCheckBoxFromList= Checkbox from table +ExtrafieldRadio=Radio buttons (on choice only) +ExtrafieldCheckBox=Checkboxes +ExtrafieldCheckBoxFromList=Checkboxes from table ExtrafieldLink=Link to an object +ComputedFormula=Computed field +ComputedFormulaDesc=You can enter here a formula using other properties of object or any PHP coding to get a dynamic computed value. You can use any PHP compatible formulas including the "?" condition operator, and following global object: $db, $conf, $langs, $mysoc, $user, $object.
        WARNING: Only some properties of $object may be available. If you need a properties not loaded, just fetch yourself the object into your formula like in the second example.
        Using a computed field means you can't enter yourself any value from interface. Also, if there is a syntax error, the formula may return nothing.

        Example of formula:
        $object->id < 5 ? round($object->id / 2, 2) : ($object->id + 2*$user->id) * (int) substr($mysoc->zip, 1, 2)

        Example of formula to force load of object and its parent object:
        (($reloadedobj = new Task($db)) && ($reloadedobj->fetch($object->id) > 0) && ($secondloadedobj = new Project($db)) && ($secondloadedobj->fetch($reloadedobj->fk_project) > 0)) ? $secondloadedobj->ref : 'Parent project not found'

        Other example to reload object
        (($reloadedobj = new Societe($db)) && ($reloadedobj->fetch($obj->id ? $obj->id : ($obj->rowid ? $obj->rowid : $object->id)) > 0)) ? round($reloadedobj->capital / 5) : '-1' ExtrafieldParamHelpselect=Parameters list have to be like key,value

        for example :
        1,value1
        2,value2
        3,value3
        ...

        In order to have the list depending on another complementary attribute list :
        1,value1|options_parent_list_code:parent_key
        2,value2|options_parent_list_code:parent_key

        In order to have the list depending on another list :
        1,value1|parent_list_code:parent_key
        2,value2|parent_list_code:parent_key ExtrafieldParamHelpcheckbox=Parameters list have to be like key,value

        for example :
        1,value1
        2,value2
        3,value3
        ... ExtrafieldParamHelpradio=Parameters list have to be like key,value

        for example :
        1,value1
        2,value2
        3,value3
        ... diff --git a/htdocs/langs/en_US/main.lang b/htdocs/langs/en_US/main.lang index 77b5af78f81..a170bc3f6e1 100644 --- a/htdocs/langs/en_US/main.lang +++ b/htdocs/langs/en_US/main.lang @@ -773,6 +773,7 @@ BulkActions=Bulk actions ClickToShowHelp=Click to show tooltip help HR=HR HRAndBank=HR and Bank +AutomaticallyCalculated=Automatically calculated # Week day Monday=Monday Tuesday=Tuesday diff --git a/htdocs/modulebuilder/skeletons/skeleton_list.php b/htdocs/modulebuilder/skeletons/skeleton_list.php index 9c258162759..47aeda79fdc 100644 --- a/htdocs/modulebuilder/skeletons/skeleton_list.php +++ b/htdocs/modulebuilder/skeletons/skeleton_list.php @@ -126,13 +126,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab } -// Load object if id or ref is provided as parameter $object=new Skeleton_Class($db); -if (($id > 0 || ! empty($ref)) && $action != 'add') -{ - $result=$object->fetch($id,$ref); - if ($result < 0) dol_print_error($db); -} @@ -354,7 +348,9 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab if (! empty($arrayfields["ef.".$key]['checked'])) { $align=$extrafields->getAlignFlag($key); - print_liste_field_titre($langs->trans($extralabels[$key]),$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($langs->trans($extralabels[$key]),$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); } } } @@ -383,7 +379,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab $align=$extrafields->getAlignFlag($key); $typeofextrafield=$extrafields->attribute_type[$key]; print ''; print ''."\n"; +// Detect if we need a fetch on each output line +$needToFetchEachLine=0; +foreach ($extrafields->attribute_computed as $key => $val) +{ + if (preg_match('/\$object/',$val)) $needToFetchEachLine++; // There is at least one compute field that use $object +} + + $i=0; $totalarray=array(); while ($i < min($num, $limit)) diff --git a/htdocs/projet/list.php b/htdocs/projet/list.php index 6230626a320..b327573e3db 100644 --- a/htdocs/projet/list.php +++ b/htdocs/projet/list.php @@ -141,6 +141,8 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab } } +$object = new Project($db); + /* * Actions @@ -200,7 +202,6 @@ if (empty($reshook)) * View */ -$projectstatic = new Project($db); $socstatic = new Societe($db); $form = new Form($db); $formother = new FormOther($db); @@ -212,12 +213,12 @@ $title=$langs->trans("Projects"); // Get list of project id allowed to user (in a string list separated by coma) $projectsListId=''; -if (! $user->rights->projet->all->lire) $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,1,$socid); +if (! $user->rights->projet->all->lire) $projectsListId = $object->getProjectsAuthorizedForUser($user,0,1,$socid); // Get id of types of contacts for projects (This list never contains a lot of elements) $listofprojectcontacttype=array(); $sql = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc"; -$sql.= " WHERE ctc.element = '" . $projectstatic->element . "'"; +$sql.= " WHERE ctc.element = '" . $object->element . "'"; $sql.= " AND ctc.source = 'internal'"; $resql = $db->query($sql); if ($resql) @@ -232,7 +233,7 @@ if (count($listofprojectcontacttype) == 0) $listofprojectcontacttype[0]='0'; $distinct='DISTINCT'; // We add distinct until we are added a protection to be sure a contact of a project and task is only once. -$sql = "SELECT ".$distinct." p.rowid as projectid, p.ref, p.title, p.fk_statut, p.fk_opp_status, p.public, p.fk_user_creat"; +$sql = "SELECT ".$distinct." p.rowid as id, p.ref, p.title, p.fk_statut, p.fk_opp_status, p.public, p.fk_user_creat"; $sql.= ", p.datec as date_creation, p.dateo as date_start, p.datee as date_end, p.opp_amount, p.opp_percent, p.tms as date_update, p.budget_amount"; $sql.= ", s.nom as name, s.rowid as socid"; $sql.= ", cls.code as opp_status_code"; @@ -360,8 +361,7 @@ $arrayofselected=is_array($toselect)?$toselect:array(); if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { $obj = $db->fetch_object($resql); - $id = $obj->projectid; - header("Location: ".DOL_URL_ROOT.'/projet/card.php?id='.$id); + header("Location: ".DOL_URL_ROOT.'/projet/card.php?id='.$obj->id); exit; } @@ -566,7 +566,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab $align=$extrafields->getAlignFlag($key); $typeofextrafield=$extrafields->attribute_type[$key]; print ''; @@ -632,7 +632,9 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab if (! empty($arrayfields["ef.".$key]['checked'])) { $align=$extrafields->getAlignFlag($key); - print_liste_field_titre($langs->trans($extralabels[$key]),$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($langs->trans($extralabels[$key]),$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); } } } @@ -652,15 +654,15 @@ while ($i < min($num,$limit)) { $obj = $db->fetch_object($resql); - $projectstatic->id = $obj->projectid; - $projectstatic->user_author_id = $obj->fk_user_creat; - $projectstatic->public = $obj->public; - $projectstatic->ref = $obj->ref; - $projectstatic->datee = $db->jdate($obj->date_end); - $projectstatic->statut = $obj->fk_statut; - $projectstatic->opp_status = $obj->fk_opp_status; - - $userAccess = $projectstatic->restrictedProjectArea($user); // why this ? + $object->id = $obj->id; + $object->user_author_id = $obj->fk_user_creat; + $object->public = $obj->public; + $object->ref = $obj->ref; + $object->datee = $db->jdate($obj->date_end); + $object->statut = $obj->fk_statut; + $object->opp_status = $obj->fk_opp_status; + + $userAccess = $object->restrictedProjectArea($user); // why this ? if ($userAccess >= 0) { print ''; @@ -669,8 +671,8 @@ while ($i < min($num,$limit)) if (! empty($arrayfields['p.ref']['checked'])) { print ''; if (! $i) $totalarray['nbfield']++; } @@ -851,8 +853,7 @@ while ($i < min($num,$limit)) // Status if (! empty($arrayfields['p.fk_statut']['checked'])) { - $projectstatic->statut = $obj->fk_statut; - print ''; + print ''; if (! $i) $totalarray['nbfield']++; } // Action column @@ -860,8 +861,8 @@ while ($i < min($num,$limit)) if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { $selected=0; - if (in_array($obj->projectid, $arrayofselected)) $selected=1; - print ''; + if (in_array($obj->id, $arrayofselected)) $selected=1; + print ''; } print ''; if (! $i) $totalarray['nbfield']++; @@ -871,7 +872,6 @@ while ($i < min($num,$limit)) } $i++; - } // Show total line diff --git a/htdocs/projet/tasks/list.php b/htdocs/projet/tasks/list.php index 1f2459e85db..4e31434dbc4 100644 --- a/htdocs/projet/tasks/list.php +++ b/htdocs/projet/tasks/list.php @@ -131,6 +131,8 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab } } +$object = new Task($db); + /* * Actions @@ -190,11 +192,11 @@ if (empty($search_projectstatus) && $search_projectstatus == '') $search_project * View */ +$now = dol_now(); $form=new Form($db); $formother=new FormOther($db); $socstatic=new Societe($db); $projectstatic = new Project($db); -$taskstatic = new Task($db); $puser=new User($db); $tuser=new User($db); if ($search_project_user > 0) $puser->fetch($search_project_user); @@ -231,7 +233,7 @@ if (count($listofprojectcontacttype) == 0) $listofprojectcontacttype[0]='0'; // Get id of types of contacts for tasks (This list never contains a lot of elements) $listoftaskcontacttype=array(); $sql = "SELECT ctc.rowid, ctc.code FROM ".MAIN_DB_PREFIX."c_type_contact as ctc"; -$sql.= " WHERE ctc.element = '" . $taskstatic->element . "'"; +$sql.= " WHERE ctc.element = '" . $object->element . "'"; $sql.= " AND ctc.source = 'internal'"; $resql = $db->query($sql); if ($resql) @@ -549,7 +551,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab $align=$extrafields->getAlignFlag($key); $typeofextrafield=$extrafields->attribute_type[$key]; print ''; if (! $i) $totalarray['nbfield']++; } @@ -665,7 +668,7 @@ while ($i < min($num,$limit)) if (! empty($arrayfields['t.label']['checked'])) { print ''; if (! $i) $totalarray['nbfield']++; } diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index 995c16719cb..ebd06dbd5c4 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -389,8 +389,6 @@ class Societe extends CommonObject $this->forme_juridique_code = 0; $this->tva_assuj = 1; $this->status = 1; - - return 1; } diff --git a/htdocs/societe/list.php b/htdocs/societe/list.php index 48e1b67a69c..51d4b41e6bb 100644 --- a/htdocs/societe/list.php +++ b/htdocs/societe/list.php @@ -831,7 +831,7 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab $align=$extrafields->getAlignFlag($key); $typeofextrafield=$extrafields->attribute_type[$key]; print '
        '.$langs->trans("Position").''.$langs->trans("Position"); +print ''; +print ''.$langs->trans("Label").''.$langs->trans("AttributeCode").''.$langs->trans("Type").''.$langs->trans("Size").''.$langs->trans("Unique").''.$langs->trans("ComputedFormula").''.$langs->trans("Required").''.$langs->trans("AlwaysEditable").''.$langs->trans("Hidden").'".$type2label[$extrafields->attribute_type[$key]]."'.$extrafields->attribute_size[$key]."'.yn($extrafields->attribute_unique[$key])."'.dol_trunc($extrafields->attribute_computed[$key], 20)."'.yn($extrafields->attribute_required[$key])."'.yn($extrafields->attribute_alwayseditable[$key])."'.yn($extrafields->attribute_hidden[$key])."'; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) { $crit=$val; $tmpkey=preg_replace('/search_options_/','',$key); @@ -427,6 +423,14 @@ print '
        '; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) { $crit=$val; $tmpkey=preg_replace('/search_options_/','',$key); @@ -599,7 +599,7 @@ if (! empty($arrayfields['p.fk_statut']['checked'])) { print ''; $arrayofstatus = array(); - foreach($projectstatic->statuts_short as $key => $val) $arrayofstatus[$key]=$langs->trans($val); + foreach($object->statuts_short as $key => $val) $arrayofstatus[$key]=$langs->trans($val); $arrayofstatus['99']=$langs->trans("NotClosed").' ('.$langs->trans('Draft').'+'.$langs->trans('Opened').')'; print $form->selectarray('search_status', $arrayofstatus, $search_status, 1, 0, 0, '', 0, 0, 0, '', 'maxwidth100'); print '
        '; - print $projectstatic->getNomUrl(1); - if ($projectstatic->hasDelay()) print img_warning($langs->trans('Late')); + print $object->getNomUrl(1); + if ($object->hasDelay()) print img_warning($langs->trans('Late')); print ''.$projectstatic->getLibStatut(5).''.$object->getLibStatut(5).''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) { $crit=$val; $tmpkey=preg_replace('/search_options_/','',$key); @@ -606,7 +608,9 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab if (! empty($arrayfields["ef.".$key]['checked'])) { $align=$extrafields->getAlignFlag($key); - print_liste_field_titre($langs->trans($extralabels[$key]),$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($langs->trans($extralabels[$key]),$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); } } } @@ -624,14 +628,21 @@ $plannedworkloadoutputformat='allhourmin'; $timespentoutputformat='allhourmin'; if (! empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) $plannedworkloadoutputformat=$conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT; if (! empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) $timespentoutputformat=$conf->global->PROJECT_TIME_SPENT_FORMAT; - -$now = dol_now(); + $i=0; $totalarray=array(); while ($i < min($num,$limit)) { $obj = $db->fetch_object($resql); + $object->id = $obj->id; + $object->ref = $obj->ref; + $object->label = $obj->label; + $object->fk_statut = $obj->fk_statut; + $object->progress = $obj->progress; + $object->datee = $db->jdate($obj->date_end); // deprecated + $object->date_end = $db->jdate($obj->date_end); + $projectstatic->id = $obj->projectid; $projectstatic->ref = $obj->projectref; $projectstatic->title = $obj->projecttitle; @@ -639,14 +650,6 @@ while ($i < min($num,$limit)) $projectstatic->statut = $obj->projectstatus; $projectstatic->datee = $db->jdate($obj->projectdatee); - $taskstatic->id = $obj->id; - $taskstatic->ref = $obj->ref; - $taskstatic->label = $obj->label; - $taskstatic->fk_statut = $obj->fk_statut; - $taskstatic->progress = $obj->progress; - $taskstatic->datee = $db->jdate($obj->date_end); // deprecated - $taskstatic->date_end = $db->jdate($obj->date_end); - $userAccess = $projectstatic->restrictedProjectArea($user); // why this ? if ($userAccess >= 0) { @@ -656,8 +659,8 @@ while ($i < min($num,$limit)) if (! empty($arrayfields['t.ref']['checked'])) { print ''; - print $taskstatic->getNomUrl(1,'withproject'); - if ($taskstatic->hasDelay()) print img_warning("Late"); + print $object->getNomUrl(1,'withproject'); + if ($object->hasDelay()) print img_warning("Late"); print ''; - print $taskstatic->label; + print $object->label; print ''; - if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select'))) + if (in_array($typeofextrafield, array('varchar', 'int', 'double', 'select')) && empty($extrafields->attribute_computed[$key])) { $crit=$val; $tmpkey=preg_replace('/search_options_/','',$key); @@ -907,7 +907,9 @@ if (is_array($extrafields->attribute_label) && count($extrafields->attribute_lab if (! empty($arrayfields["ef.".$key]['checked'])) { $align=$extrafields->getAlignFlag($key); - print_liste_field_titre($langs->trans($extralabels[$key]),$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); + $sortonfield = "ef.".$key; + if (! empty($extrafields->attribute_computed[$key])) $sortonfield=''; + print_liste_field_titre($langs->trans($extralabels[$key]),$_SERVER["PHP_SELF"],$sortonfield,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder); } } }